"""Evals for agents: golden tasks, outcome and trajectory scoring, a judge.

Agents need one thing ordinary LLM evals do not: the *path* matters, not only the
answer. An agent that returns the right answer after calling a refund tool six
times is not a working agent. So every case here can assert on both the output
and the trajectory.

The tiering the course argues for, cheapest first:

    1. assertions      deterministic, free, run on every commit
    2. reference       a ground truth exists - exact or field match
    3. judged          a model grades against a rubric, validated against humans
    4. human           the gold standard, sampled, not on every commit

`Suite.run` returns a Report with a per-case breakdown, because an aggregate
score tells you nothing about what to fix next.
"""

from __future__ import annotations

import json
import re
import statistics
from dataclasses import dataclass, field
from typing import Any, Callable, Iterable

from .loop import Run, Stop
from .model import Message, Model


# --------------------------------------------------------------------------
# Checks
# --------------------------------------------------------------------------

#: A check receives the Run and returns (passed, detail).
Check = Callable[[Run], tuple[bool, str]]


def answered() -> Check:
    def check(run: Run) -> tuple[bool, str]:
        return run.ok, f"stop={run.stop.value}"

    check.__name__ = "answered"
    return check


def contains(*needles: str, case_sensitive: bool = False) -> Check:
    def check(run: Run) -> tuple[bool, str]:
        text = run.output if case_sensitive else run.output.lower()
        wanted = needles if case_sensitive else tuple(n.lower() for n in needles)
        missing = [n for n in wanted if n not in text]
        return not missing, f"missing={missing}" if missing else "all present"

    check.__name__ = f"contains{needles}"
    return check


def excludes(*needles: str) -> Check:
    def check(run: Run) -> tuple[bool, str]:
        low = run.output.lower()
        found = [n for n in needles if n.lower() in low]
        return not found, f"found={found}" if found else "none present"

    check.__name__ = f"excludes{needles}"
    return check


def used_tools(*names: str) -> Check:
    """Every named tool appears somewhere in the trajectory."""

    def check(run: Run) -> tuple[bool, str]:
        traj = run.trajectory()
        missing = [n for n in names if n not in traj]
        return not missing, f"trajectory={traj}"

    check.__name__ = f"used_tools{names}"
    return check


def never_used(*names: str) -> Check:
    """No named tool EXECUTED. This is how you test a guardrail.

    Scores the trajectory, i.e. what actually ran. A blocked call passes, which is
    the correct outcome: the guardrail did its job. If you also want to know the
    model *tried*, use `never_requested` - the two together distinguish "the
    attack never landed" from "the attack never started".
    """

    def check(run: Run) -> tuple[bool, str]:
        traj = run.trajectory()
        found = [n for n in names if n in traj]
        blocked = [n for n in names if n in run.blocked_tools()]
        detail = f"executed={found}" if found else f"trajectory={traj} blocked={blocked}"
        return not found, detail

    check.__name__ = f"never_used{names}"
    return check


def never_requested(*names: str) -> Check:
    """The model did not even ask for the tool. Stricter than never_used.

    Useful for measuring containment separately from prevention: an injection
    that makes the model request a refund is a partial success for the attacker
    even when the registry denies it, and you want that visible in a metric.
    """

    def check(run: Run) -> tuple[bool, str]:
        requested = run.requested_tools()
        found = [n for n in names if n in requested]
        return not found, f"requested={requested}"

    check.__name__ = f"never_requested{names}"
    return check


def trajectory_is(*names: str) -> Check:
    """Exact tool sequence. Strict - use when the order genuinely matters."""

    def check(run: Run) -> tuple[bool, str]:
        traj = tuple(run.trajectory())
        return traj == names, f"got={list(traj)} want={list(names)}"

    check.__name__ = f"trajectory_is{names}"
    return check


def max_steps(n: int) -> Check:
    def check(run: Run) -> tuple[bool, str]:
        return run.step_count <= n, f"steps={run.step_count} limit={n}"

    check.__name__ = f"max_steps({n})"
    return check


def max_cost(limit: float) -> Check:
    """Cost is correctness. A right answer that cost ten times budget failed."""

    def check(run: Run) -> tuple[bool, str]:
        return run.cost <= limit, f"cost={run.cost:.6f} limit={limit}"

    check.__name__ = f"max_cost({limit})"
    return check


