"""
Practice: the measurements behind Lab 01's scripts 03_what_ci_catches.py and 04_corpus_budget.py.
You'll split records into batches, decide when a test catches a mutant, count where mutants survive,
and work out how precise a reviewer's score can be with 173 planted bugs.

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


def batch_sizes(n_records: int, size: int) -> list[int]:
    """The batches a send makes: n_records split into batches of at most `size`, in order.
    batch_sizes(13, 4) == [4, 4, 4, 1]. No records means no batches."""
    return [min(size, n_records - start) for start in range(0, n_records, size)]


def caught(original, mutant, inputs: list) -> bool:
    """A test catches a mutant when, on at least one of the inputs it tries, the mutant gives a
    different result from the original. original and mutant are functions of one argument. If the
    mutant raises an exception where the original doesn't, that counts as different too.
    Return True if caught, False if the mutant survives these inputs."""
    for x in inputs:
        want = original(x)
        try:
            got = mutant(x)
        except Exception:
            return True
        if got != want:
            return True
    return False


def survival_by(rows: list[dict], key: str) -> dict:
    """rows: one dict per mutant, with at least `key` and "caught_by" (None when it survived CI).
    Return {value of key: (survived, total)} for every value that appears."""
    out: dict = {}
    for r in rows:
        s, n = out.get(r[key], (0, 0))
        out[r[key]] = (s + (r["caught_by"] is None), n + 1)
    return out


def wilson(k: float, n: int, z: float = 1.96) -> tuple[float, float]:
    """The 95% Wilson score interval for k successes out of n, as (low, high), both within [0, 1].
    With p = k / n:
        centre = (p + z²/(2n)) / (1 + z²/n)
        half   = z * sqrt(p(1-p)/n + z²/(4n²)) / (1 + z²/n)
    Return (max(0, centre - half), min(1, centre + half)). With n == 0, return (0.0, 1.0)."""
    if n == 0:
        return (0.0, 1.0)
    p = k / n
    denom = 1 + z**2 / n
    centre = (p + z**2 / (2 * n)) / denom
    half = z * math.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / denom
    return (max(0.0, centre - half), min(1.0, centre + half))


def bugs_needed(recall: float, half_width: float) -> int:
    """The smallest number of bugs n for which a reviewer who finds `recall` of them gets a Wilson
    interval no wider than ±half_width (half of high - low). Use k = recall * n, not rounded."""
    n = 1
    while True:
        lo, hi = wilson(recall * n, n)
        if (hi - lo) / 2 <= half_width:
            return n
        n += 1
