#!/usr/bin/env python3
"""Scoring core and CLI runner for `ridloabelian/dalil-citation-bench`.

Task: given a piece of text containing ONE Islamic citation (Quran / Hadith / Kitab / fatwa reference,
optionally with a quoted Arabic excerpt), predict dalil-guard's verdict status.

    VERIFIED_EXACT | VERIFIED_NORMALIZED | PARTIAL_TRUNCATED | REFERENCE_MISMATCH |
    NOT_FOUND_HALLUCINATION | UNVERIFIABLE_NO_CORPUS

Gold labels come from the deterministic dalil-guard verifier (agreeing with the construction intent of each
mutation). No model scores are bundled or simulated: bring your own predictions or endpoint.

Examples
    python dalil_eval_runner.py --predictions preds.jsonl                 # {"id": ..., "predicted_status": ...} per line
    python dalil_eval_runner.py --endpoint http://127.0.0.1:11434/v1 --model qwen3:14b   # LLM-judge baseline (no tools)
    python dalil_eval_runner.py --oracle-binary tmp/dalil-guard --oracle-db tmp/corpus.db  # verifier self-consistency
"""

from __future__ import annotations

import argparse
import json
import os
import re
import subprocess
import sys
import urllib.error
import urllib.request
from collections import Counter, defaultdict
from pathlib import Path
from typing import Any

HERE = Path(__file__).resolve().parent
STATUSES = [
    "VERIFIED_EXACT",
    "VERIFIED_NORMALIZED",
    "PARTIAL_TRUNCATED",
    "REFERENCE_MISMATCH",
    "NOT_FOUND_HALLUCINATION",
    "UNVERIFIABLE_NO_CORPUS",
]
# dalil-guard default flags: these statuses pass; everything else fails.
PASSING_STATUSES = {"VERIFIED_EXACT", "VERIFIED_NORMALIZED", "UNVERIFIABLE_NO_CORPUS"}

JUDGE_PROMPT = """You audit Islamic citations WITHOUT any tools or corpus. The text below contains one citation.
Classify it with exactly one status:
- VERIFIED_EXACT: the cited reference exists and any quoted Arabic is verbatim at that reference.
- VERIFIED_NORMALIZED: the quote matches the cited reference once diacritics/spelling are normalized.
- PARTIAL_TRUNCATED: the quote is a word-aligned contiguous piece of the cited text, not the whole text.
- REFERENCE_MISMATCH: the quote is genuine text but belongs to a different reference than the one cited.
- NOT_FOUND_HALLUCINATION: the reference does not exist, or the quote is altered, merged, or fabricated.
- UNVERIFIABLE_NO_CORPUS: the reference type is valid but outside the Quran, Sahih al-Bukhari and Sahih Muslim
  (e.g. Tirmidhi, Abu Dawud, Ibn Majah, Shamela pages, fatwa URIs), so it cannot be checked here.
Answer with JSON only: {"status": "<ONE_OF_THE_SIX>"}.

TEXT:
"""


def load_records(base: Path | None = None) -> list[dict[str, Any]]:
    """Load benchmark rows from the Space assets (preferred) or the sibling dataset directory."""
    candidates = [base] if base else [HERE / "assets", HERE.parent.parent / "datasets" / "dalil-citation-bench" / "data"]
    for d in candidates:
        if d and d.is_dir():
            shards = sorted(list(d.glob("records-*.jsonl")) + list(d.glob("train-*.jsonl")))
            if shards:
                rows = [json.loads(line) for s in shards for line in s.read_text(encoding="utf-8").splitlines() if line.strip()]
                return sorted(rows, key=lambda r: r["id"])
    raise FileNotFoundError("No benchmark shards found next to dalil_eval_runner.py or in ../../datasets/dalil-citation-bench/data")


def _round(x: float) -> float:
    return round(x + 0.0, 4)


def score_predictions(records: list[dict[str, Any]], predictions: dict[str, Any]) -> dict[str, Any]:
    """Score `{id: predicted_status}` against gold rows. Missing/invalid predictions count as wrong."""
    n = len(records)
    correct = 0
    bin_correct = 0
    exp_fail = exp_pass = 0
    caught_fail = kept_pass = false_alarm = 0
    answered = invalid = 0
    confusion: dict[str, Counter] = defaultdict(Counter)
    per_cat: dict[str, list[int]] = defaultdict(lambda: [0, 0])
    for r in records:
        gold = r["expected_status"]
        raw = predictions.get(r["id"])
        if raw is None:
            pred, label = None, "MISSING"
        elif raw in STATUSES:
            pred, label = raw, raw
            answered += 1
        else:
            pred, label = None, "INVALID"
            invalid += 1
            answered += 1
        confusion[gold][label] += 1
        hit = pred == gold
        correct += hit
        per_cat[r["category"]][0] += hit
        per_cat[r["category"]][1] += 1
        pred_bin = None if pred is None else ("pass" if pred in PASSING_STATUSES else "fail")
        gold_bin = "pass" if r["expected_passed"] else "fail"
        bin_correct += pred_bin == gold_bin
        if gold_bin == "fail":
            exp_fail += 1
            caught_fail += pred_bin == "fail"
        else:
            exp_pass += 1
            kept_pass += pred_bin == "pass"
            false_alarm += pred_bin == "fail"
    recall = caught_fail / exp_fail if exp_fail else 0.0
    specificity = kept_pass / exp_pass if exp_pass else 0.0
    cvs = 2 * recall * specificity / (recall + specificity) if (recall + specificity) else 0.0
    return {
        "n": n,
        "answered": answered,
        "missing": n - answered,
        "invalid": invalid,
        "accuracy_6class": _round(correct / n) if n else 0.0,
        "accuracy_binary": _round(bin_correct / n) if n else 0.0,
        "fabrication_recall": _round(recall),
        "specificity": _round(specificity),
        "false_alarm_rate": _round(false_alarm / exp_pass) if exp_pass else 0.0,
        "cvs": _round(cvs),
        "per_category_accuracy": {c: _round(v[0] / v[1]) for c, v in sorted(per_cat.items())},
        "confusion": {g: dict(sorted(c.items())) for g, c in sorted(confusion.items())},
    }


