#!/usr/bin/env python3
"""Score the rules engine on synthetic labeled leads and write eval/report.md.

Three tuning rounds. Each is judged on 20 fresh leads that were written and
hash-frozen before that round's rule changes (eval/HOLDOUT_FREEZE.txt):
  round 1  eval/history/triage_v1.py  tuned on tune (40)                      tested on holdout  (20)
  round 2  eval/history/triage_v2.py  tuned on tune + holdout (60)            tested on holdout2 (20)
  round 3  triage.py (current)        tuned on tune + holdout + holdout2 (80) tested on holdout3 (20)

Usage: python3 eval.py             full report
       python3 eval.py --tune-only current engine on its 80 tuning leads only
"""
import hashlib
import importlib.util
import json
import re
import sys
from datetime import datetime
from pathlib import Path

import triage

HERE = Path(__file__).resolve().parent
EVAL = HERE / "eval"
REPORT = EVAL / "report.md"
CATS = triage.CATEGORIES
SHORT = {"buyer": "buyer", "vendor_pitch": "vendor", "partnership": "partner", "support": "support", "spam": "spam"}
FILES = ("leads_labeled.jsonl", "leads_holdout2.jsonl", "leads_holdout3.jsonl")
HOLDOUTS = ("holdout", "holdout2", "holdout3")  # same order as the hashes in HOLDOUT_FREEZE.txt


def load_module(path, name):
    spec = importlib.util.spec_from_file_location(name, path)
    mod = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(mod)
    return mod


def load_rows():
    rows, hashes = [], {s: hashlib.sha256() for s in HOLDOUTS}
    for name in FILES:
        for line in (EVAL / name).read_text(encoding="utf-8").splitlines():
            obj = json.loads(line)
            if "_meta" in obj:
                continue
            rows.append(obj)
            if obj["split"] in hashes:
                hashes[obj["split"]].update((line + "\n").encode())
    frozen = re.findall(r"\b[0-9a-f]{64}\b", (EVAL / "HOLDOUT_FREEZE.txt").read_text(encoding="utf-8"))
    return rows, {s: hashes[s].hexdigest() == frozen[i] for i, s in enumerate(HOLDOUTS)}


def run(mod, rows):
    return {r["id"]: mod.set_priority(r, mod.classify_rules(r)) for r in rows}


def metrics(rows, preds):
    conf = {g: {p: 0 for p in CATS} for g in CATS}
    for r in rows:
        conf[r["label"]][preds[r["id"]].category] += 1
    per = {}
    for c in CATS:
        tp = conf[c][c]
        fp = sum(conf[g][c] for g in CATS if g != c)
        fn = sum(conf[c][p] for p in CATS if p != c)
        prec = tp / (tp + fp) if tp + fp else 0.0
        rec = tp / (tp + fn) if tp + fn else 0.0
        per[c] = (prec, rec, 2 * prec * rec / (prec + rec) if prec + rec else 0.0, tp + fn)
    correct = sum(conf[c][c] for c in CATS)
    sure = [r for r in rows if getattr(preds[r["id"]], "confident", True)]
    sure_ok = sum(preds[r["id"]].category == r["label"] for r in sure)
    return {"n": len(rows), "correct": correct, "acc": correct / len(rows),
            "macro": sum(v[2] for v in per.values()) / len(CATS), "per": per, "conf": conf,
            "sure_n": len(sure), "sure_acc": sure_ok / len(sure) if sure else 0.0}


def business(rows, preds):
    buyers = [r for r in rows if r["label"] == "buyer"]
    junk_rows = [r for r in rows if r["label"] in ("vendor_pitch", "spam")]
    return {
        "buyers": len(buyers),
        "buried": [r["id"] for r in buyers if preds[r["id"]].priority in ("P3", "P4")],
        "junk": len(junk_rows),
        "junk_up": [r["id"] for r in junk_rows if preds[r["id"]].priority in ("P1", "P2")],
        "inj": [r["id"] for r in rows if preds[r["id"]].injection_suspected],
        "inj_p1": [r["id"] for r in rows if preds[r["id"]].injection_suspected and preds[r["id"]].priority == "P1"],
        "inj_labeled": [r["id"] for r in rows if "injection" in r.get("note", "")],
    }


