"""Read your own eval results the way lesson 4.2 does: pass@1, pass^k, and the share of cases that passed every trial,
with a Wilson interval on cases.

    python3 pass_k.py results.csv      # your runs: one row per trial (case_id,passed with 1 or 0)
                                       #        or one row per case  (case_id,passes,trials)
    python3 pass_k.py --cases 18 18    # just the interval: 18 of 18 cases passed every trial

A case is one question with its checks; a trial is one run of it. pass^k is the chance that k tries in a row all pass.
The gate reads the last line: the cases that passed every trial, and the bottom of their 95% interval.
Standard library only. Python 3.9 or later.
"""
# From lesson 4.2 of Cohorte's Trust Engineering (cohorte.co/trust-engineering).
import argparse
import csv
import math
import sys
from collections import defaultdict
from statistics import NormalDist

Z = NormalDist().inv_cdf(0.975)                  # 1.96 for a 95% interval
YES, NO = ("1", "true", "pass"), ("0", "false", "fail")


def wilson(passes: float, n: float) -> tuple:
    """Wilson score interval: honest at 0 and at n, where the school formula says 'plus or minus nothing'."""
    if n == 0:
        return 0.0, 1.0
    p = passes / n
    centre = (p + Z * Z / (2 * n)) / (1 + Z * Z / n)
    half = Z * math.sqrt(p * (1 - p) / n + Z * Z / (4 * n * n)) / (1 + Z * Z / n)
    return max(0.0, centre - half), min(1.0, centre + half)


def pass_hat_k(cases: list, k: int) -> float:
    """Mean over cases of C(c, k) / C(n, k): the chance that k trials drawn from a case's n all passed."""
    return sum(math.comb(c, k) / math.comb(n, k) for c, n in cases) / len(cases)


def read(path: str) -> list:
    per_trial, per_case = defaultdict(lambda: [0, 0]), []
    with open(path, newline="", encoding="utf-8") as f:
        for row in csv.reader(f):
            row = [x.strip() for x in row if x.strip()]
            if not row or row[0].startswith("#"):
                continue
            try:
                if len(row) == 2:
                    v = row[1].lower()
                    if v not in YES + NO:
                        if per_trial or per_case:
                            sys.exit(f"Can't read {row[1]!r} as a pass or a fail (use 1/0, true/false or pass/fail).")
                        continue                      # a header row
                    per_trial[row[0]][0] += v in YES
                    per_trial[row[0]][1] += 1
                elif len(row) == 3:
                    per_case.append((int(row[1]), int(row[2])))
                else:
                    sys.exit(f"Each row needs 2 columns (case_id,passed) or 3 (case_id,passes,trials): {row}")
            except ValueError:
                continue                              # a header row
    cases = per_case + [tuple(v) for v in per_trial.values()]
    if not cases:
        sys.exit(f"No results found in {path}.")
    if any(not 0 <= c <= n or n == 0 for c, n in cases):
        sys.exit("Each case needs 0 <= passes <= trials and at least one trial.")
    return cases


def report(cases: list) -> None:
    n = len(cases)
    k = min(t for _, t in cases)
    if len({t for _, t in cases}) > 1:
        print(f"Trials per case differ; pass^k uses k up to {k}, the smallest count.")
    print(f"{n} cases, {k} trials per case")
    print(f"pass@1   {sum(c / t for c, t in cases) / n:6.1%}   (the average over trials)")
    for j in range(2, k + 1):
        print(f"pass^{j}   {pass_hat_k(cases, j):6.1%}")
    full = sum(c == t for c, t in cases)
    lo, hi = wilson(full, n)
    print(f"all {k} trials passed   {full}/{n}   95% interval {lo:.1%} to {hi:.1%}")
    print(f"Gate on {lo:.1%}, the bottom of that interval.")
    if full == n:
        need = math.ceil(0.95 * Z * Z / 0.05)
        print(f"With no failures, {need} cases are needed before that bottom reaches 95%.")


def main() -> None:
    ap = argparse.ArgumentParser(description="pass@1, pass^k and a Wilson interval on cases, from your eval results.")
    ap.add_argument("csv", nargs="?", help="results: case_id,passed per trial, or case_id,passes,trials per case")
    ap.add_argument("--cases", nargs=2, type=int, metavar=("PASSED", "TOTAL"),
                    help="only the interval: cases that passed every trial, out of all cases")
    a = ap.parse_args()
    if a.cases:
        full, n = a.cases
        if not 0 <= full <= n or n == 0:
            sys.exit("Need 0 <= PASSED <= TOTAL and TOTAL > 0.")
        lo, hi = wilson(full, n)
        print(f"{full}/{n} cases passed every trial: 95% interval {lo:.1%} to {hi:.1%}. Gate on {lo:.1%}.")
        return
    if not a.csv:
        ap.error("give a results file, or --cases PASSED TOTAL")
    report(read(a.csv))


if __name__ == "__main__":
    main()