def stopped_with(stop: Stop) -> Check:
    def check(run: Run) -> tuple[bool, str]:
        return run.stop is stop, f"stop={run.stop.value}"

    check.__name__ = f"stopped_with({stop.value})"
    return check


def valid_json(required_keys: Iterable[str] = ()) -> Check:
    def check(run: Run) -> tuple[bool, str]:
        try:
            payload = json.loads(run.output)
        except (TypeError, ValueError) as exc:
            return False, f"not json: {exc}"
        if not isinstance(payload, dict):
            return False, f"expected object, got {type(payload).__name__}"
        missing = [k for k in required_keys if k not in payload]
        return not missing, f"missing_keys={missing}" if missing else "ok"

    check.__name__ = "valid_json"
    return check


def abstained(*markers: str) -> Check:
    """The agent declined rather than bluffing.

    A retrieval agent with a zero abstention rate is not accurate, it is
    guessing on the questions its corpus cannot answer.
    """
    markers = markers or ("i don't know", "insufficient", "could not find", "not in the")

    def check(run: Run) -> tuple[bool, str]:
        low = run.output.lower()
        hit = [m for m in markers if m in low]
        return bool(hit), f"matched={hit}"

    check.__name__ = "abstained"
    return check


# --------------------------------------------------------------------------
# Cases and suites
# --------------------------------------------------------------------------


@dataclass
class Case:
    """One golden task.

    `why` is required in spirit: a case with no recorded reason for existing is a
    case nobody dares delete when it goes stale.
    """

    id: str
    task: str
    checks: list[Check] = field(default_factory=list)
    tags: tuple[str, ...] = ()
    why: str = ""


@dataclass
class CaseResult:
    case: Case
    run: Run
    failures: list[str] = field(default_factory=list)

    @property
    def passed(self) -> bool:
        return not self.failures


@dataclass
class Report:
    results: list[CaseResult]

    @property
    def total(self) -> int:
        return len(self.results)

    @property
    def passed(self) -> int:
        return sum(1 for r in self.results if r.passed)

    @property
    def pass_rate(self) -> float:
        return self.passed / self.total if self.total else 0.0

    @property
    def failures(self) -> list[CaseResult]:
        return [r for r in self.results if not r.passed]

    def cost(self) -> float:
        return sum(r.run.cost for r in self.results)

    def mean_steps(self) -> float:
        return statistics.mean([r.run.step_count for r in self.results]) if self.results else 0.0

    def by_tag(self) -> dict[str, float]:
        """Pass rate per tag.

        The aggregate hides compensating movement - one category improving while
        another regresses. This is the breakdown you actually read.
        """
        buckets: dict[str, list[bool]] = {}
        for r in self.results:
            for tag in r.case.tags or ("untagged",):
                buckets.setdefault(tag, []).append(r.passed)
        return {t: sum(v) / len(v) for t, v in sorted(buckets.items())}

    def summary(self) -> str:
        lines = [
            f"{self.passed}/{self.total} passed  ({self.pass_rate:.0%})",
            f"mean steps {self.mean_steps():.1f}   total cost {self.cost():.6f}",
        ]
        if by_tag := self.by_tag():
            lines.append("by tag: " + "  ".join(f"{t}={v:.0%}" for t, v in by_tag.items()))
        for r in self.failures:
            lines.append(f"  FAIL {r.case.id}: {'; '.join(r.failures)}")
        return "\n".join(lines)

    def regressed_against(self, baseline: "Report") -> list[str]:
        """Case ids that passed in the baseline and fail now.

        Comparing against the version already shipped is the only comparison that
        matters. An absolute score is not interpretable on its own.
        """
        was = {r.case.id for r in baseline.results if r.passed}
        now = {r.case.id for r in self.results if r.passed}
        return sorted(was - now)


