#!/usr/bin/env python3
"""
AntLevee Research — Zero-Dependency Deterministic Grader for Forensic SEC Eval Suite v1.0
Verifies predicted numerical answers against ground-truth tolerances in JSONL benchmark tasks.

Usage:
  python3 score_forensic_eval.py --self-test
  python3 score_forensic_eval.py --tasks data/antlevee_forensic_sec_eval_sample10.jsonl --predictions preds.jsonl
"""
import argparse
import json
import sys
from pathlib import Path


def load_jsonl(path: Path) -> list[dict]:
    rows = []
    for line in path.read_text(encoding="utf-8").splitlines():
        s = line.strip()
        if s:
            rows.append(json.loads(s))
    return rows


def score_predictions(tasks: list[dict], preds_by_id: dict[str, float]) -> dict:
    passed = 0
    details = []
    for t in tasks:
        tid = t["id"]
        exp = float(t["expected_value"])
        tol = float(t["tolerance"])
        got = preds_by_id.get(tid)
        ok = got is not None and abs(float(got) - exp) <= tol
        if ok:
            passed += 1
        details.append({"id": tid, "ok": ok, "expected": exp, "got": got, "tolerance": tol})
    return {
        "total": len(tasks),
        "passed": passed,
        "accuracy_pct": round((passed / len(tasks) * 100.0) if tasks else 0.0, 2),
        "details": details,
    }


def self_test() -> int:
    here = Path(__file__).resolve()
    # Works whether run from paper/dist-public/code or unpacked eval vault
    candidates = [
        here.parent.parent / "data" / "antlevee_forensic_sec_eval_sample10.jsonl",
        here.parent / "antlevee_forensic_sec_eval_sample10.jsonl",
    ]
    sample_path = next((p for p in candidates if p.exists()), None)
    if not sample_path:
        print("ERROR: antlevee_forensic_sec_eval_sample10.jsonl not found", file=sys.stderr)
        return 1
    sample_tasks = load_jsonl(sample_path)
    perfect = {t["id"]: t["expected_value"] for t in sample_tasks}
    res = score_predictions(sample_tasks, perfect)
    assert res["total"] == 10 and res["passed"] == 10, res

    full_candidates = [
        here.parent.parent.parent / "feeds" / "out" / "antlevee_forensic_sec_eval_v1_full50.jsonl",
        here.parent / "antlevee_forensic_sec_eval_v1_full50.jsonl",
    ]
    full_path = next((p for p in full_candidates if p.exists()), None)
    full_res = None
    if full_path:
        full_tasks = load_jsonl(full_path)
        full_res = score_predictions(full_tasks, {t["id"]: t["expected_value"] for t in full_tasks})
        assert full_res["total"] == 50 and full_res["passed"] == 50, full_res

    print(json.dumps({
        "self_test": "PASS",
        "sample10": {"passed": res["passed"], "total": res["total"]},
        "full50": {"passed": full_res["passed"], "total": full_res["total"]} if full_res else "not_present_public_env"
    }))
    return 0


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--self-test", action="store_true")
    ap.add_argument("--tasks", type=Path)
    ap.add_argument("--predictions", type=Path, help="JSONL of {id, predicted_value}")
    args = ap.parse_args()
    if args.self_test:
        sys.exit(self_test())
    if not args.tasks or not args.predictions:
        ap.error("Provide --self-test OR both --tasks and --predictions")
    tasks = load_jsonl(args.tasks)
    preds = {r["id"]: float(r["predicted_value"]) for r in load_jsonl(args.predictions) if r.get("predicted_value") is not None}
    print(json.dumps(score_predictions(tasks, preds), indent=2))


if __name__ == "__main__":
    main()
