"""Score an agent's answers against dd-eval-v1 (Canadian address due diligence).

Answers are JSONL, one object per item:

  {"id": "<item id>", "answer": <value>}            a value (string, number or list)
  {"id": "<item id>", "state": "not_covered"}       a non-answer state
  {"id": "<item id>", "answer": "not_covered"}      the same state given as the answer

States: answered, not_covered, no_match, ambiguous, not_published, unavailable.
Checks: ``set`` (normalized set equality), ``one_of`` (answer equals one accepted value),
``exact`` (normalized equality), ``numeric`` (absolute or relative tolerance) and
``state`` (the answer must name the expected state). A missing answer is wrong.

  uv run python scripts/evals/score_due_diligence.py answers.jsonl [--answered-only] [--json]

The scorer is standard-library only and also scores the public sample (``dd-eval-v1-public``,
downloadable from hillbase.com/benchmark) and the keyed full set (``dd-eval-v1-full``):

  python3 score_due_diligence.py answers.jsonl --items dd-eval-v1-public.jsonl
"""

from __future__ import annotations

import argparse
import json
import re
import sys
import unicodedata
from collections import defaultdict
from datetime import date
from pathlib import Path

EVAL_VERSION = "dd-eval-v1"
# The same items and rules without lineage: the public sample and the keyed full set.
EVAL_VERSIONS = (
    EVAL_VERSION,
    "dd-eval-v1-public",
    "dd-eval-v1-full",
    "dd-eval-v1.1",
    "dd-eval-v1.1-public",
    "dd-eval-v1.1-full",
)
_HERE = Path(__file__).resolve().parent
ITEMS = _HERE.parents[1] / "docs" / "evals" / "due-diligence-v1.jsonl"
if not ITEMS.is_file():  # downloaded next to the public sample
    ITEMS = _HERE / "dd-eval-v1-public.jsonl"
STATES = ("answered", "not_covered", "no_match", "ambiguous", "not_published", "unavailable")
STATE_ALIASES = {
    "not covered": "not_covered",
    "unsupported": "not_covered",
    "no match": "no_match",
    "none": "no_match",
    "not found": "no_match",
    "not published": "not_published",
    "unavailable": "unavailable",
    "ambiguous": "ambiguous",
}
AREA_ALIASES = {
    "yes": "in_area",
    "true": "in_area",
    "inside": "in_area",
    "in area": "in_area",
    "no": "not_in_area",
    "false": "not_in_area",
    "outside": "not_in_area",
    "not in area": "not_in_area",
}
# Public forms ask whether a name matches any loaded sanctions list ("listed").
LISTED_ALIASES = {"yes", "true", "listed", "match", "matched", "in list", "on list"}


def norm(value) -> str:
    text = unicodedata.normalize("NFKD", str(value))
    text = "".join(c for c in text if not unicodedata.combining(c)).casefold()
    text = text.replace("’", "'")
    return re.sub(r"[^0-9a-z]+", " ", text).strip()


def answer_state(row: dict) -> str:
    if row.get("state"):
        return STATE_ALIASES.get(norm(row["state"]), norm(row["state"]).replace(" ", "_"))
    answer = row.get("answer")
    if answer is None or answer == [] or answer == "":
        return "no_match"
    if isinstance(answer, str):
        key = norm(answer)
        if key.replace(" ", "_") in STATES and key != "answered":
            return key.replace(" ", "_")
        if key in STATE_ALIASES:
            return STATE_ALIASES[key]
    return "answered"


def number(value) -> float | None:
    if isinstance(value, bool):
        return None
    if isinstance(value, int | float):
        return float(value)
    if isinstance(value, list) and len(value) == 1:
        return number(value[0])
    if isinstance(value, str):
        match = re.search(r"-?\d[\d,]*(?:\.\d+)?", value.replace(" ", ""))
        if match:
            return float(match.group().replace(",", ""))
    return None


def as_list(value) -> list:
    if isinstance(value, list):
        return value
    if isinstance(value, str) and ";" in value:
        return [v for v in value.split(";") if v.strip()]
    return [value]


def as_date(value) -> str | None:
    try:
        return date.fromisoformat(str(value).strip()[:10]).isoformat()
    except ValueError:
        return None


