"""
Practice: repeated runs. Lab 06's repeat math (evalkit/repeats.py and 01-03 scripts): which tasks are
flaky, which flipped between two runs, pass@k and pass^k from n runs per task, and a 95% confidence
interval two ways: naive (every run as a separate test case) and from the tasks.

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

A results matrix is a list of rows, one row per task, one 0/1 entry per run (1 = pass).
Every task has the same number of runs. Standard library only.
"""
import math

Z_95 = 1.959964  # the z value for a 95% interval, as in the lab


def flakiness(m):
    """Count tasks that passed every run, failed every run, or flipped (flaky).
    Return a dict {"always_pass": .., "always_fail": .., "flaky": ..}."""
    out = {"always_pass": 0, "always_fail": 0, "flaky": 0}
    for row in m:
        c = sum(row)
        if c == len(row):
            out["always_pass"] += 1
        elif c == 0:
            out["always_fail"] += 1
        else:
            out["flaky"] += 1
    return out


def flips(a, b):
    """Two runs of the same tasks, a and b (lists of 0/1, one per task).
    Return (passed_then_failed, failed_then_passed)."""
    p2f = sum(1 for x, y in zip(a, b) if x == 1 and y == 0)
    f2p = sum(1 for x, y in zip(a, b) if x == 0 and y == 1)
    return p2f, f2p


def all_k_pass(p, k):
    """One task (or one shooter) with chance p per run: the chance all k runs pass."""
    return p ** k


def pass_at_k(m, k):
    """Chance at least one of k runs passes, averaged over tasks. Per task, from c passes in n runs:
    1 - C(n - c, k) / C(n, k)  (it counts the ways to pick k runs that are all failures).
    Raise ValueError if k > n."""
    n = len(m[0])
    if k > n:
        raise ValueError("k needs at least k runs per task")
    return sum(1 - math.comb(n - sum(r), k) / math.comb(n, k) for r in m) / len(m)


def pass_hat_k(m, k):
    """pass^k: chance ALL k runs pass, averaged over tasks. Per task: C(c, k) / C(n, k).
    Raise ValueError if k > n."""
    n = len(m[0])
    if k > n:
        raise ValueError("k needs at least k runs per task")
    return sum(math.comb(sum(r), k) / math.comb(n, k) for r in m) / len(m)


def naive_ci(m):
    """The WRONG interval, for comparison: every run treated as a separate test case.
    p = all passes / all runs, N = tasks x runs, half-width = Z_95 * sqrt(p (1 - p) / N).
    Return (low, high)."""
    flat = [x for r in m for x in r]
    p, n = sum(flat) / len(flat), len(flat)
    half = Z_95 * math.sqrt(p * (1 - p) / n)
    return p - half, p + half


def task_level_ci(m):
    """The honest interval: built from each task's own pass rate (one number per task).
    mean of the per-task rates +/- Z_95 * SD(per-task rates, n - 1 in the denominator) / sqrt(tasks).
    Return (low, high)."""
    rates = [sum(r) / len(r) for r in m]
    t = len(rates)
    mean = sum(rates) / t
    sd = math.sqrt(sum((x - mean) ** 2 for x in rates) / (t - 1))
    half = Z_95 * sd / math.sqrt(t)
    return mean - half, mean + half


def effective_tasks(tasks, runs, icc):
    """How many independent tasks `tasks` x `runs` results are worth: tasks*runs / design effect,
    where design effect = 1 + (runs - 1) * icc (icc = the share of the variance that belongs to the task)."""
    return tasks * runs / (1 + (runs - 1) * icc)
