#!/usr/bin/env python3
"""TypeSafe check, version 2: one yes/no question per NUMBER, plus planted errors.

verify.py asked one compound question per line item ("...quantity Q, day rate D, week rate W,
4-week rate F and amount A?"). TypeSafe's own guidance is to ask atomic questions, so this
version asks about each value on a line separately and takes the lowest probability as the
line's score.

Real extraction errors are scarce (the models are mostly right), so with --plant we also corrupt
about one value in eight of each extraction in a known way and check whether Jev notices:
  digit_swap    two adjacent digits transposed            (4500345838 -> 4500354838)
  column_shift  a neighbouring column copied in           (billed amount := the 4-week rate)
  magnitude     decimal point moved one place             (2557.60 -> 255.76)
  date_swap     day and month exchanged                   (2026-07-04 -> 2026-04-07)
Planted errors are labelled as planted in the output and reported separately from real ones.

Usage:  venv/bin/python verify2.py --run 1 [--plant] [--models a,b] [--only rent-01] [--workers 4]
Output: verify-b2/run<N>[-planted]/<model>/<doc>.json
"""
import argparse, concurrent.futures as cf, copy, json, os, random, re, time
from score import right, ORDER
from score_b import judge, LINEKEY, lkey
from verify import pages, post, FIELD_TEXT, JEV, HERE

ID = {'rental': 'equipment_number', 'paint': 'sales_number', 'screening': 'service_code'}
NUMS = {'rental': [('quantity', 'the quantity'), ('day_rate', 'the day rate'), ('week_rate', 'the week rate'), ('four_week_rate', 'the 4-week rate'), ('amount', 'the billed amount')],
        'paint': [('quantity', 'the quantity'), ('unit_price', 'the price charged per unit (not the list price)'), ('amount', 'the extended price')],
        'screening': [('quantity', 'the quantity'), ('unit_price', 'the unit price'), ('amount', 'the amount')]}
WHAT = {'rental': 'rented equipment number', 'paint': 'product', 'screening': 'service code'}

def swap_digits(s, rng):
    idx = [i for i in range(len(s) - 1) if s[i].isdigit() and s[i + 1].isdigit() and s[i] != s[i + 1]]
    if not idx: return None
    i = rng.choice(idx); return s[:i] + s[i + 1] + s[i] + s[i + 2:]

def plant(family, parsed, items, rng):
    """Corrupt some truly-correct values in place. Returns {path: type}."""
    planted = {}
    ok_hdr = {name for kind, name, exp, got, ok in items if kind == 'header' and ok}
    for f in list(parsed):
        if f in ('lines', 'locations') or f not in ok_hdr or rng.random() > 0.13: continue
        v = parsed[f]; new, typ = None, None
        if isinstance(v, str) and re.fullmatch(r'\d{4}-\d{2}-\d{2}', v):
            y, mo, d = v.split('-')
            if int(d) <= 12 and d != mo: new, typ = f'{y}-{d}-{mo}', 'date_swap'
        elif isinstance(v, str) and f != 'vendor_name' and f != 'invoice_type': new, typ = swap_digits(v, rng), 'digit_swap'
        elif isinstance(v, (int, float)) and not isinstance(v, bool) and abs(v) >= 10:
            if rng.random() < 0.5: new, typ = round(v / 10, 2), 'magnitude'
            else:
                s = swap_digits(f'{v:.2f}', rng); new, typ = (float(s) if s else None), 'digit_swap'
        if new is not None and new != v: parsed[f] = new; planted[('header', f)] = typ
    for i, l in enumerate(parsed.get('lines') or []):
        if not isinstance(l, dict) or rng.random() > 0.13: continue
        r = rng.random()
        if r < 0.4:
            src = {'rental': rng.choice(['four_week_rate', 'week_rate']), 'paint': 'unit_price', 'screening': 'unit_price'}[family]
            if l.get(src) is not None and l.get(src) != l.get('amount'): l['amount'] = l[src]; planted[('line', i)] = 'column_shift'
        elif r < 0.7:
            s = swap_digits(f"{l.get('amount', 0):.2f}", rng)
            if s and float(s) != l.get('amount'): l['amount'] = float(s); planted[('line', i)] = 'digit_swap'
        else:
            s = swap_digits(str(l.get(ID[family], '')), rng)
            if s: l[ID[family]] = s; planted[('line', i)] = 'digit_swap_id'
    return planted

def build(family, parsed, imgs):
    state = {f'page_{i+1}': f'pg-asset-{i+1:02d}-x' for i in range(len(imgs))}
    assets = {f'pg-asset-{i+1:02d}-x': {'type': 'image', 'format': 'jpg', 'data_base64': b} for i, b in enumerate(imgs)}
    qs, meta = {}, {}
    def ask(qid, text, m): qs[qid] = {'type': 'noul', 'instructions': text}; meta[qid] = m
    for f, v in parsed.items():
        if f in ('lines', 'locations') or f not in FIELD_TEXT: continue
        if v is None: t = f"Is it true that the invoice pages do not show {FIELD_TEXT[f].split(' (')[0]}?"
        elif isinstance(v, (int, float)) and v == 0 and f != 'tax_total': t = f"Is it true that {FIELD_TEXT[f]} is zero or not charged on this invoice?"
        else: t = f"Is {json.dumps(v)} {FIELD_TEXT[f]} printed on this invoice?"
        ask(f'h_{f}', t, ('header', f))
    for i, l in enumerate(parsed.get('lines') or []):
        if not isinstance(l, dict): continue
        ident = l.get(ID[family]); who = f"{WHAT[family]} {ident}" + (f" in colour {l.get('color_code')}" if family == 'paint' and l.get('color_code') else '')
        ask(f'l{i}_exists', f"Does the invoice list {who}?", ('line', i))
        for f, label in NUMS[family]:
            ask(f'l{i}_{f}', f"On the invoice line for {who}, is {l.get(f)} {label}?", ('line', i))
    for i, l in enumerate(parsed.get('locations') or []):
        if isinstance(l, dict): ask(f'c{i}', f"Does the charges-by-location table show location code {l.get('location_code')} with an amount of {l.get('amount')}?", ('location', i))
    return {'model': JEV, 'state': state, 'assets': assets, 'questions': qs}, meta

def one(key, a, model, doc_id, outdir):
    src = os.path.join(HERE, 'results-b', 'run' + a.run, model, doc_id + '.json'); dst = os.path.join(outdir, model, doc_id + '.json')
    if not os.path.exists(src): return 'nosrc'
    if os.path.exists(dst) and not json.load(open(dst)).get('error'): return 'skip'
    parsed = json.load(open(src)).get('parsed')
    rec = dict(model=model, doc=doc_id, run=a.run, planted=bool(a.plant), checks=[], usage=None, seconds=None, error=None)
    if not isinstance(parsed, dict): rec['error'] = 'no parsed extraction'
    else:
        k = key[doc_id]; fam = k['family']; parsed = copy.deepcopy(parsed)
        items, _ = judge(fam, k['truth'], parsed)
        planted = plant(fam, parsed, items, random.Random(f'{model}/{doc_id}/{a.run}')) if a.plant else {}
        body, meta = build(fam, parsed, pages(doc_id)); t = time.time()
        try:
            resp = post(body); rec['seconds'] = round(time.time() - t, 2); rec['usage'] = resp.get('usage')
            items, _ = judge(fam, k['truth'], parsed)
            hdr_ok = {name: ok for kind, name, exp, got, ok in items if kind == 'header'}
            tl = {lkey(l, LINEKEY[fam]): l for l in k['truth']['lines']}; tc = {lkey(l, ('location_code',)): l for l in k['truth'].get('locations', [])}
            agg = {}
            for qid, m in meta.items():
                p = (resp['answers'].get(qid) or {}).get('noul')
                if p is not None: agg.setdefault(m, []).append(p)
            for (kind, ref), ps in agg.items():
                if kind == 'header': ok, name, val = hdr_ok.get(ref, False), ref, parsed.get(ref)
                elif kind == 'line':
                    l = parsed['lines'][ref]; t_ = tl.get(lkey(l, LINEKEY[fam])); ok = bool(t_) and all(right(f, v, l.get(f)) for f, v in t_.items()); name, val = 'line', l
                else:
                    l = parsed['locations'][ref]; t_ = tc.get(lkey(l, ('location_code',))); ok = bool(t_) and all(right(f, v, l.get(f)) for f, v in t_.items()); name, val = 'location', l
                rec['checks'].append(dict(kind=kind, name=name, value=val, really_correct=bool(ok), p_yes=min(ps), questions=len(ps), planted=planted.get((kind, ref))))
        except Exception as ex: rec['error'] = str(ex)[:400]
    os.makedirs(os.path.dirname(dst), exist_ok=True); json.dump(rec, open(dst, 'w'), indent=1)
    return 'err' if rec['error'] else 'ok'

def main():
    ap = argparse.ArgumentParser(); ap.add_argument('--run', default='1'); ap.add_argument('--plant', action='store_true'); ap.add_argument('--models'); ap.add_argument('--only'); ap.add_argument('--workers', type=int, default=4)
    a = ap.parse_args()
    key = json.load(open(os.path.join(HERE, 'answer-key-b.json')))
    models = a.models.split(',') if a.models else ORDER
    docs = [d for d in sorted(key) if not a.only or d in a.only.split(',')]
    outdir = os.path.join(HERE, 'verify-b2', 'run' + a.run + ('-planted' if a.plant else ''))
    for m in models:
        with cf.ThreadPoolExecutor(a.workers) as ex: res = list(ex.map(lambda d: one(key, a, m, d, outdir), docs))
        print(m, {x: res.count(x) for x in sorted(set(res))}, flush=True)

if __name__ == '__main__':
    main()