def detail(title, m):
    out = [f"### {title}", "",
           f"Accuracy **{m['acc']:.1%}** ({m['correct']}/{m['n']}), macro F1 **{m['macro']:.2f}**", "",
           "| Class | Precision | Recall | F1 | Support |", "|---|---|---|---|---|"]
    for c in CATS:
        p, r, f, n = m["per"][c]
        out.append(f"| {c} | {p:.2f} | {r:.2f} | {f:.2f} | {n} |")
    out += ["", "Confusion matrix (rows = true label, columns = predicted):", "",
            "| true \\ pred | " + " | ".join(SHORT[c] for c in CATS) + " |", "|---|" + "---|" * len(CATS)]
    out += [f"| {SHORT[g]} | " + " | ".join(str(m["conf"][g][p]) for p in CATS) + " |" for g in CATS]
    return out + [""]


def misses(title, rows, preds):
    bad = [r for r in rows if preds[r["id"]].category != r["label"]]
    out = [f"### {title} ({len(bad)})", ""]
    if not bad:
        return out + ["None.", ""]
    for r in bad:
        res = preds[r["id"]]
        scores = ", ".join(f"{SHORT[c]} {s}" for c, s in res.scores.items() if s) or "all zero"
        sure = "" if getattr(res, "confident", True) else ", low confidence"
        out += [f"**{r['id']}** ({r['split']}): true `{r['label']}`, predicted `{res.category}` ({res.priority}{sure})",
                f"- Message: \"{' '.join(r['message'].split())}\"",
                f"- Scores: {scores}",
                f"- Signals fired: {'; '.join(res.reasons) or 'none'}"]
        if r.get("note"):
            out.append(f"- Why it is hard (label note): {r['note']}")
        out.append("")
    return out


