"""Number trace: find every number in the AI text in the table it cites.
Usage: python trace_numbers.py csr_tables_excerpt.txt csr_output.txt
Checks that each number exists in the cited table (not that it sits in the right cell; that was read by hand).
"""
import re, sys, collections

NUM = re.compile(r'-?\d+(?:\.\d+)?')
ex = open(sys.argv[1], encoding='utf-8').read()
out = open(sys.argv[2], encoding='utf-8').read()

blocks, cur = {}, None
for ln in ex.split('\n'):
    m = re.match(r'\[CSR Table (\d+-\d+\.\d+)', ln)
    if m:
        cur = m.group(1); blocks[cur] = ln + '\n'
    elif cur:
        blocks[cur] += ln + '\n'
alltoks = set()
for b in blocks.values():
    alltoks |= set(NUM.findall(b))


def clean(s):
    s = re.sub(r'\[Table [^\]]+\]', ' ', s)
    s = re.sub(r'Week \d+', 'Week', s)
    s = re.sub(r'\(11\)|\(14\)', ' ', s)
    return re.sub(r'95%|CSR|ITT', ' ', s)


c = collections.Counter()
for ln in out.split('\n'):
    s = ln.strip()
    if not s or s.startswith('- ') or s.isupper():
        continue
    for part in re.findall(r'.*?\[Table [^\]]+\]\.?|.+$', s):
        cites = re.findall(r'\[Table ([^\]]+)\]', part)
        allowed = set()
        for t in cites:
            allowed |= set(NUM.findall(blocks.get(t, '')))
        allowed = allowed if cites else alltoks
        for n in NUM.findall(clean(part)):
            st = 'FOUND' if n in allowed else ('THRESHOLD' if n in ('0.05', '0.15') else 'NOT FOUND')
            c[st] += 1
            if st != 'FOUND':
                print(st, n, '|', part[:80])
print(dict(c), 'total', sum(c.values()))
