#!/usr/bin/env python3
"""Score the extraction runs against answer-key.json.

A field is right only if it matches the key after light normalisation:
  text    - case, spacing and punctuation ignored
  numbers - within 0.005
  dates   - exact YYYY-MM-DD (a time of day after the right date is accepted)
  governing_law - the key's jurisdiction must appear in the answer ("the State of New York" == "New York")
A document is "perfect" when every field is right. That is the number that matters for
touchless processing: one wrong field means a person has to open the document anyway.

Usage:  venv/bin/python score.py   -> results.csv (one row per model/run/doc/field), summary.json, prints tables
"""
import csv, glob, json, os, re, statistics as st, unicodedata

HERE = os.path.dirname(os.path.abspath(__file__))
# USD per 1M tokens, standard tier, from each vendor's pricing page on 2026-12-01 (copies in pricing/)
PRICE = {'gpt-6.2-sol': (2.00, 10.00), 'gpt-6-luna': (0.10, 0.50), 'gemini-4-hydrogen': (1.50, 7.50), 'gemini-3.5-flash-lite': (0.30, 2.50),
         'claude-sonnet-5-5': (2.00, 10.00), 'claude-haiku-5-5': (0.10, 0.50)}
ORDER = list(PRICE)

def norm(s):
    s = unicodedata.normalize('NFKC', str(s)).casefold()
    return re.sub(r'[^0-9a-zÀ-ɏ]+', '', s)

def law_key(s):
    s = unicodedata.normalize('NFKC', str(s)).casefold()
    s = re.sub(r'\b(the|state|province|commonwealth|laws?|of)\b', ' ', s)
    return re.sub(r'[^a-z]+', ' ', s).strip()

def right(field, truth, got):
    if truth is None: return got is None
    if got is None: return False
    if isinstance(truth, bool): return got is truth
    if isinstance(truth, (int, float)) and not isinstance(truth, bool):
        try: return abs(float(got) - float(truth)) < 0.005
        except Exception: return False
    if field == 'governing_law': return law_key(truth) in law_key(got)
    if isinstance(truth, str) and re.fullmatch(r'\d{4}-\d{2}-\d{2}', truth):
        # dates must match exactly; a time of day appended to the right date ("2026-09-02 07:00") is accepted
        g = str(got).strip(); return g[:10] == truth and (len(g) == 10 or g[10] in ' T')
    return norm(got) == norm(truth)

