"""Lesson 8: run a system over a test set, save results, compare runs, gate releases."""
from __future__ import annotations

import json
import time
from dataclasses import asdict, dataclass, field
from pathlib import Path
from typing import Callable

from .dataset import Case

Scorer = Callable[[Case, str], float]   # (case, output) -> score in [0, 1]


@dataclass
class CaseResult:
    id: str
    output: str
    scores: dict[str, float]
    passed: bool
    latency_ms: float
    tags: list[str] = field(default_factory=list)
    error: str | None = None


def run(system: Callable[[str], str], cases: list[Case], scorers: dict[str, Scorer],
        pass_rule: Callable[[dict[str, float]], bool] | None = None) -> list[CaseResult]:
    pass_rule = pass_rule or (lambda s: all(v >= 1.0 for v in s.values()))
    results = []
    for case in cases:
        t0 = time.perf_counter()
        try:
            output, error = system(case.input), None
        except Exception as exc:  # a crash is a failed case, not a crashed eval run
            output, error = "", f"{type(exc).__name__}: {exc}"
        latency = (time.perf_counter() - t0) * 1000
        scores = {name: (0.0 if error else float(fn(case, output))) for name, fn in scorers.items()}
        results.append(CaseResult(case.id, output, scores, (error is None) and pass_rule(scores),
                                  round(latency, 2), case.tags, error))
    return results


def summarize(results: list[CaseResult]) -> dict:
    n = len(results)
    names = results[0].scores.keys() if results else []
    summary = {"cases": n, "pass_rate": sum(r.passed for r in results) / n if n else 0.0,
               "errors": sum(r.error is not None for r in results)}
    for name in names:
        summary[f"mean_{name}"] = sum(r.scores[name] for r in results) / n
    tags: dict[str, list[bool]] = {}
    for r in results:
        for t in r.tags or ["untagged"]:
            tags.setdefault(t, []).append(r.passed)
    summary["pass_rate_by_tag"] = {t: sum(v) / len(v) for t, v in sorted(tags.items())}
    return summary


def save(results: list[CaseResult], path: str | Path) -> None:
    Path(path).write_text("\n".join(json.dumps(asdict(r)) for r in results) + "\n", encoding="utf-8")


def load(path: str | Path) -> list[CaseResult]:
    return [CaseResult(**json.loads(l)) for l in Path(path).read_text(encoding="utf-8").splitlines() if l.strip()]


def compare_runs(baseline: list[CaseResult], candidate: list[CaseResult]) -> dict:
    """Which cases newly fail (regressions) or newly pass (fixes)?"""
    base = {r.id: r for r in baseline}
    regressions = [r.id for r in candidate if r.id in base and base[r.id].passed and not r.passed]
    fixes = [r.id for r in candidate if r.id in base and not base[r.id].passed and r.passed]
    new_cases = [r.id for r in candidate if r.id not in base]
    return {"regressions": regressions, "fixes": fixes, "new_cases": new_cases,
            "baseline_pass_rate": summarize(baseline)["pass_rate"],
            "candidate_pass_rate": summarize(candidate)["pass_rate"]}


def gate(comparison: dict, *, max_regressions: int = 0, min_pass_rate: float = 0.0) -> tuple[bool, str]:
    """Release gate for CI: fail on too many regressions or a pass rate below the floor."""
    if len(comparison["regressions"]) > max_regressions:
        return False, f"{len(comparison['regressions'])} regression(s): {', '.join(comparison['regressions'])}"
    if comparison["candidate_pass_rate"] < min_pass_rate:
        return False, f"pass rate {comparison['candidate_pass_rate']:.2f} below {min_pass_rate:.2f}"
    return True, "ok"
