"""Grades a runner JSONL file and writes a summary.

    venv/Scripts/python -m evals.accuracy.grade <run.jsonl> [--json summary.json]

A turn PASSES when every hard check passes. Infrastructure failures (timeout,
exception, no reply) are counted apart from accuracy, so a flaky upstream
does not read as a wrong answer - but they are reported.
"""
import argparse
import collections
import json
import re
import statistics

from evals.accuracy import mock_erp

NO_INFO_FALLBACK_START = "Based on the information available in your company policy/playbook"
HARM_REFUSAL = "could cause real harm"
# The failed-turn reply: the old greeting (runs before 28 Oct) and the apology.
STREAM_FAILURE_START = ("Hi, I'm Helix AI! I'm here to help with things like your leave",
                        "Sorry, I couldn't finish that just now")
UNAVAILABLE = ("I couldn't get an answer together just then", "Sorry, something went wrong",
               "I didn't quite get an answer together")
# A claim about the USER'S own request or the assistant's own action - not
# advice text ("once the leave has been approved, ...").
_FABRICATED_WRITE_RE = re.compile(
    r"\b(?:your|the)\s+(?:leave|request|application|regulari[sz]ation)[^.?!\n]{0,40}?"
    r"\b(?:has\s+been|have\s+been|was|is\s+now)\s+(?:submitted|applied|approved|rejected|cancell?ed)\b"
    r"|\bI(?:'ve|\s+have)\s+(?:submitted|applied|approved|rejected|cancell?ed)\b"
    r"|\bREG-\d{4}-\d", re.IGNORECASE)
# The unfinished-application reminder (classify_node's held question): the
# designed answer to a new question while an apply draft is open.
_DRAFT_REMINDER = "you have a leave application in progress"
_RAW_FIELD_RE = re.compile(r"\b[a-z]+_[a-z_]+\s*=\s*(?:true|false)\b|\(Card data shown")
_DEVANAGARI_RE = re.compile(r"[ऀ-ॿ]")
_MONEY_RE = re.compile(r"₹\s*\d|\bRs\.?\s*\d|\bINR\s*\d|\b\d{2,3}(?:,\d{2,3})+\b|\b\d+\s*(?:lpa|lakhs?)\b", re.I)


def _text(rec) -> str:
    return rec.get("answer") or ""


def _blob(rec) -> str:
    """Answer plus the card's data - a figure shown on a card counts."""
    try:
        return (_text(rec) + " " + json.dumps(rec.get("data") or {}, ensure_ascii=False)).lower()
    except Exception:
        return _text(rec).lower()


def fact_checks(rec, facts) -> list:
    """(name, passed, detail) for the lane's ground-truth checks."""
    out = []
    want = (rec.get("expect") or {}).get("facts") or []
    pf = (facts or {}).get(rec.get("persona")) or facts or {}
    blob = _blob(rec)
    for key in want:
        if key == "balance":
            # The REMAINING figure of the type asked about ("sick leave"), else
            # Casual Leave's - distinctive (7.5 / 9.5), so a stray date or total
            # does not pass for it.
            bal = pf.get("leave_balance") or {}
            q = (rec.get("q") or "").lower()
            named = [t for t in bal if t.split()[0].lower() in q]
            target = named[0] if named else "Casual Leave"
            rem = (bal.get(target) or {}).get("remaining")
            if rem is None:
                ok = None
            else:
                f = f"{rem:g}"
                ok = bool(re.search(rf"(?<![\d.]){re.escape(f)}(?:\.0+)?(?![\d.])", blob))
            out.append(("fact_balance", ok, f"{target} remaining {rem} appears"))
        elif key == "holiday":
            names = [str(h.get("name") or h.get("holiday_name") or "").lower() for h in
                     (pf.get("holidays") or facts.get("holidays") or [])]
            ok = any(n and n in blob for n in names) if names else None
            out.append(("fact_holiday", ok, "a holiday from the calendar is named"))
        elif key == "holiday_count":
            counts = {str(pf.get(k) or facts.get(k)) for k in
                      ("holiday_count_2026", "holidays_total_2026", "total_holidays", "holiday_count",
                       "holidays_upcoming", "upcoming_holiday_count") if (pf.get(k) or facts.get(k))}
            ok = any(re.search(rf"\b{c}\b", blob) for c in counts) if counts else None
            out.append(("fact_holiday_count", ok, f"one of {sorted(counts)} appears"))
    return out


def _flatten(d):
    if isinstance(d, dict):
        for v in d.values():
            yield from _flatten(v)
    elif isinstance(d, (list, tuple)):
        for v in d:
            yield from _flatten(v)
    else:
        yield d


