"""
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."""
    # TODO
    raise NotImplementedError


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%)."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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)"""
    # TODO
    raise NotImplementedError


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'."""
    # TODO
    raise NotImplementedError


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)."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError
