"""
Practice: confidence intervals for eval scores. Lab 02 (How Many Evals?) of the eval labs:
the interval code in evalkit/stats.py (margin_for_n, wald_ci, wilson_ci, newcombe_diff_ci),
exact coverage from common.py, the cases-for-a-margin table from 01_shrinking_interval.py and
the changelog check from 05_your_results.py.

Fill in the TODOs, then run the tests:
    pytest test_howmany_practice.py        (locally)
or press "Run tests" on the chapter page.

Notation: k = right answers (passes), n = test cases, p = a pass rate between 0 and 1.
Every interval is a (low, high) tuple of rates, 95% unless said otherwise.
"""
import math

Z_95 = 1.959964


def margin_for_n(p, n, z=Z_95):
    """The simplest ± margin for a pass rate: z x sqrt(p(1-p)/n). Half the width of the range."""
    return z * math.sqrt(p * (1 - p) / n)


def wald_ci(k, n, z=Z_95):
    """The simplest formula (Wald): score ± margin_for_n(score, n). Deliberately NOT clipped to
    0..1, so you can see where it breaks (20/20 gives zero width, 19/20 goes past 100%)."""
    p = k / n
    m = margin_for_n(p, n, z)
    return p - m, p + m


def wilson_ci(k, n, z=Z_95):
    """Wilson interval for a pass rate. With s = k/n:
    center = (s + z^2/(2n)) / (1 + z^2/n)
    half   = z * sqrt(s(1-s)/n + z^2/(4n^2)) / (1 + z^2/n)
    Return (max(0, center - half), min(1, center + half)); (0, 1) if n == 0."""
    if n == 0:
        return 0.0, 1.0
    p = k / n
    denom = 1 + z * z / n
    center = (p + z * z / (2 * n)) / denom
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
    return max(0.0, center - half), min(1.0, center + half)


def newcombe_diff_ci(k_a, n_a, k_b, n_b, z=Z_95):
    """Range for (rate B - rate A) when A and B were tested on DIFFERENT cases (Newcombe),
    built from the two Wilson intervals (la, ua) and (lb, ub), with pa = k_a/n_a, pb = k_b/n_b:
    low  = (pb - pa) - sqrt((pb - lb)^2 + (ua - pa)^2)
    high = (pb - pa) + sqrt((ub - pb)^2 + (pa - la)^2)"""
    pa, pb = k_a / n_a, k_b / n_b
    la, ua = wilson_ci(k_a, n_a, z)
    lb, ub = wilson_ci(k_b, n_b, z)
    d = pb - pa
    return (d - math.sqrt((pb - lb) ** 2 + (ua - pa) ** 2),
            d + math.sqrt((ub - pb) ** 2 + (pa - la) ** 2))


def verdict(low, high):
    """'bigger than noise' if the whole range is above zero, 'worse' if it's all below zero,
    otherwise 'could be noise'."""
    if low > 0:
        return "bigger than noise"
    if high < 0:
        return "worse"
    return "could be noise"


def cases_for_margin(margin, p):
    """The fewest cases whose simple ± margin at pass rate p is at most `margin`:
    ceil(Z_95^2 * p(1-p) / margin^2)."""
    return math.ceil(Z_95 ** 2 * p * (1 - p) / margin ** 2)


def binom_pmf(k, n, p):
    """Chance of exactly k right answers out of n when each is right with chance p.
    Given: you don't need to change this."""
    return math.comb(n, k) * p ** k * (1 - p) ** (n - k)


def exact_coverage(interval, n, p):
    """How often interval(k, n) contains the true p, over every possible k = 0..n weighted by
    binom_pmf(k, n, p). Exact: no simulation needed."""
    total = 0.0
    for k in range(n + 1):
        lo, hi = interval(k, n)
        if lo <= p <= hi:
            total += binom_pmf(k, n, p)
    return total


def p_retest_beats(n, p, by_cases):
    """An unchanged system (true rate p) is tested twice on n fresh cases. The chance the second
    score beats the first by at least `by_cases` right answers: sum binom_pmf(a) * binom_pmf(b)
    over every pair with b - a >= by_cases."""
    pm = [binom_pmf(k, n, p) for k in range(n + 1)]
    return sum(pm[a] * pm[b] for a in range(n + 1) for b in range(n + 1) if b - a >= by_cases)