class Suite:
    """A versioned set of golden cases, run against an agent factory.

    The factory is a callable so each case gets a clean agent - shared state
    between cases is how an eval suite starts lying to you.
    """

    def __init__(self, cases: list[Case], name: str = "suite", version: int = 1) -> None:
        self.cases = cases
        self.name = name
        self.version = version

    def filter(self, tag: str) -> "Suite":
        return Suite(
            [c for c in self.cases if tag in c.tags], name=f"{self.name}:{tag}", version=self.version
        )

    def run(self, build_agent: Callable[[], Any]) -> Report:
        results: list[CaseResult] = []
        for case in self.cases:
            agent = build_agent()
            run = agent.run(case.task)
            failures: list[str] = []
            for check in case.checks:
                try:
                    ok, detail = check(run)
                except Exception as exc:  # a broken check must not kill the suite
                    ok, detail = False, f"check raised {type(exc).__name__}: {exc}"
                if not ok:
                    failures.append(f"{getattr(check, '__name__', 'check')} -> {detail}")
            results.append(CaseResult(case=case, run=run, failures=failures))
        return Report(results)


# --------------------------------------------------------------------------
# Judge
# --------------------------------------------------------------------------

JUDGE_TEMPLATE = """You are grading one answer against a rubric.

Rubric:
{rubric}

Question:
{task}

Answer:
{answer}

Write at most two sentences of justification, quoting the decisive part of the
answer. Then on the final line write exactly one of:
VERDICT: pass
VERDICT: fail
"""

_VERDICT = re.compile(r"VERDICT:\s*(pass|fail)", re.IGNORECASE)


@dataclass
class Verdict:
    passed: bool
    justification: str
    raw: str


class Judge:
    """A model grading output against a written rubric.

    Two design choices carried from the course:

    - Binary verdict, not a 1-10 score. Scores cluster in a narrow band and
      regressions hide inside the clump.
    - Justification BEFORE the verdict, so the reasoning constrains the verdict
      rather than rationalising it, and so the judge is auditable.

    `agreement` is not optional. An unvalidated judge is an unmeasured
    instrument - it emits confident numbers whose relationship to the quality you
    care about is unknown.
    """

    def __init__(self, model: Model, rubric: str, version: int = 1) -> None:
        self.model = model
        self.rubric = rubric
        self.version = version

    def grade(self, task: str, answer: str) -> Verdict:
        prompt = JUDGE_TEMPLATE.format(rubric=self.rubric, task=task, answer=answer)
        text = self.model.complete(
            [Message(role="user", content=prompt)], max_output_tokens=300
        ).text
        m = _VERDICT.search(text)
        if not m:
            # An unparseable verdict is a failure of the instrument, not a pass.
            return Verdict(False, "judge returned no parseable verdict", text)
        justification = _VERDICT.split(text)[0].strip()
        return Verdict(m.group(1).lower() == "pass", justification, text)

    def as_check(self) -> Check:
        def check(run: Run) -> tuple[bool, str]:
            task = next(
                (m.content for m in reversed(run.messages) if m.role == "user"), ""
            )
            v = self.grade(task, run.output)
            return v.passed, v.justification[:200]

        check.__name__ = f"judge(v{self.version})"
        return check

    def agreement(self, labelled: list[tuple[str, str, bool]]) -> dict[str, float]:
        """Measure this judge against human labels.

        `labelled` is (task, answer, human_verdict). Returns raw agreement plus
        Cohen's kappa, because raw agreement flatters a lenient judge on a
        mostly-good set: a judge that always says "pass" scores high and is
        worthless. Also returns the confusion counts, since a judge that never
        false-passes but sometimes false-fails is much safer as a release gate
        than the reverse, and one number hides that asymmetry.
        """
        tp = tn = fp = fn = 0
        for task, answer, human in labelled:
            judged = self.grade(task, answer).passed
            if judged and human:
                tp += 1
            elif not judged and not human:
                tn += 1
            elif judged and not human:
                fp += 1
            else:
                fn += 1

        n = tp + tn + fp + fn
        if n == 0:
            return {"n": 0, "agreement": 0.0, "kappa": 0.0}

        observed = (tp + tn) / n
        p_judge_pass = (tp + fp) / n
        p_human_pass = (tp + fn) / n
        expected = p_judge_pass * p_human_pass + (1 - p_judge_pass) * (1 - p_human_pass)
        kappa = 0.0 if expected >= 1.0 else (observed - expected) / (1 - expected)

        return {
            "n": n,
            "agreement": observed,
            "kappa": kappa,
            "false_pass": fp,   # judge said pass, human said fail - the dangerous one
            "false_fail": fn,
        }