def check(item: dict, row: dict | None) -> tuple[bool, str]:
    """(correct, reason) for one item."""
    if row is None:
        return False, "missing"
    expected = item["expected"]
    got_state = answer_state(row)
    if expected["state"] != "answered":
        ok = got_state == expected["state"]
        return ok, "state" if ok else f"state:{got_state}"
    if got_state != "answered":
        return False, f"state:{got_state}"
    answer, want, rule = row.get("answer"), expected["value"], item["check"]
    if rule == "set":
        ok = {norm(v) for v in as_list(answer)} == {norm(v) for v in want}
    elif rule == "one_of":
        first = as_list(answer)[0]
        ok = norm(first) in {norm(v) for v in want}
    elif rule == "exact":
        if item["qtype"] == "waste_next_garbage":
            ok = as_date(answer) == want
        elif want == "listed":
            ok = norm(answer) in LISTED_ALIASES
        else:
            got = norm(answer)
            ok = AREA_ALIASES.get(got, got.replace(" ", "_")) == want
    elif rule == "numeric":
        got = number(answer)
        tolerance = item.get("tolerance") or {"absolute": 0}
        if got is None:
            return False, "not_a_number"
        if "relative" in tolerance:
            ok = abs(got - want) <= tolerance["relative"] * abs(want)
        else:
            ok = abs(got - want) <= tolerance["absolute"] + 1e-9
    else:
        raise ValueError(f"unknown check {rule}")
    return ok, "value" if ok else "wrong_value"


def load_items(path: Path = ITEMS) -> list[dict]:
    """Items from JSONL, or from the saved ``GET /v1/evals/due-diligence`` response."""
    text = path.read_text()
    try:
        whole = json.loads(text)
    except json.JSONDecodeError:
        whole = None
    if isinstance(whole, dict) and "items" in (whole.get("data") or whole):
        items = (whole.get("data") or whole)["items"]
    else:
        items = [json.loads(line) for line in text.splitlines() if line.strip()]
    versions = {i["eval_version"] for i in items}
    if len(versions) != 1 or not versions <= set(EVAL_VERSIONS):
        raise SystemExit(f"items are {sorted(versions)}, scorer reads {list(EVAL_VERSIONS)}")
    return items


def score(items: list[dict], answers: list[dict], *, answered_only: bool = False) -> dict:
    by_id = {}
    for row in answers:
        by_id[row["id"]] = row
    unknown = sorted(set(by_id) - {i["id"] for i in items})
    if answered_only:
        items = [i for i in items if i["id"] in by_id]
    groups: dict[str, dict[str, list[int]]] = defaultdict(lambda: defaultdict(lambda: [0, 0]))
    details = []
    for item in items:
        ok, reason = check(item, by_id.get(item["id"]))
        details.append({"id": item["id"], "correct": ok, "reason": reason})
        for group, key in (
            ("overall", "all"),
            ("qtype", item["qtype"]),
            ("expected_state", item["expected"]["state"]),
            ("difficulty", item["difficulty"]),
        ):
            groups[group][key][0] += ok
            groups[group][key][1] += 1
    report = {
        "eval_version": items[0]["eval_version"] if items else EVAL_VERSION,
        "items": len(items),
        "answers": len(by_id),
        "unknown_ids": unknown,
        "missing": sum(1 for d in details if d["reason"] == "missing"),
    }
    for group, values in groups.items():
        report[group] = {
            k: {"correct": c, "total": t, "accuracy": round(c / t, 4) if t else None}
            for k, (c, t) in sorted(values.items())
        }
    report["details"] = details
    return report


def table(report: dict) -> str:
    lines = [
        f"{report['eval_version']}: {report['overall']['all']['correct']}/"
        f"{report['items']} correct ({report['overall']['all']['accuracy']:.1%}),"
        f" {report['missing']} missing"
    ]
    for group in ("qtype", "expected_state", "difficulty"):
        lines.append(f"\nby {group}:")
        for key, value in report.get(group, {}).items():
            lines.append(
                f"  {key:<24} {value['correct']:>4}/{value['total']:<4} {value['accuracy']:.1%}"
            )
    return "\n".join(lines)


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description="Score answers against dd-eval-v1 items")
    parser.add_argument("answers", type=Path)
    parser.add_argument("--items", type=Path, default=ITEMS)
    parser.add_argument("--answered-only", action="store_true", help="score only answered ids")
    parser.add_argument("--json", action="store_true")
    args = parser.parse_args(argv)
    answers = [json.loads(line) for line in args.answers.read_text().splitlines() if line.strip()]
    report = score(load_items(args.items), answers, answered_only=args.answered_only)
    if args.json:
        print(json.dumps({k: v for k, v in report.items() if k != "details"}, indent=1))
    else:
        print(table(report))
    return 0


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