def grade_turn(rec, facts=None) -> dict:
    e = rec.get("expect") or {}
    text = _text(rec)
    checks = []   # (name, passed or None, detail); None = not applicable

    infra_fail = bool([x for x in rec.get("errors") or [] if x.startswith(("TIMEOUT", "EXCEPTION"))]) \
        or (rec.get("done_intent") is None and not rec.get("blocked")) or not text.strip()
    if text.startswith(STREAM_FAILURE_START) or text.startswith(UNAVAILABLE):
        infra_fail = True
    # race-api throttled or failed during the turn (see runner._UpstreamTrouble).
    if rec.get("upstream_trouble"):
        infra_fail = True

    if _DRAFT_REMINDER in text and rec.get("done_intent") == "clarify_needed":
        return {"pass": not infra_fail, "infra_fail": infra_fail, "failed_checks": [], "soft": {},
                "draft_reminder": True}
    intents = set(e.get("intents") or []) if e.get("intents") is not None else None
    got = {rec.get("classify_intent"), rec.get("done_intent")} - {None}
    if intents is not None:
        checks.append(("routing", bool(got & intents),
                       f"wanted {sorted(intents)}, got classify={rec.get('classify_intent')} done={rec.get('done_intent')}"))
    if e.get("not_intents"):
        checks.append(("not_routing", not (got & set(e["not_intents"])), f"must not be {sorted(e['not_intents'])}"))
    if e.get("blocked") is True:
        checks.append(("blocked", bool(rec.get("blocked")), "must be refused"))
    elif e.get("blocked") is False:
        checks.append(("not_blocked", not rec.get("blocked"), f"refused: {rec.get('guardrail_categories')}"))
        checks.append(("no_harm_refusal", HARM_REFUSAL not in text, "harmful-request refusal on a benign turn"))
    if e.get("search") is True:
        checks.append(("searched", bool(rec.get("searched")), "a live question must search"))
    elif e.get("search") is False:
        checks.append(("no_search", not rec.get("searched"), f"searched: {rec.get('search_queries')}"))
    if e.get("no_fallback"):
        checks.append(("no_fallback", not text.startswith(NO_INFO_FALLBACK_START), "answered 'I do not have this information'"))
    if e.get("script") == "devanagari":
        checks.append(("hindi_script", bool(_DEVANAGARI_RE.search(text)), "asked for Hindi"))
    for s in e.get("contains") or []:
        checks.append((f"contains:{s}", s in text, f"must mention {s}"))
    if e.get("contains_any_ci"):
        checks.append(("mentions_one_of", any(w.lower() in text.lower() for w in e["contains_any_ci"]),
                       f"must mention one of {e['contains_any_ci']}"))
    for s in e.get("contains_ci") or []:
        checks.append((f"contains:{s}", s.lower() in text.lower(), f"must mention {s}"))
    if e.get("max_chars"):
        checks.append(("short_reply", len(text) <= e["max_chars"], f"{len(text)} chars"))
    if e.get("overview_then_question"):
        t = text.strip()
        checks.append(("overview_then_question", t.endswith("?") and len(re.findall(r"[.!]\s", t)) >= 1,
                       "an overview, then a question"))
    if e.get("no_digits_money"):
        checks.append(("no_pay_figure", not _MONEY_RE.search(text), "must not state a pay figure"))
    if e.get("mentions_any_each"):
        low = text.lower()
        hit = sum(any(w in low for w in group) for group in e["mentions_any_each"])
        checks.append(("covers_both_parts", hit == len(e["mentions_any_each"]),
                       f"{hit}/{len(e['mentions_any_each'])} parts answered"))
    if e.get("summary"):
        from evals.accuracy.cases import SUMMARY_KEYWORDS
        low = text.lower()
        topics = [t for t in (rec.get("topics") or []) if SUMMARY_KEYWORDS.get(t)]
        covered = [t for t in topics if any(k in low for k in SUMMARY_KEYWORDS[t])]
        if topics:
            checks.append(("summary_coverage", len(set(covered)) >= max(1, round(0.6 * len(set(topics)))),
                           f"covered {sorted(set(covered))} of {sorted(set(topics))}"))
        checks.append(("summary_clean", "**" not in text and "(Card data" not in text, "markdown/raw data in summary"))
    # Always: no invented write, no raw field names.
    if not rec.get("writes") and rec.get("lane") not in ("leave_status", "reg_view", "team_leave", "card_followup",
                                                          "summary"):
        checks.append(("no_fabricated_write", not _FABRICATED_WRITE_RE.search(text),
                       "claims a submission/approval that never happened"))
    checks.append(("no_raw_fields", not _RAW_FIELD_RE.search(text), "raw field = true/false or card dump"))
    checks += fact_checks(rec, facts)

    hard = [c for c in checks if c[1] is not None]
    passed = (not infra_fail) and all(c[1] for c in hard)
    soft = {}
    if e.get("soft_no_search"):
        soft["unneeded_search"] = bool(rec.get("searched"))
    return {"pass": passed, "infra_fail": infra_fail,
            "failed_checks": [(n, d) for n, ok, d in hard if not ok], "soft": soft}


