# /// script
# requires-python = ">=3.10"
# dependencies = ["pyyaml>=6", "jsonschema[format-nongpl]>=4.18"]
# ///
"""Check and score an open coding agent benchmark scorecard.

Validates task-spec.yaml against task-spec.schema.json, validates runs.csv
against the run log columns and the scorecard's validation checklist, then
computes summary.csv from runs.csv. Run it from the scorecard folder:

    uv run check.py            # check everything, compare with summary.csv
    uv run check.py --write    # check, then (re)write summary.csv

Formulas and column definitions: https://autorouter.com/blog/coding-agent-benchmark-scorecard
"""

import argparse
import csv
import json
import math
import statistics
import sys
from datetime import date
from pathlib import Path

import yaml
from jsonschema import Draft202012Validator

# -----------------------------------------------------------------------------
# Main export
# -----------------------------------------------------------------------------


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument("folder", nargs="?", default=Path(__file__).parent, type=Path)
    parser.add_argument("--write", action="store_true", help="write summary.csv")
    args = parser.parse_args()
    folder: Path = args.folder

    errors: list[str] = []
    warnings: list[str] = []

    task_ids = check_task_spec(folder, errors, warnings)
    runs = check_runs(folder, errors, warnings)
    if runs and task_ids:
        missing = sorted(task_ids - {r["task_id"] for r in runs})
        if missing:
            warnings.append(f"tasks in task-spec.yaml with no runs: {', '.join(missing)}")

    summary = summarize(runs) if runs and not errors else []
    if summary:
        path = folder / "summary.csv"
        if args.write:
            write_csv(path, SUMMARY_COLUMNS, summary)
            print(f"wrote {path}")
        elif path.exists():
            with path.open(newline="") as f:
                if list(csv.DictReader(f)) != summary:
                    errors.append("summary.csv does not match runs.csv; rerun with --write")
        print_table(summary)

    for w in warnings:
        print(f"warning: {w}")
    for e in errors:
        print(f"error: {e}")
    print("ok" if not errors else f"{len(errors)} error(s)")
    return 1 if errors else 0


# -----------------------------------------------------------------------------
# Helpers
# -----------------------------------------------------------------------------

RUN_COLUMNS = {
    "run_id": str,
    "task_id": str,
    "setup_id": str,
    "run": int,
    "date": date.fromisoformat,
    "harness": str,
    "harness_version": str,
    "model": str,
    "effort": str,
    "passed": bool,
    "grader_notes": str,
    "wall_time_s": float,
    "input_tokens": int,
    "output_tokens": int,
    "cached_tokens": int,
    "cost_usd": float,
    "tool_calls": int,
    "human_interventions": int,
    "illustrative": bool,
}

SUMMARY_COLUMNS = [
    "setup_id",
    "harness",
    "harness_version",
    "model",
    "effort",
    "tasks",
    "runs_per_task",
    "runs",
    "passed_runs",
    "pass_rate",
    "pass_rate_ci_low",
    "pass_rate_ci_high",
    "solved_tasks",
    "total_cost_usd",
    "cost_per_solved_task_usd",
    "median_wall_time_s",
    "flaky_tasks",
    "flakiness_rate",
    "illustrative",
]

SETTING_COLUMNS = ("harness", "harness_version", "model", "effort")
MIN_RUNS_PER_TASK = 3
Z_95 = 1.959964


def check_task_spec(folder: Path, errors: list[str], warnings: list[str]) -> set[str]:
    schema = json.loads((folder / "task-spec.schema.json").read_text())
    spec = yaml.safe_load((folder / "task-spec.yaml").read_text())
    validator = Draft202012Validator(schema, format_checker=Draft202012Validator.FORMAT_CHECKER)
    for err in sorted(validator.iter_errors(spec), key=lambda e: list(e.path)):
        where = "/".join(str(p) for p in err.path) or "(root)"
        errors.append(f"task-spec.yaml {where}: {err.message}")
    tasks = spec.get("tasks", []) if isinstance(spec, dict) else []
    ids = [t.get("id") for t in tasks if isinstance(t, dict)]
    if len(ids) != len(set(ids)):
        errors.append("task-spec.yaml: task ids must be unique")
    for t in tasks:
        v = t.get("validation", {}) if isinstance(t, dict) else {}
        if not (v.get("fails_before_fix") and v.get("passes_after_fix") and v.get("gold_patch_hidden")):
            warnings.append(f"task {t.get('id')}: validation checklist not complete")
    return set(ids)


