#!/usr/bin/env python3
"""Summarise the TypeSafe checks: how many wrong values a low probability catches, and at what false-alarm cost.
Usage: venv/bin/python analyze_verify.py verify-b2/run1 [verify-b2/run1-planted ...]"""
import glob, json, sys, collections
def load(d):
    C, tok, n, err, secs = [], 0, 0, 0, []
    for f in glob.glob(d + '/*/*.json'):
        r = json.load(open(f))
        if r.get('error'): err += 1; continue
        n += 1; tok += r['usage']['input_tokens']; secs.append(r['seconds'])
        for c in r['checks']:
            if c['p_yes'] is not None: C.append(dict(c, model=r['model'], doc=r['doc']))
    return C, tok, n, err, secs
for d in sys.argv[1:]:
    C, tok, n, err, secs = load(d)
    right = [c['p_yes'] for c in C if c['really_correct']]; wrong = [c for c in C if not c['really_correct']]
    print(f'\n== {d}: {n} requests ({err} failed), {len(C)} values, {len(wrong)} wrong, {tok:,} tokens = ${tok*0.042/1e6:.3f}, median {sorted(secs)[len(secs)//2]}s')
    if not wrong: continue
    auc = sum((w['p_yes'] < r) + 0.5 * (w['p_yes'] == r) for w in wrong for r in right) / (len(wrong) * len(right))
    print(f'   AUROC {auc:.3f}')
    for th in (0.3, 0.5, 0.7, 0.9):
        c = sum(1 for w in wrong if w['p_yes'] < th); fa = sum(1 for p in right if p < th)
        print(f'   flag p<{th}: catches {c}/{len(wrong)} ({100*c/len(wrong):.0f}%) | false alarms {fa}/{len(right)} ({100*fa/len(right):.1f}%)')
    for label, keyf in (('by kind', lambda w: w['kind']), ('by planted type', lambda w: w.get('planted') or 'real')):
        g = collections.defaultdict(list)
        for w in wrong: g[keyf(w)].append(w['p_yes'])
        print('   ' + label + ': ' + '; '.join(f"{k} {sum(1 for p in v if p < 0.5)}/{len(v)} caught at 0.5" for k, v in sorted(g.items())))