def main():
    key = json.load(open(os.path.join(HERE, 'answer-key.json')))
    rows, calls = [], []
    for path in sorted(glob.glob(os.path.join(HERE, 'results', 'run[0-9]*', '*', '*.json'))):
        r = json.load(open(path)); run = path.split(os.sep)[-3].replace('run', '')
        k = key[r['doc']]; parsed = r.get('parsed') or {}
        ok_all = True
        for f, t in k['truth'].items():
            g = parsed.get(f) if isinstance(parsed, dict) else None
            ok = bool(r.get('parsed')) and right(f, t, g)
            ok_all &= ok
            rows.append(dict(run=run, model=r['model'], doc=r['doc'], kind=k['kind'], tier=k['tier'], trap=k['trap'], scanned='yes' if k['scanned'] else 'no',
                             field=f, expected=json.dumps(t, ensure_ascii=False), got=json.dumps(g, ensure_ascii=False), correct=int(ok)))
        u = r.get('usage') or {}
        pin, pout = PRICE[r['model']]
        calls.append(dict(run=run, model=r['model'], doc=r['doc'], kind=k['kind'], tier=k['tier'], trap=k['trap'], perfect=int(ok_all), error=r.get('error') or '',
                          seconds=r.get('seconds'), input_tokens=u.get('input_tokens', 0), output_tokens=u.get('output_tokens', 0),
                          cost_usd=round((u.get('input_tokens', 0) * pin + u.get('output_tokens', 0) * pout) / 1e6, 6)))
    with open(os.path.join(HERE, 'results.csv'), 'w', newline='') as f:
        w = csv.DictWriter(f, fieldnames=list(rows[0])); w.writeheader(); w.writerows(rows)
    with open(os.path.join(HERE, 'calls.csv'), 'w', newline='') as f:
        w = csv.DictWriter(f, fieldnames=list(calls[0])); w.writeheader(); w.writerows(calls)

    summary = {}
    for m in ORDER:
        mr = [x for x in rows if x['model'] == m]; mc = [x for x in calls if x['model'] == m]
        if not mc: continue
        def acc(xs): return round(100 * sum(x['correct'] for x in xs) / len(xs), 1) if xs else None
        def perf(xs): return round(100 * sum(x['perfect'] for x in xs) / len(xs), 1) if xs else None
        runs = sorted({x['run'] for x in mc})
        secs = [x['seconds'] for x in mc if x['seconds']]
        summary[m] = dict(
            calls=len(mc), runs=runs, errors=sum(1 for x in mc if x['error']),
            field_accuracy=acc(mr), perfect_docs=perf(mc),
            perfect_by_run={r: perf([x for x in mc if x['run'] == r]) for r in runs},
            perfect_invoice_clean=perf([x for x in mc if x['kind'] == 'invoice' and x['tier'] == 'clean']),
            perfect_invoice_scan=perf([x for x in mc if x['kind'] == 'invoice' and x['tier'] == 'scan']),
            perfect_invoice_trap=perf([x for x in mc if x['kind'] == 'invoice' and x['tier'] == 'trap']),
            perfect_contract=perf([x for x in mc if x['kind'] == 'contract']),
            wrong_fields=sum(1 - x['correct'] for x in mr),
            wrong_by_field={f: n for f, n in sorted(((f, sum(1 - x['correct'] for x in mr if x['field'] == f)) for f in {x['field'] for x in mr}), key=lambda t: -t[1]) if n},
            wrong_by_trap={t: n for t, n in sorted(((t, sum(1 - x['perfect'] for x in mc if x['trap'] == t)) for t in {x['trap'] for x in mc if x['trap']}), key=lambda t: -t[1]) if n},
            median_seconds=round(st.median(secs), 1) if secs else None, p90_seconds=round(sorted(secs)[int(len(secs) * 0.9) - 1], 1) if secs else None,
            avg_input_tokens=round(st.mean(x['input_tokens'] for x in mc)), avg_output_tokens=round(st.mean(x['output_tokens'] for x in mc)),
            cost_per_1000_docs=round(1000 * st.mean(x['cost_usd'] for x in mc), 2), total_cost=round(sum(x['cost_usd'] for x in mc), 3))
    # docs where both runs of the same model disagree on any field
    for m in summary:
        by = {}
        for x in rows:
            if x['model'] == m: by.setdefault((x['doc'], x['field']), {})[x['run']] = x['got']
        summary[m]['fields_differing_between_runs'] = sum(1 for v in by.values() if len(set(v.values())) > 1)
    json.dump(summary, open(os.path.join(HERE, 'summary.json'), 'w'), indent=1)
    cols = ['field_accuracy', 'perfect_docs', 'perfect_invoice_clean', 'perfect_invoice_scan', 'perfect_invoice_trap', 'perfect_contract', 'wrong_fields', 'median_seconds', 'p90_seconds', 'cost_per_1000_docs', 'errors', 'fields_differing_between_runs']
    print('model'.ljust(24) + ' '.join(c[:13].rjust(14) for c in cols))
    for m, s in summary.items(): print(m.ljust(24) + ' '.join(str(s[c]).rjust(14) for c in cols))
    for m, s in summary.items(): print('\n' + m, '\n  by field:', s['wrong_by_field'], '\n  by trap :', s['wrong_by_trap'])
    print('\ntotal spend: $%.2f' % sum(s['total_cost'] for s in summary.values()))

if __name__ == '__main__':
    main()
