"""
Solution: the QA agent's alarm rules from Lab 18's script 03 (qa.py). Every rule is set from
baseline runs 1-3 of the unchanged assistant; a "night" is one real run of the 195-test suite,
a list of True (pass) / False (fail), one per test.
"""
import math


def reference(cal: list[list[bool]]) -> list[bool]:
    """The paired test's reference: what each test did in most of the calibration runs."""
    return [sum(run[i] for run in cal) * 2 > len(cal) for i in range(len(cal[0]))]


def stable(cal: list[list[bool]]) -> list[bool]:
    """True for tests that gave the same result in every calibration run (not flaky)."""
    return [len({run[i] for run in cal}) == 1 for i in range(len(cal[0]))]


def down_up(ref: list[bool], night: list[bool], use: list[bool] | None = None) -> tuple[int, int]:
    """(went down, went up): tests the reference calls a pass that fail tonight, and the reverse.
    `use` marks the tests to count (None = all)."""
    use = use or [True] * len(ref)
    down = sum(u and r and not x for u, r, x in zip(use, ref, night))
    up = sum(u and x and not r for u, r, x in zip(use, ref, night))
    return down, up


def mcnemar_p(down: int, up: int) -> float:
    """Exact two-sided McNemar test: only the tests that changed count, and under 'no change'
    each is a coin flip. p = 2 × P(at most min(down, up) heads in down + up flips), capped at 1."""
    n = down + up
    if n == 0:
        return 1.0
    k = min(down, up)
    return min(1.0, 2 * sum(math.comb(n, i) for i in range(k + 1)) / 2 ** n)


def paired_alarm(ref: list[bool], night: list[bool], use: list[bool] | None = None, alpha: float = 0.01) -> bool:
    """Alarm when more tests went down than up, and p < alpha."""
    down, up = down_up(ref, night, use)
    return down > up and mcnemar_p(down, up) < alpha


def pass_rates(cal: list[list[bool]]) -> list[float]:
    """Each test's own pass rate, pulled toward the suite's average (three runs is few):
    (passes + k·avg) / (2k), with k calibration runs and avg the pass rate over all of them."""
    k, n = len(cal), len(cal[0])
    avg = sum(sum(run) for run in cal) / (k * n)
    return [(sum(run[i] for run in cal) + k * avg) / (2 * k) for i in range(n)]


def alarm_line(rates: list[float], z: float = 3.0) -> tuple[float, float]:
    """(expected failures on a normal night, the alarm line). Expected = Σ(1 − p_i); the line is
    expected + z standard deviations, with SD = √Σ p_i(1 − p_i)."""
    expected = sum(1 - p for p in rates)
    sd = math.sqrt(sum(p * (1 - p) for p in rates))
    return expected, expected + z * sd


def per_test_alarm(rates: list[float], night: list[bool], z: float = 3.0) -> bool:
    """Alarm when tonight's failures are past the line."""
    return sum(not x for x in night) > alarm_line(rates, z)[1]


def slip_rate(cal: list[list[bool]], later: list[list[bool]]) -> float:
    """Among tests that passed every calibration run, the share of later results that failed.
    Regression to the mean: 'always passes' was partly luck."""
    sure = [i for i in range(len(cal[0])) if all(run[i] for run in cal)]
    results = [run[i] for run in later for i in sure]
    return sum(not x for x in results) / len(results)
