#!/usr/bin/env python3
"""Score set B (rental, paint and screening invoices with line items) against answer-key-b.json.

Header fields are scored like set A (see score.py). Line items are matched to the key by their
identifier (equipment number / sales number + colour code / service code / location code); a line
is right only when every value on it matches. A document is "perfect" when every header field is
right, every line in the key was returned right, and no extra line was invented.

Usage:  venv/bin/python score_b.py  -> results-b.csv, calls-b.csv, summary-b.json, prints tables
"""
import csv, glob, json, os, statistics as st
from score import right, norm, PRICE, ORDER

HERE = os.path.dirname(os.path.abspath(__file__))
LINEKEY = {'rental': ('equipment_number',), 'paint': ('sales_number', 'color_code'), 'screening': ('service_code',)}

def lkey(line, fields): return tuple(norm(line.get(f)) if line.get(f) is not None else '' for f in fields)

def judge(family, truth, parsed):
    """Return (list of (kind, name, expected, got, ok), spurious_line_count)."""
    out = []
    parsed = parsed if isinstance(parsed, dict) else {}
    for f, t in truth.items():
        if f in ('lines', 'locations'): continue
        out.append(('header', f, t, parsed.get(f), right(f, t, parsed.get(f))))
    spurious = 0
    for coll, fields in (('lines', LINEKEY[family]), ('locations', ('location_code',))):
        if coll not in truth: continue
        got = {}
        for g in (parsed.get(coll) or []):
            if isinstance(g, dict): got.setdefault(lkey(g, fields), g)
        seen = set()
        for tl in truth[coll]:
            k = lkey(tl, fields); g = got.get(k); seen.add(k)
            ok = bool(g) and all(right(f, v, g.get(f)) for f, v in tl.items())
            out.append((coll[:-1], '|'.join(str(tl[f]) for f in fields), tl, g, ok))
        spurious += sum(1 for k in got if k not in seen) + max(0, len(parsed.get(coll) or []) - len(got))
    return out, spurious

def load():
    key = json.load(open(os.path.join(HERE, 'answer-key-b.json')))
    rows, calls = [], []
    for path in sorted(glob.glob(os.path.join(HERE, 'results-b', 'run[0-9]*', '*', '*.json'))):
        r = json.load(open(path)); run = path.split(os.sep)[-3].replace('run', ''); k = key[r['doc']]
        items, spurious = judge(k['family'], k['truth'], r.get('parsed'))
        for kind, name, exp, got, ok in items:
            rows.append(dict(run=run, model=r['model'], doc=r['doc'], family=k['family'], scanned='yes' if k['scanned'] else 'no', pages=k['pages'], kind=kind, name=name,
                             expected=json.dumps(exp), got=json.dumps(got), correct=int(ok)))
        u = r.get('usage') or {}; pin, pout = PRICE[r['model']]
        calls.append(dict(run=run, model=r['model'], doc=r['doc'], family=k['family'], scanned='yes' if k['scanned'] else 'no', pages=k['pages'], lines_in_key=k['line_count'],
                          header_wrong=sum(1 for x in items if x[0] == 'header' and not x[4]), lines_wrong=sum(1 for x in items if x[0] != 'header' and not x[4]), spurious_lines=spurious,
                          perfect=int(all(x[4] for x in items) and spurious == 0), error=r.get('error') or '', seconds=r.get('seconds'),
                          input_tokens=u.get('input_tokens', 0), output_tokens=u.get('output_tokens', 0),
                          cost_usd=round((u.get('input_tokens', 0) * pin + u.get('output_tokens', 0) * pout) / 1e6, 6)))
    return key, rows, calls

def main():
    key, rows, calls = load()
    for name, data in (('results-b.csv', rows), ('calls-b.csv', calls)):
        with open(os.path.join(HERE, name), 'w', newline='') as f:
            w = csv.DictWriter(f, fieldnames=list(data[0])); w.writeheader(); w.writerows(data)
    pct = lambda n, d: round(100 * n / d, 1) if d else None
    summary = {}
    for m in ORDER:
        mr = [x for x in rows if x['model'] == m]; mc = [x for x in calls if x['model'] == m]
        if not mc: continue
        hdr = [x for x in mr if x['kind'] == 'header']; ln = [x for x in mr if x['kind'] != 'header']
        secs = [x['seconds'] for x in mc if x['seconds']]
        s = dict(calls=len(mc), errors=sum(1 for x in mc if x['error']), header_accuracy=pct(sum(x['correct'] for x in hdr), len(hdr)), line_accuracy=pct(sum(x['correct'] for x in ln), len(ln)),
                 perfect_docs=pct(sum(x['perfect'] for x in mc), len(mc)), spurious_lines=sum(x['spurious_lines'] for x in mc),
                 wrong_values=sum(1 - x['correct'] for x in mr),
                 median_seconds=round(st.median(secs), 1) if secs else None, cost_per_1000_docs=round(1000 * st.mean(x['cost_usd'] for x in mc), 2), total_cost=round(sum(x['cost_usd'] for x in mc), 3))
        for fam in ('rental', 'paint', 'screening'):
            fc = [x for x in mc if x['family'] == fam]; s['perfect_' + fam] = pct(sum(x['perfect'] for x in fc), len(fc))
        for sc in ('no', 'yes'):
            fc = [x for x in mc if x['scanned'] == sc]; s['perfect_' + ('scan' if sc == 'yes' else 'digital')] = pct(sum(x['perfect'] for x in fc), len(fc))
        bad = {}
        for x in mr:
            if not x['correct']:
                nm = x['name'] if x['kind'] == 'header' else x['family'] + ' ' + x['kind']
                bad[nm] = bad.get(nm, 0) + 1
        s['wrong_by_field'] = dict(sorted(bad.items(), key=lambda t: -t[1])[:8])
        summary[m] = s
    json.dump(summary, open(os.path.join(HERE, 'summary-b.json'), 'w'), indent=1)
    cols = ['header_accuracy', 'line_accuracy', 'perfect_docs', 'perfect_rental', 'perfect_paint', 'perfect_screening', 'perfect_digital', 'perfect_scan', 'wrong_values', 'spurious_lines', 'median_seconds', 'cost_per_1000_docs', 'errors', 'calls']
    print('model'.ljust(23) + ' '.join(c.replace('perfect_', 'pf_')[:11].rjust(12) for c in cols))
    for m, s in summary.items(): print(m.ljust(23) + ' '.join(str(s[c]).rjust(12) for c in cols))
    for m, s in summary.items(): print(m, s['wrong_by_field'])
    print('total spend set B: $%.2f' % sum(s['total_cost'] for s in summary.values()))

if __name__ == '__main__':
    main()
