"""Lesson 7: is the difference real? Confidence intervals and paired tests, standard library only."""
from __future__ import annotations

import math
import random
from statistics import mean


def bootstrap_ci(values: list[float], confidence: float = 0.95, iterations: int = 2000,
                 seed: int = 0) -> tuple[float, float, float]:
    """(mean, low, high) percentile bootstrap confidence interval for the mean."""
    if not values:
        raise ValueError("no values")
    rng = random.Random(seed)
    n = len(values)
    means = sorted(mean(rng.choices(values, k=n)) for _ in range(iterations))
    alpha = (1 - confidence) / 2
    lo = means[int(alpha * iterations)]
    hi = means[min(iterations - 1, int((1 - alpha) * iterations))]
    return mean(values), lo, hi


def paired_bootstrap(a: list[float], b: list[float], iterations: int = 2000, seed: int = 0) -> dict:
    """Compare two systems scored on the SAME cases. Returns the mean difference (b - a),
    its 95% interval, and how often b beat a across resamples."""
    if len(a) != len(b) or not a:
        raise ValueError("need two equal-length, non-empty score lists")
    rng = random.Random(seed)
    diffs = [y - x for x, y in zip(a, b)]
    n = len(diffs)
    boots = sorted(mean(rng.choices(diffs, k=n)) for _ in range(iterations))
    return {"mean_diff": mean(diffs), "low": boots[int(0.025 * iterations)],
            "high": boots[min(iterations - 1, int(0.975 * iterations))],
            "prob_b_better": sum(d > 0 for d in boots) / iterations}


def mcnemar_exact(a_pass: list[bool], b_pass: list[bool]) -> dict:
    """Exact McNemar test for paired pass/fail results. Only discordant cases matter:
    b01 = a failed & b passed, b10 = a passed & b failed. Two-sided binomial p-value."""
    if len(a_pass) != len(b_pass):
        raise ValueError("lists must have equal length")
    b01 = sum((not x) and y for x, y in zip(a_pass, b_pass))
    b10 = sum(x and (not y) for x, y in zip(a_pass, b_pass))
    n = b01 + b10
    if n == 0:
        return {"b01": 0, "b10": 0, "p_value": 1.0}
    k = min(b01, b10)
    tail = sum(math.comb(n, i) for i in range(k + 1)) / 2 ** n
    return {"b01": b01, "b10": b10, "p_value": min(1.0, 2 * tail)}


def cohens_kappa(rater1: list, rater2: list) -> float:
    """Agreement between two raters (e.g. an LLM judge and a human) beyond chance. 1 = perfect, 0 = chance."""
    if len(rater1) != len(rater2) or not rater1:
        raise ValueError("need two equal-length, non-empty label lists")
    n = len(rater1)
    labels = set(rater1) | set(rater2)
    observed = sum(x == y for x, y in zip(rater1, rater2)) / n
    expected = sum((rater1.count(l) / n) * (rater2.count(l) / n) for l in labels)
    return 1.0 if expected == 1 else (observed - expected) / (1 - expected)


def min_detectable_difference(n: int, p: float = 0.8, z: float = 1.96) -> float:
    """Rough half-width of a 95% interval for a pass rate p measured on n cases.
    Differences smaller than about this are hard to distinguish from noise."""
    return z * math.sqrt(p * (1 - p) / n)