def check_runs(folder: Path, errors: list[str], warnings: list[str]) -> list[dict]:
    with (folder / "runs.csv").open(newline="") as f:
        reader = csv.DictReader(f)
        if reader.fieldnames != list(RUN_COLUMNS):
            errors.append(f"runs.csv columns must be exactly: {','.join(RUN_COLUMNS)}")
            return []
        raw = list(reader)

    runs = []
    for line, row in enumerate(raw, start=2):
        parsed = {}
        for col, kind in RUN_COLUMNS.items():
            value = row[col]
            if col == "grader_notes":
                parsed[col] = value
                continue
            try:
                parsed[col] = parse(value, kind)
            except ValueError:
                errors.append(f"runs.csv line {line}: {col}={value!r} is not a valid {kind.__name__}")
        if len(parsed) == len(RUN_COLUMNS):
            for col in ("wall_time_s", "input_tokens", "output_tokens", "cached_tokens", "cost_usd", "tool_calls", "human_interventions"):
                if parsed[col] < 0:
                    errors.append(f"runs.csv line {line}: {col} is negative")
            runs.append(parsed)
    if errors:
        return []

    if len({r["run_id"] for r in runs}) != len(runs):
        errors.append("runs.csv: run_id values must be unique")

    by_setup: dict[str, list[dict]] = {}
    for r in runs:
        by_setup.setdefault(r["setup_id"], []).append(r)

    task_sets = {}
    for sid, rows in by_setup.items():
        for col in SETTING_COLUMNS:
            if len({r[col] for r in rows}) > 1:
                errors.append(f"{sid}: {col} changes between runs; give each setting its own setup_id")
        per_task: dict[str, list[int]] = {}
        for r in rows:
            per_task.setdefault(r["task_id"], []).append(r["run"])
        for tid, nums in per_task.items():
            if sorted(nums) != list(range(1, len(nums) + 1)):
                errors.append(f"{sid} {tid}: run numbers must be 1..k with no gaps or repeats")
        counts = {len(n) for n in per_task.values()}
        if len(counts) > 1:
            errors.append(f"{sid}: every task needs the same number of runs")
        elif min(counts) < MIN_RUNS_PER_TASK:
            warnings.append(f"{sid}: fewer than {MIN_RUNS_PER_TASK} runs per task; flakiness can't be measured")
        task_sets[sid] = frozenset(per_task)

    if len(set(task_sets.values())) > 1:
        errors.append("every setup must run the same set of tasks")
    for col in ("harness", "harness_version"):
        if len({r[col] for r in runs}) > 1:
            warnings.append(f"setups differ in {col}; compare models only within one harness and version")
    if any(r["human_interventions"] for r in runs):
        warnings.append("some runs had human interventions; report them beside the pass rate")
    return runs


def parse(value: str, kind):
    if kind is bool:
        if value not in ("true", "false"):
            raise ValueError
        return value == "true"
    if kind is str:
        if not value.strip():
            raise ValueError
        return value
    return kind(value)


def summarize(runs: list[dict]) -> list[dict]:
    by_setup: dict[str, list[dict]] = {}
    for r in runs:
        by_setup.setdefault(r["setup_id"], []).append(r)

    summary = []
    for sid in sorted(by_setup):
        rows = by_setup[sid]
        per_task: dict[str, list[bool]] = {}
        for r in rows:
            per_task.setdefault(r["task_id"], []).append(r["passed"])
        tasks = len(per_task)
        runs_per_task = len(rows) // tasks
        passed = sum(r["passed"] for r in rows)
        rate = passed / len(rows)
        low, high = wilson(rate, tasks)
        solved = sum(1 for p in per_task.values() if sum(p) * 2 > len(p))
        flaky = sum(1 for p in per_task.values() if 0 < sum(p) < len(p))
        cost = sum(r["cost_usd"] for r in rows)
        first = rows[0]
        summary.append({
            "setup_id": sid,
            **{col: first[col] for col in SETTING_COLUMNS},
            "tasks": str(tasks),
            "runs_per_task": str(runs_per_task),
            "runs": str(len(rows)),
            "passed_runs": str(passed),
            "pass_rate": f"{rate:.3f}",
            "pass_rate_ci_low": f"{low:.3f}",
            "pass_rate_ci_high": f"{high:.3f}",
            "solved_tasks": str(solved),
            "total_cost_usd": f"{cost:.2f}",
            "cost_per_solved_task_usd": f"{cost / passed:.2f}" if passed else "",
            "median_wall_time_s": f"{statistics.median(r['wall_time_s'] for r in rows):.0f}",
            "flaky_tasks": str(flaky),
            "flakiness_rate": f"{flaky / tasks:.3f}",
            "illustrative": "true" if any(r["illustrative"] for r in rows) else "false",
        })
    return summary


def wilson(p: float, n: int) -> tuple[float, float]:
    # n is the number of tasks, not runs: repeated runs of one task are not
    # independent samples, so counting them would make the interval too narrow.
    z2 = Z_95 * Z_95
    center = (p + z2 / (2 * n)) / (1 + z2 / n)
    half = Z_95 * math.sqrt(p * (1 - p) / n + z2 / (4 * n * n)) / (1 + z2 / n)
    return max(0.0, center - half), min(1.0, center + half)


def write_csv(path: Path, columns: list[str], rows: list[dict]) -> None:
    with path.open("w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=columns, lineterminator="\n")
        writer.writeheader()
        writer.writerows(rows)


def print_table(summary: list[dict]) -> None:
    print(f"{'setup':<10} {'pass rate (95% CI)':<22} {'solved':>8} {'$/solved':>9} {'median s':>9} {'flaky':>6}")
    for s in summary:
        ci = f"{float(s['pass_rate']):.0%} ({float(s['pass_rate_ci_low']):.0%}-{float(s['pass_rate_ci_high']):.0%})"
        print(f"{s['setup_id']:<10} {ci:<22} {s['solved_tasks'] + '/' + s['tasks']:>8} "
              f"{s['cost_per_solved_task_usd']:>9} {s['median_wall_time_s']:>9} {float(s['flakiness_rate']):>6.0%}")


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