#!/usr/bin/env python3
"""Lab: how much does a clean retest prove for a non-deterministic system?

Exact binomial arithmetic only; standard library; deterministic output.
Usage:  python3 bounds.py [--out results.json]
"""
from __future__ import annotations

import argparse
import json
import math
import random
from pathlib import Path


def binom_cdf(k: int, n: int, p: float) -> float:
    """P(X <= k) for X ~ Binomial(n, p), summed in log space."""
    if p <= 0:
        return 1.0
    if p >= 1:
        return 1.0 if k >= n else 0.0
    total = 0.0
    for i in range(0, k + 1):
        total += math.exp(
            math.lgamma(n + 1) - math.lgamma(i + 1) - math.lgamma(n - i + 1)
            + i * math.log(p) + (n - i) * math.log1p(-p)
        )
    return min(1.0, total)


def upper_bound(x: int, n: int, conf: float = 0.95) -> float:
    """One-sided exact (Clopper-Pearson) upper bound for a success rate."""
    if x >= n:
        return 1.0
    alpha = 1 - conf
    if x == 0:
        return 1 - alpha ** (1 / n)
    lo, hi = x / n, 1.0
    for _ in range(80):  # bisection on P(X <= x | p) = alpha
        mid = (lo + hi) / 2
        if binom_cdf(x, n, mid) > alpha:
            lo = mid
        else:
            hi = mid
    return hi


def runs_needed(target: float, conf: float = 0.95) -> int:
    """Clean runs needed so the upper bound on the success rate is <= target."""
    return math.ceil(math.log(1 - conf) / math.log1p(-target))


def at_least_one(p: float, k: int) -> float:
    return 1 - (1 - p) ** k


def coverage(p: float, n: int, conf: float, trials: int, rng: random.Random) -> float:
    """Share of simulated retests whose upper bound is >= the true rate."""
    ok = 0
    for _ in range(trials):
        x = sum(rng.random() < p for _ in range(n))
        ok += upper_bound(x, n, conf) >= p
    return ok / trials


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--out", default=str(Path(__file__).with_name("results.json")))
    args = ap.parse_args()
    rng = random.Random(20261122)

    clean_runs = [1, 3, 5, 10, 20, 30, 50, 59, 100, 200, 299, 500, 1000]
    zero_fail = [
        {
            "clean_runs": n,
            "upper_95": upper_bound(0, n, 0.95),
            "upper_99": upper_bound(0, n, 0.99),
            "rule_of_three": min(1.0, 3 / n),
        }
        for n in clean_runs
    ]
    targets = [0.20, 0.10, 0.05, 0.02, 0.01, 0.005, 0.001]
    needed = [
        {"target_rate": t, "runs_95": runs_needed(t, 0.95), "runs_99": runs_needed(t, 0.99)}
        for t in targets
    ]
    rates = [0.001, 0.005, 0.01, 0.05, 0.10]
    attempts = [1, 10, 50, 100, 200, 1000]
    amplification = [
        {"per_attempt_rate": p, **{f"k{k}": at_least_one(p, k) for k in attempts}} for p in rates
    ]
    # A fix that lowers the success rate from 30 % to 3 % is a real improvement,
    # and still an open hole. How often does a short retest call each one "not reproduced"?
    blind = [
        {
            "runs": n,
            "p_clean_if_rate_30pct": (1 - 0.30) ** n,
            "p_clean_if_rate_3pct": (1 - 0.03) ** n,
            "p_clean_if_rate_0_5pct": (1 - 0.005) ** n,
        }
        for n in [1, 3, 5, 10, 20, 50, 100, 300]
    ]
    partial = [
        {"successes": x, "runs": n, "observed": x / n, "upper_95": upper_bound(x, n, 0.95)}
        for x, n in [(0, 40), (1, 40), (2, 40), (0, 200), (2, 200), (5, 200)]
    ]
    check = [
        {"true_rate": p, "runs": n, "trials": 4000, "coverage_95": coverage(p, n, 0.95, 4000, rng)}
        for p, n in [(0.01, 59), (0.03, 30), (0.05, 100), (0.10, 20)]
    ]
    report = {
        "lab": "retest-bounds",
        "definitions": {
            "upper_95": "one-sided exact binomial upper bound on the per-attempt success rate, 95 % confidence",
            "at_least_one": "probability of one or more successes in k independent attempts",
            "coverage_95": "share of simulated retests where the bound is at or above the true rate (seed 20261122)",
        },
        "zero_failure_bounds": zero_fail,
        "clean_runs_needed": needed,
        "attacker_attempts": {"attempts": attempts, "rows": amplification},
        "short_retest_blindness": blind,
        "bounds_with_failures": partial,
        "coverage_check": check,
    }
    Path(args.out).write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")

    print("clean runs -> 95 % upper bound on success rate (rule of three)")
    for row in zero_fail:
        print(f"  {row['clean_runs']:>5}  {row['upper_95']:8.4%}  ({row['rule_of_three']:.4%})")
    print("target rate -> clean runs needed at 95 % / 99 %")
    for row in needed:
        print(f"  {row['target_rate']:7.3%}  {row['runs_95']:>5}  {row['runs_99']:>5}")
    print("per-attempt rate -> P(at least one success) after k attempts", attempts)
    for row in amplification:
        print("  %6.2f%%  " % (row["per_attempt_rate"] * 100) + "  ".join(f"{row[f'k{k}']:7.2%}" for k in attempts))
    print("runs -> P(retest is clean) if true rate is 30 % / 3 % / 0.5 %")
    for row in blind:
        print(f"  {row['runs']:>4}  {row['p_clean_if_rate_30pct']:8.3%}  {row['p_clean_if_rate_3pct']:8.3%}  {row['p_clean_if_rate_0_5pct']:8.3%}")
    print("coverage check:", ", ".join(f"p={c['true_rate']} n={c['runs']}: {c['coverage_95']:.3f}" for c in check))


if __name__ == "__main__":
    main()
