#!/usr/bin/env python3
"""Second-opinion check: ask TypeSafe's Jev whether each extracted value matches the invoice.

For every extraction in results-b/run<N>/ we send the page images once and one yes/no (Noul)
question per extracted header field and per extracted line. Jev returns P(yes) for each. We then
know, from the answer key, which values were really right, so we can measure how well a low
probability picks out the wrong ones.

Usage:  TYPESAFE_API_KEY=... venv/bin/python verify.py --run 1 [--models a,b] [--only rent-01] [--workers 4]
Output: verify-b/run<N>/<model>/<doc>.json
"""
import argparse, base64, concurrent.futures as cf, io, json, os, time, urllib.request, urllib.error
import fitz
from PIL import Image
from score_b import judge, LINEKEY, lkey

HERE = os.path.dirname(os.path.abspath(__file__))
JEV = 'jev-1.14.0'
URL = 'https://api.typesafe.ai/v1/systemone'

FIELD_TEXT = {  # what each header field means, in the words used in the extraction prompt
    'vendor_name': 'the legal name of the company that issued this invoice', 'invoice_number': "this invoice's own number", 'invoice_date': 'the invoice date (shown here as YYYY-MM-DD)',
    'rental_agreement_number': 'the rental agreement or contract number', 'po_number': "the buyer's purchase order number", 'job_number': 'the job number',
    'billed_from': 'the start of the billing period (shown here as YYYY-MM-DD)', 'billed_through': 'the end of the billing period (shown here as YYYY-MM-DD)',
    'invoice_type': 'the type of document, where cycle_bill is a recurring 4-week cycle bill, final_return is the invoice issued when equipment is returned and credit is a credit memo',
    'rental_subtotal': 'the rental subtotal', 'rental_protection_plan': 'the rental protection plan charge', 'environmental_charge': 'the environmental charge',
    'delivery_charge': 'the delivery charge', 'pickup_charge': 'the pickup charge', 'sales_items_total': 'the subtotal of sales and miscellaneous items', 'tax_total': 'the total tax', 'total': 'the invoice total',
    'account_number': 'the customer account number', 'subtotal': 'the merchandise subtotal before fees and tax', 'stewardship_fee_total': 'the total paint stewardship fee',
    'customer_account': 'the customer account number', 'billing_period_start': 'the start of the service period (shown here as YYYY-MM-DD)', 'billing_period_end': 'the end of the service period (shown here as YYYY-MM-DD)',
    'services_subtotal': 'the services subtotal', 'program_fee': 'the monthly program or administration fee', 'credits_total': 'the total of credits',
}
LINE_TEXT = {
    'rental': lambda l: f"Does the invoice list rented equipment number {l.get('equipment_number')} with quantity {l.get('quantity')}, day rate {l.get('day_rate')}, week rate {l.get('week_rate')}, 4-week rate {l.get('four_week_rate')} and a billed amount of {l.get('amount')}?",
    'paint': lambda l: f"Does the invoice list product {l.get('sales_number')} " + (f"tinted to colour code {l.get('color_code')}" if l.get('color_code') else 'with no colour code') + f", quantity {l.get('quantity')} of size or unit {l.get('unit')}, at a charged unit price of {l.get('unit_price')} (not the list price) and an extended price of {l.get('amount')}?",
    'screening': lambda l: f"Does the summary of charges list service code {l.get('service_code')} with quantity {l.get('quantity')}, unit price {l.get('unit_price')} and amount {l.get('amount')}?",
}

def pages(doc_id):
    out = []
    for p in fitz.open(os.path.join(HERE, 'docs-b', doc_id + '.pdf')):
        pix = p.get_pixmap(dpi=132)
        im = Image.frombytes('RGB', (pix.width, pix.height), pix.samples); im.thumbnail((1568, 1568))
        b = io.BytesIO(); im.save(b, 'JPEG', quality=88); out.append(base64.b64encode(b.getvalue()).decode())
    return out

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 = {}, {}
    for f, v in parsed.items():
        if f in ('lines', 'locations') or f not in FIELD_TEXT: continue
        qid = f'h_{f}'
        if v is None: text = 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 not in ('tax_total',): text = f"Is it true that {FIELD_TEXT[f]} is zero or not charged on this invoice?"
        else: text = f"Is {json.dumps(v)} {FIELD_TEXT[f]} printed on this invoice?"
        qs[qid] = {'type': 'noul', 'instructions': text}; meta[qid] = ('header', f)
    for i, l in enumerate(parsed.get('lines') or []):
        if not isinstance(l, dict): continue
        qs[f'l_{i}'] = {'type': 'noul', 'instructions': LINE_TEXT[family](l)}; meta[f'l_{i}'] = ('line', i)
    for i, l in enumerate(parsed.get('locations') or []):
        if not isinstance(l, dict): continue
        qs[f'c_{i}'] = {'type': 'noul', 'instructions': f"Does the charges-by-location table show location code {l.get('location_code')} with an amount of {l.get('amount')}?"}; meta[f'c_{i}'] = ('location', i)
    return {'model': JEV, 'state': state, 'assets': assets, 'questions': qs}, meta

def post(body):
    req = urllib.request.Request(URL, data=json.dumps(body).encode(), headers={'Authorization': 'Bearer ' + os.environ['TYPESAFE_API_KEY'], 'Content-Type': 'application/json', 'TypeSafe-Danger-Zone-Images': 'true'})
    for attempt in range(5):
        try:
            return json.load(urllib.request.urlopen(req, timeout=180))
        except urllib.error.HTTPError as ex:
            msg = ex.read().decode()[:400]
            if ex.code in (429, 529, 500, 502, 503) and attempt < 4: time.sleep(5 * (attempt + 1)); continue
            raise RuntimeError(f'HTTP {ex.code}: {msg}')

def one(key, run, model, doc_id, outdir):
    src = os.path.join(HERE, 'results-b', 'run' + 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'
    r = json.load(open(src)); parsed = r.get('parsed')
    rec = dict(model=model, doc=doc_id, run=run, 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']
        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', [])}
            from score import right
            for qid, (kind, ref) in meta.items():
                p = (resp['answers'].get(qid) or {}).get('noul')
                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=p))
        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('--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')))
    from score import ORDER
    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-b', 'run' + a.run)
    for m in models:
        with cf.ThreadPoolExecutor(a.workers) as ex: res = list(ex.map(lambda d: one(key, a.run, m, d, outdir), docs))
        print(m, {x: res.count(x) for x in sorted(set(res))}, flush=True)

if __name__ == '__main__':
    main()
