#!/usr/bin/env python3
"""Which invoices need a human look? Compare three ways of flagging an extraction, per document:
  arithmetic  - free: do the line amounts add up to the subtotal, and does qty x unit price = amount?
  second model- run a second cheap model (claude-haiku-5-5, or gpt-6-luna when checking haiku) and flag any disagreement
  typesafe    - flag if Jev gives any value a probability below the threshold (verify-b2/run<N>)
A document "has an error" when score_b.py says it is not perfect.
Usage: venv/bin/python baselines.py [run]   -> baselines.json + table"""
import json, os, sys, glob
from score import right
from score_b import judge, LINEKEY, lkey, HERE
run = sys.argv[1] if len(sys.argv) > 1 else '1'
key = json.load(open(os.path.join(HERE, 'answer-key-b.json')))
MODELS = ['gemini-4-hydrogen', 'claude-sonnet-5-5', 'gpt-6.2-sol', 'claude-haiku-5-5', 'gpt-6-luna', 'gemini-3.5-flash-lite']
SUB = {'rental': 'rental_subtotal', 'paint': 'subtotal', 'screening': 'services_subtotal'}
def get(m, d):
    p = os.path.join(HERE, 'results-b', 'run' + run, m, d + '.json')
    return (json.load(open(p)).get('parsed') or {}) if os.path.exists(p) else {}
def arithmetic(fam, p):
    try:
        lines = p.get('lines') or []
        if abs(sum(l['amount'] for l in lines) - p[SUB[fam]]) > 0.011: return True
        if fam in ('paint', 'screening') and any(abs(l['quantity'] * l['unit_price'] - l['amount']) > 0.011 for l in lines): return True
        if fam == 'screening' and abs(sum(l['amount'] for l in p.get('locations') or []) - p[SUB[fam]]) > 0.011: return True
        return False
    except Exception: return True
def disagree(fam, a, b):
    items, sp = judge(fam, {k: v for k, v in a.items()}, b) if a.get('lines') is not None else ([], 1)
    return sp > 0 or any(not ok for *_, ok in items) or len(a.get('lines') or []) != len(b.get('lines') or [])
def jev(m, d, th):
    p = os.path.join(HERE, 'verify-b2', 'run' + run, m, d + '.json')
    if not os.path.exists(p): return None
    return any(c['p_yes'] is not None and c['p_yes'] < th for c in json.load(open(p))['checks'])
out = {}
print('extractor'.ljust(20), 'docs wrong'.rjust(10), '| check'.ljust(22), 'caught'.rjust(8), 'false flags'.rjust(12), 'flagged %'.rjust(10))
tot = {}
for m in MODELS:
    other = 'gpt-6-luna' if m == 'claude-haiku-5-5' else 'claude-haiku-5-5'
    rows = []
    for d, k in key.items():
        p = get(m, d); items, sp = judge(k['family'], k['truth'], p); bad = sp > 0 or any(not ok for *_, ok in items)
        rows.append(dict(bad=bad, arithmetic=arithmetic(k['family'], p), second_model=disagree(k['family'], p, get(other, d)), typesafe_05=jev(m, d, 0.5), typesafe_03=jev(m, d, 0.3)))
    nb = sum(r['bad'] for r in rows); out[m] = {'docs': len(rows), 'docs_with_error': nb}
    for c in ('arithmetic', 'second_model', 'typesafe_03', 'typesafe_05'):
        caught = sum(1 for r in rows if r['bad'] and r[c]); ff = sum(1 for r in rows if not r['bad'] and r[c]); fl = sum(1 for r in rows if r[c])
        out[m][c] = dict(caught=caught, false_flags=ff, flagged=fl)
        t = tot.setdefault(c, [0, 0, 0, 0, 0]); t[0] += caught; t[1] += nb; t[2] += ff; t[3] += len(rows) - nb; t[4] += fl
        print(m.ljust(20), str(nb).rjust(10), ('| ' + c).ljust(22), f'{caught}/{nb}'.rjust(8), f'{ff}/{len(rows)-nb}'.rjust(12), f'{100*fl/len(rows):.0f}%'.rjust(10))
print()
for c, t in tot.items(): print('ALL'.ljust(20), str(t[1]).rjust(10), ('| ' + c).ljust(22), f'{t[0]}/{t[1]}'.rjust(8), f'{t[2]}/{t[3]}'.rjust(12), f'{100*t[4]/(t[1]+t[3]):.0f}%'.rjust(10))
out['ALL'] = {c: dict(caught=t[0], docs_with_error=t[1], false_flags=t[2], clean_docs=t[3], flagged=t[4]) for c, t in tot.items()}
json.dump(out, open(os.path.join(HERE, f'baselines-run{run}.json'), 'w'), indent=1)