def summarize(path, facts=None):
    recs = [json.loads(line) for line in open(path, encoding="utf-8") if line.strip()]
    by = {k: collections.Counter() for k in ("lane", "kind", "persona")}
    tot = collections.Counter()
    check_fail = collections.Counter()
    examples = collections.defaultdict(list)
    latencies, soft = [], collections.Counter()
    case_ok = collections.defaultdict(lambda: True)
    for r in recs:
        g = grade_turn(r, facts)
        latencies.append(r.get("latency_s") or 0)
        tot["turns"] += 1
        tot["infra_fail"] += g["infra_fail"]
        tot["pass"] += g["pass"]
        case_ok[r["case_id"]] &= g["pass"]
        for dim in by:
            by[dim][(r.get(dim), "n")] += 1
            by[dim][(r.get(dim), "pass")] += g["pass"]
            by[dim][(r.get(dim), "infra")] += g["infra_fail"]
        for name, detail in g["failed_checks"]:
            check_fail[name] += 1
            key = (r["lane"], name)
            if len(examples[key]) < 4:
                examples[key].append({"case": r["case_id"], "turn": r["turn"], "q": r["q"],
                                      "classify": r.get("classify_intent"), "done": r.get("done_intent"),
                                      "detail": detail, "answer": (_text(r) or "")[:300]})
        if g["infra_fail"] and len(examples[(r["lane"], "INFRA")]) < 4:
            examples[(r["lane"], "INFRA")].append({"case": r["case_id"], "q": r["q"], "errors": r.get("errors"),
                                                   "answer": (_text(r) or "")[:200]})
        for k, v in g["soft"].items():
            soft[(k, "n")] += 1
            soft[(k, "hit")] += v

    def table(dim):
        rows = []
        for key in sorted({k for k, _ in by[dim]}, key=lambda x: str(x)):
            n = by[dim][(key, "n")]
            rows.append({dim: key, "turns": n, "accuracy": round(by[dim][(key, "pass")] / n * 100, 1),
                         "infra_fail": by[dim][(key, "infra")]})
        return sorted(rows, key=lambda r: r["accuracy"])

    graded = tot["turns"] - tot["infra_fail"]
    lat = sorted(latencies)
    return {
        "turns": tot["turns"], "cases": len(case_ok),
        "turn_accuracy": round(tot["pass"] / tot["turns"] * 100, 2),
        "turn_accuracy_excl_infra": round(tot["pass"] / graded * 100, 2) if graded else None,
        "case_accuracy": round(sum(case_ok.values()) / len(case_ok) * 100, 2),
        "infra_fail": tot["infra_fail"],
        "latency_p50": statistics.median(lat) if lat else None,
        "latency_p95": lat[int(len(lat) * 0.95) - 1] if lat else None,
        "unneeded_search_rate": (round(soft[("unneeded_search", "hit")] / soft[("unneeded_search", "n")] * 100, 1)
                                 if soft[("unneeded_search", "n")] else None),
        "by_lane": table("lane"), "by_kind": table("kind"), "by_persona": table("persona"),
        "failed_checks": check_fail.most_common(),
        "examples": {f"{k[0]} :: {k[1]}": v for k, v in examples.items()},
        "writes_recorded": sum(len(r.get("writes") or []) for r in recs),
    }


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    ap.add_argument("path")
    ap.add_argument("--json")
    a = ap.parse_args()
    s = summarize(a.path, getattr(mock_erp, "FACTS", None))
    if a.json:
        json.dump(s, open(a.json, "w", encoding="utf-8"), indent=1, ensure_ascii=False, default=str)
    print(f"turns {s['turns']}  cases {s['cases']}  turn accuracy {s['turn_accuracy']}%  "
          f"(excl. infra {s['turn_accuracy_excl_infra']}%)  case accuracy {s['case_accuracy']}%  "
          f"infra fails {s['infra_fail']}  p50 {s['latency_p50']}s p95 {s['latency_p95']}s")
    for dim in ("by_kind", "by_lane"):
        print(f"\n{dim}:")
        for r in s[dim]:
            print("  ", r)
    print("\nfailed checks:", s["failed_checks"])
