"""
Practice: stratified sampling. Lab 04's math (evalkit/stats.py, evalkit/planning.py,
evalkit/sampling.py, 01_zero_catastrophe.py, 03_reweighting.py, 04_risk_based.py):
how often a random test set misses a rare group, how many random cases it takes to get
enough of them, the Wilson interval for one group, raw vs weighted scores, what zero
failures prove, a release verdict per group, and where the harm is.

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

Notation: a "group" (stratum) is a kind of request: normal, difficult, ambiguous, critical.
counts maps group -> (passes, cases). shares maps group -> share of real traffic (sums to 1).
Rates and shares are fractions (0.70, not 70).
"""
import math

Z_95 = 1.959963984540054


def chance_of_none(n, share):
    """The chance a random test set of n cases contains no case at all from a group that is
    `share` of traffic: every one of the n draws misses it."""
    return (1 - share) ** n


def chance_at_least(n, share, k_min):
    """The chance a random set of n cases has at least k_min cases from the group: 1 minus the
    binomial chance of 0, 1, ..., k_min - 1. Use math.comb (or logs, if n gets large)."""
    below = 0.0
    for k in range(k_min):
        log_term = (math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)
                    + k * math.log(share) + (n - k) * math.log(1 - share))
        below += math.exp(log_term)
    return 1 - below


def random_cases_needed(share, k_min, sure=0.95):
    """The smallest random test set that contains at least k_min cases from the group with
    chance >= sure. Start at k_min and count up."""
    n = k_min
    while chance_at_least(n, share, k_min) < sure:
        n += 1
    return n


def wilson_ci(passes, n, z=Z_95):
    """Wilson score interval (low, high) for a pass rate. (0.0, 1.0) when n == 0.
    center = (p + z^2/(2n)) / (1 + z^2/n),  half = z * sqrt(p(1-p)/n + z^2/(4n^2)) / (1 + z^2/n);
    clip to [0, 1]."""
    if n == 0:
        return 0.0, 1.0
    p = passes / 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 raw_score(counts):
    """Every case counts the same: all passes / all cases."""
    return sum(k for k, _ in counts.values()) / sum(n for _, n in counts.values())


def weighted_score(counts, shares):
    """Each group's own pass rate, weighted by its share of real traffic: sum of share * rate."""
    return sum(shares[g] * k / n for g, (k, n) in counts.items())


def zero_failure_upper(n, confidence=0.95):
    """After n cases with 0 failures, how high the failure rate could still be:
    1 - (1 - confidence) ** (1 / n). The rule of three says about 3 / n."""
    return 1 - (1 - confidence) ** (1 / n)


def clean_cases_needed(max_failure_rate, confidence=0.95):
    """Cases that must ALL pass to claim 'failure rate below max_failure_rate':
    the smallest whole n with (1 - max_failure_rate) ** n <= 1 - confidence,
    i.e. ceil(ln(1 - confidence) / ln(1 - max_failure_rate))."""
    return math.ceil(math.log(1 - confidence) / math.log(1 - max_failure_rate))


def verdict(low, high, target):
    """A release verdict for one group from its interval: 'meets' if the whole interval is at
    or above the target, 'fails' if it's all below, otherwise "can't tell"."""
    if low >= target:
        return "meets"
    if high < target:
        return "fails"
    return "can't tell"


def harm_per_1000(shares, pass_rates, costs):
    """Expected cost of failures per 1,000 requests, by group:
    1,000 * traffic share * failure rate * cost of one failure. Returns group -> harm."""
    return {g: 1000 * shares[g] * (1 - pass_rates[g]) * costs[g] for g in shares}
