"""Charts for the "which check finds the wrong values" lab. Usage: python3 charts-checks.py <out_dir>
Reads checks-by-document.json and typesafe-summary.json beside it."""
import json, os, sys
OUT = sys.argv[1]; H = os.path.dirname(os.path.abspath(__file__))
D = json.load(open(H + '/checks-by-document.json'))['ALL']; T = json.load(open(H + '/typesafe-summary.json'))
F = 'font-family="IBM Plex Sans, Inter, system-ui, sans-serif"'
TEAL, TERRA, S6, S5, S2, W = '#0e7c7b', '#b05525', '#475569', '#64748b', '#e2e8f0', '#ffffff'
def svg(title, desc, body, h=630):
    return (f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 {h}" width="100%" role="img" aria-labelledby="t d"><title id="t">{title}</title><desc id="d">{desc}</desc>'
            f'<rect width="1200" height="{h}" rx="12" fill="{W}"/>{body}</svg>\n')
def txt(x, y, s, size=24, fill=S6, weight='400', anchor='start'):
    return f'<text x="{x}" y="{y}" {F} font-size="{size}" font-weight="{weight}" fill="{fill}" text-anchor="{anchor}">{s}</text>'
# 1. per document: wrong documents caught vs clean documents flagged
checks = [('second_model', 'Second cheap model'), ('typesafe_05', 'TypeSafe, flag below 0.5'), ('typesafe_03', 'TypeSafe, flag below 0.3'), ('arithmetic', 'Arithmetic checks')]
b = txt(48, 66, 'Which check catches the invoices with an error?', 32, S6, '600')
b += f'<rect x="48" y="92" width="22" height="22" rx="4" fill="{TEAL}"/>' + txt(80, 111, 'Invoices with an error that were caught', 21) + f'<rect x="520" y="92" width="22" height="22" rx="4" fill="{TERRA}"/>' + txt(552, 111, 'Clean invoices flagged anyway', 21)
x0, bw = 400, 560; desc = []
for i, (k, lab) in enumerate(checks):
    c = D[k]; y = 150 + i * 106; b += txt(48, y + 46, lab, 24)
    for j, (n, d, fill) in enumerate(((c['caught'], c['docs_with_error'], TEAL), (c['false_flags'], c['clean_docs'], TERRA))):
        yy = y + j * 40; L = bw * n / d
        b += f'<rect x="{x0}" y="{yy}" width="{bw}" height="32" rx="4" fill="{S2}"/><rect x="{x0}" y="{yy}" width="{max(L,2):.1f}" height="32" rx="4" fill="{fill}"/>' + txt(x0 + bw + 14, yy + 24, f'{n} of {d} ({100*n/d:.0f}%)', 21, S6, '600')
    desc.append(f"{lab}: caught {c['caught']} of {c['docs_with_error']}, flagged {c['false_flags']} of {c['clean_docs']} clean")
b += txt(48, 604, '240 extractions of 40 hard invoices by six models; 33 had at least one wrong value. Pondero Labs, December 1, 2026.', 19, S5)
open(OUT + '/checks-by-document.svg', 'w').write(svg('Wrong invoices caught and clean invoices flagged, by check', '; '.join(desc), b))
# 2. TypeSafe catch rate by kind of error
pl = T['planted']['caught_at_0.5_by_type']; re_ = T['real']['caught_at_0.5_by_type']
misfiled = [re_.get(k, {'wrong': 0, 'caught': 0}) for k in ('sales_items_total', 'delivery_charge', 'tax_total', 'pickup_charge')]
rows = [('Planted: value from the wrong column', pl['column_shift']), ('Planted: decimal point moved', pl['magnitude']), ('Planted: day and month swapped', pl['date_swap']),
        ('Planted: two digits swapped in a value', pl['digit_swap']), ('Planted: two digits swapped in an ID', pl['digit_swap_id']),
        ('Real: charge filed in the wrong field', {'wrong': sum(m['wrong'] for m in misfiled), 'caught': sum(m['caught'] for m in misfiled)}),
        ('Real: job number or vendor name', {'wrong': re_['job_number']['wrong'] + re_['vendor_name']['wrong'], 'caught': re_['job_number']['caught'] + re_['vendor_name']['caught']}),
        ('Real: wrong or misread line item', re_['line item'])]
b = txt(48, 62, 'What TypeSafe caught at a 0.5 threshold, by kind of error', 32, S6, '600'); desc = []
for i, (lab, v) in enumerate(rows):
    y = 96 + i * 60; L = 500 * v['caught'] / v['wrong']; fill = TEAL if lab.startswith('Planted') else TERRA
    b += txt(48, y + 34, lab, 22) + f'<rect x="520" y="{y+8}" width="500" height="36" rx="4" fill="{S2}"/><rect x="520" y="{y+8}" width="{max(L,2):.1f}" height="36" rx="4" fill="{fill}"/>' + txt(1034, y + 34, f"{v['caught']} of {v['wrong']}", 21, S6, '600')
    desc.append(f"{lab}: {v['caught']} of {v['wrong']}")
b += txt(48, 606, 'Planted errors were inserted by us into correct extractions; real errors are the models\' own. Pondero Labs, December 1, 2026.', 19, S5)
open(OUT + '/typesafe-by-error-type.svg', 'w').write(svg('TypeSafe catch rate by kind of error', '; '.join(desc), b))
print('\n'.join(desc))