def trivial_baselines(records: list[dict[str, Any]]) -> dict[str, Any]:
    """Deterministic non-model baselines that calibrate how much headroom the benchmark has."""
    out: dict[str, Any] = {}
    counts = Counter(r["expected_status"] for r in records)
    majority = counts.most_common(1)[0][0]
    for label, status in (("always_VERIFIED_EXACT", "VERIFIED_EXACT"), ("always_NOT_FOUND_HALLUCINATION", "NOT_FOUND_HALLUCINATION"), (f"majority_class ({majority})", majority)):
        m = score_predictions(records, {r["id"]: status for r in records})
        out[label] = {k: m[k] for k in ("accuracy_6class", "accuracy_binary", "fabrication_recall", "specificity", "false_alarm_rate", "cvs")}
    return out


# ---------- prediction sources ----------

def read_predictions(path: Path) -> dict[str, Any]:
    preds: dict[str, Any] = {}
    for line_no, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
        if not line.strip():
            continue
        obj = json.loads(line)
        if "id" not in obj or "predicted_status" not in obj:
            raise ValueError(f"{path}:{line_no}: expected keys 'id' and 'predicted_status'")
        if obj["id"] in preds:
            raise ValueError(f"{path}:{line_no}: duplicate id {obj['id']!r}")
        preds[obj["id"]] = obj["predicted_status"]
    return preds


def oracle_predictions(records: list[dict[str, Any]], binary: Path, db: Path) -> dict[str, Any]:
    preds: dict[str, Any] = {}
    for r in records:
        proc = subprocess.run([str(binary), "verify", "--db", str(db), "--json"], input=r["input_text"], text=True, capture_output=True, timeout=30)
        report = json.loads(proc.stdout)
        preds[r["id"]] = report["claims"][0]["status"] if report["claims"] else None
    return preds


def judge_predictions(records: list[dict[str, Any]], endpoint: str, model: str, api_key_env: str | None, limit: int | None) -> dict[str, Any]:
    url = endpoint.rstrip("/") + "/chat/completions"
    headers = {"Content-Type": "application/json"}
    if api_key_env:
        key = os.environ.get(api_key_env, "")
        if not key:
            raise SystemExit(f"Environment variable {api_key_env} is empty.")
        headers["Authorization"] = f"Bearer {key}"
    preds: dict[str, Any] = {}
    for r in records[: limit or None]:
        body = json.dumps({"model": model, "temperature": 0, "messages": [{"role": "user", "content": JUDGE_PROMPT + r["input_text"]}]}).encode("utf-8")
        req = urllib.request.Request(url, data=body, headers=headers, method="POST")
        try:
            with urllib.request.urlopen(req, timeout=120) as resp:
                content = json.loads(resp.read().decode("utf-8"))["choices"][0]["message"]["content"]
        except (urllib.error.URLError, KeyError, json.JSONDecodeError) as exc:
            print(f"[warn] {r['id']}: {exc}", file=sys.stderr)
            continue
        m = re.search(r'"status"\s*:\s*"([A-Z_]+)"', content)
        preds[r["id"]] = m.group(1) if m else "INVALID"
    return preds


def main(argv: list[str] | None = None) -> int:
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    src = p.add_mutually_exclusive_group(required=True)
    src.add_argument("--predictions", type=Path, help="JSONL with id + predicted_status.")
    src.add_argument("--endpoint", help="OpenAI-compatible base URL for the no-tools LLM-judge baseline.")
    src.add_argument("--oracle-binary", type=Path, help="dalil-guard binary (verifier self-consistency run).")
    p.add_argument("--model", help="Model name for --endpoint.")
    p.add_argument("--api-key-env", help="Env var holding the API key for --endpoint.")
    p.add_argument("--oracle-db", type=Path, help="corpus.db for --oracle-binary.")
    p.add_argument("--limit", type=int, help="Only query the first N rows (endpoint mode); the rest count as missing.")
    p.add_argument("--out", type=Path, help="Write metrics JSON here.")
    args = p.parse_args(argv)

    records = load_records()
    if args.predictions:
        preds = read_predictions(args.predictions)
    elif args.endpoint:
        if not args.model:
            p.error("--model is required with --endpoint")
        preds = judge_predictions(records, args.endpoint, args.model, args.api_key_env, args.limit)
    else:
        if not args.oracle_db:
            p.error("--oracle-db is required with --oracle-binary")
        preds = oracle_predictions(records, args.oracle_binary, args.oracle_db)

    unknown = sorted(set(preds) - {r["id"] for r in records})
    if unknown:
        print(f"[warn] {len(unknown)} predictions reference unknown ids (ignored), e.g. {unknown[:3]}", file=sys.stderr)
    metrics = score_predictions(records, preds)
    text = json.dumps(metrics, indent=2, ensure_ascii=False)
    print(text)
    if args.out:
        args.out.write_text(text + "\n", encoding="utf-8")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