def main():
    rows, hash_ok = load_rows()
    split = {s: [r for r in rows if r["split"] == s] for s in ("tune",) + HOLDOUTS}
    cur = run(triage, rows)
    tune3 = split["tune"] + split["holdout"] + split["holdout2"]

    if "--tune-only" in sys.argv:  # what I looked at while tuning round 3: never shows holdout3
        m = metrics(tune3, cur)
        print(f"round-3 tuning leads ({m['n']}): accuracy {m['acc']:.1%}")
        for r in tune3:
            if cur[r["id"]].category != r["label"]:
                print(f"  {r['id']} {r['label']} -> {cur[r['id']].category} {cur[r['id']].scores}")
        return 0

    v1 = run(load_module(EVAL / "history" / "triage_v1.py", "triage_v1"), rows)
    v2 = run(load_module(EVAL / "history" / "triage_v2.py", "triage_v2"), rows)
    rounds = [
        ("Round 1", "`eval/history/triage_v1.py`", v1, split["tune"], "holdout 1", split["holdout"]),
        ("Round 2", "`eval/history/triage_v2.py`", v2, split["tune"] + split["holdout"], "holdout 2", split["holdout2"]),
        ("Round 3", "`triage.py` (current)", cur, tune3, "holdout 3", split["holdout3"]),
    ]
    h3 = split["holdout3"]
    same = [(name, metrics(h3, preds)) for name, _, preds, *_ in rounds]
    m3 = metrics(h3, cur)
    b3, ball = business(h3, cur), business(rows, cur)

    def ids(xs):
        return f" ({', '.join(xs)})" if xs else ""

    out = ["# Rules engine evaluation", "",
           f"Run: `python3 eval.py` on {datetime.now(triage.BIZ_TZ).strftime('%B %-d, %Y')}. "
           f"Data: {len(rows)} **synthetic** leads, 20 per class, labeled with `eval/LABEL_GUIDE.md` before scoring.", "",
           "Holdout integrity (sha256 checked against `eval/HOLDOUT_FREEZE.txt`, frozen before each round's changes): "
           + ", ".join(f"{s} **{'matches' if ok else 'DOES NOT MATCH'}**" for s, ok in hash_ok.items()) + ".", "",
           "## Summary", "",
           "| Round | Engine | Tuned on | Accuracy on its tuning leads | Accuracy on fresh held-out leads "
           "| Fresh: buyers buried | Fresh: vendor/spam in P1-P2 | Fresh: injection at P1 |",
           "|---|---|---|---|---|---|---|---|"]
    for name, engine, preds, tune_rows, test_name, test_rows in rounds:
        mt, mh, bh = metrics(tune_rows, preds), metrics(test_rows, preds), business(test_rows, preds)
        out.append(f"| {name} | {engine} | {len(tune_rows)} leads | {mt['acc']:.1%} | "
                   f"{test_name}: **{mh['acc']:.1%}** (macro F1 {mh['macro']:.2f}) | "
                   f"{len(bh['buried'])} of {bh['buyers']} | {len(bh['junk_up'])} of {bh['junk']} | {len(bh['inj_p1'])} |")
    out += ["", "All three engines on holdout 3, which none of them was tuned on:", "",
            "| Engine | Accuracy | Macro F1 |", "|---|---|---|"]
    out += [f"| {name} | {m['acc']:.1%} | {m['macro']:.2f} |" for name, m in same]
    out += ["", f"Round 3 confidence flag on holdout 3: {m3['sure_n']} of {m3['n']} leads marked confident, "
            f"**{m3['sure_acc']:.1%}** of those correct. The other {m3['n'] - m3['sure_n']} are marked low confidence "
            "for a person to check, and are never archived or given P1.", "",
            "Business checks, round 3 engine on holdout 3:", "",
            f"- Buyers sent to P3 or P4 (buried): **{len(b3['buried'])} of {b3['buyers']}**{ids(b3['buried'])}",
            f"- Vendor pitches and spam that reached P1 or P2: **{len(b3['junk_up'])} of {b3['junk']}**{ids(b3['junk_up'])}",
            f"- Injection leads flagged: {len(b3['inj'])}{ids(b3['inj'])}; reached P1: **{len(b3['inj_p1'])}**", "",
            f"Same checks on all {len(rows)} leads (includes the 80 the engine was tuned on): buyers buried **{len(ball['buried'])} of {ball['buyers']}**{ids(ball['buried'])}, "
            f"vendor/spam in P1 or P2 **{len(ball['junk_up'])} of {ball['junk']}**{ids(ball['junk_up'])}, "
            f"injection leads flagged {len(ball['inj'])} of the {len(ball['inj_labeled'])} written as attacks{ids(ball['inj'])}, "
            f"reached P1 **{len(ball['inj_p1'])}**.", "",
            "## Detail", ""]
    out += detail("Round 3 engine on holdout 3 (fresh, 20 leads)", m3)
    out += detail("Round 3 engine on its 80 tuning leads", metrics(tune3, cur))
    out += ["## Every misclassification", ""]
    out += misses("Round 3 engine, all leads", rows, cur)
    out += misses("Round 2 engine on holdout 2 (at the time)", split["holdout2"], v2)
    out += misses("Round 1 engine on holdout 1 (at the time)", split["holdout"], v1)
    out += ["## Caveats", "",
            "- One author wrote the leads and the rules, so held-out scores are likely optimistic. A sample of real inbox mail is the next test.",
            "- 20 held-out leads means each lead moves accuracy by 5 points. Treat differences under 10 points as noise.", ""]
    REPORT.write_text("\n".join(out), encoding="utf-8")

    for name, engine, preds, tune_rows, test_name, test_rows in rounds:
        mt, mh = metrics(tune_rows, preds), metrics(test_rows, preds)
        print(f"{name.lower()}: tuning {mt['acc']:.1%} ({len(tune_rows)}) | {test_name} {mh['acc']:.1%} "
              f"({len(test_rows)}), macro F1 {mh['macro']:.2f}")
    print("all engines on holdout 3: " + ", ".join(f"{n} {m['acc']:.1%}" for n, m in same))
    print(f"round 3 confident on holdout 3: {m3['sure_n']}/{m3['n']}, {m3['sure_acc']:.1%} correct")
    print(f"holdout 3 checks: buyers buried {len(b3['buried'])}/{b3['buyers']}, vendor/spam in P1-P2 "
          f"{len(b3['junk_up'])}/{b3['junk']}, injection flagged {len(b3['inj'])}, reached P1 {len(b3['inj_p1'])}")
    print(f"all {len(rows)} checks: buyers buried {len(ball['buried'])}/{ball['buyers']}, vendor/spam in P1-P2 "
          f"{len(ball['junk_up'])}/{ball['junk']}, injections flagged {len(ball['inj'])}/{len(ball['inj_labeled'])}, reached P1 {len(ball['inj_p1'])}")
    print("hashes: " + ", ".join(f"{k} {'OK' if v else 'MISMATCH'}" for k, v in hash_ok.items()))
    bad = [r for r in rows if cur[r["id"]].category != r["label"]]
    print("round 3 misclassified: " + (", ".join(f"{r['id']}({r['split']}) {r['label']}->{cur[r['id']].category}" for r in bad) or "none"))
    print(f"wrote {REPORT.relative_to(HERE)}")
    return 0 if all(hash_ok.values()) else 1


if __name__ == "__main__":
    sys.exit(main())
