"""
Practice: audit a headline score, then design the rebuild. The capstone's math (evalkit/judge.py, evalkit/planning.py,
02_decompose.py, 03_design.py, 04_rebuild.py): a judge's skill score J, the planned margin of a judge-graded eval, the
range when a kind of ticket has no cases, reweighting to the traffic mix, the answer key's waterfall, what each grader
costs over a year of releases, the cheapest judge design that meets the margin, and the held-out consistency check.

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

Rates are fractions (0.92, not 92). Standard library only.
"""
import math

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

# Prices from the capstone (sim.py), in dollars
CURATION = 0.50   # pull, anonymize and check one real ticket for the eval set
RUN = 0.004       # the summarizer, per ticket
LABEL = 2.00      # one human pass/fail label


def wilson_ci(k, n, z=Z_95):
    """Given (no TODO). 95% Wilson interval for k passes out of n (Chapter 1). Return (low, high); (0.0, 1.0) if n == 0."""
    if n == 0:
        return 0.0, 1.0
    p = k / 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 margin_at(p, n, z=Z_95):
    """Given (no TODO). The +/- a perfectly graded eval of n cases gives at pass rate p: z * sqrt(p (1 - p) / n)."""
    return z * math.sqrt(p * (1 - p) / n)


def n_for_margin(p, margin, z=Z_95):
    """Given (no TODO). Cases needed for +/- margin at pass rate p: ceil(z^2 p (1 - p) / margin^2) (Chapter 2)."""
    return math.ceil(z * z * p * (1 - p) / (margin * margin) - 1e-9)


def youden_j(tpr, tnr):
    """A judge's skill score J = TPR + TNR - 1: 1 is perfect, 0 is no better than a coin flip."""
    # TODO
    raise NotImplementedError


def corrected_margin(true_pass, tpr, tnr, n, n_cal, z=Z_95):
    """The planned +/- of a judge-corrected pass rate (evalkit's corrected_margin, the delta method).
    n cases are judged; n_cal of them (a random subset) are also labelled by people to calibrate the judge.
      p_obs = tpr * true_pass + (1 - tnr) * (1 - true_pass)      (what the judge reads on average)
      var   = p_obs (1 - p_obs) / n                               (which cases were judged)
            + true_pass^2 * tpr (1 - tpr) / (true_pass * n_cal)   (how well the labels pin down TPR)
            + (1 - true_pass)^2 * tnr (1 - tnr) / ((1 - true_pass) * n_cal)   (and TNR)
      margin = z * sqrt(var) / J
    """
    # TODO
    raise NotImplementedError


def unmeasured_range(lo, hi, missing_share):
    """The range for ALL traffic when a kind of ticket with missing_share of traffic has no cases: its pass rate
    could be anything from 0 to 1. Return ((1 - share) * lo, (1 - share) * hi + share)."""
    # TODO
    raise NotImplementedError


def reweight(rates, shares):
    """Weight each kind's pass rate by its share of traffic. Only the kinds in `rates` count: renormalize their
    shares so they add up to 1 (shares may include kinds with no rate). Return sum(weight * rate)."""
    # TODO
    raise NotImplementedError


def waterfall(levels):
    """levels: a list of (name, true pass rate) in order, starting with ("headline", 0.92). Each later entry is the
    true rate after one more problem is taken out. Return a list of (name, points) for every entry after the first,
    where points = previous rate - this rate (as a fraction; 0.054 means 5.4 points)."""
    # TODO
    raise NotImplementedError


def people_cost(cases, releases):
    """People grade every case. First run: each case is curated, run and labelled. Every later release: run and
    labelled again. Return {"first": .., "per_release": .., "total": first + (releases - 1) * per_release}."""
    # TODO
    raise NotImplementedError


def judge_cost(cases, labels, judge_price, releases, recheck=100):
    """A judge grades every case; people label `labels` of them to calibrate it. First run: curate, run and judge
    each case, plus the labels. Every later release: run and judge again, plus `recheck` fresh human labels to catch
    the judge drifting. Return the same dict as people_cost."""
    # TODO
    raise NotImplementedError


def cheapest_judge_design(tpr, tnr, judge_price, target=0.03, pool=5800, plan_p=0.5):
    """The capstone's search (03_design.py): for n = 200, 250, ... up to pool, find the smallest number of
    calibration labels k = 50, 75, ... (at most n) whose corrected_margin(plan_p, tpr, tnr, n, k) <= target.
    Among those (n, k), return the one with the cheapest first run as {"cases": n, "labels": k, "first": cost},
    or None if no n reaches the target."""
    # TODO
    raise NotImplementedError


def consistent(held_rate, held_ci, estimate, estimate_ci):
    """The held-out check (04_rebuild.py): the people-only rate agrees with the judge-based estimate if
    |held_rate - estimate| <= sqrt(h1^2 + h2^2), where h1 and h2 are the two intervals' half-widths."""
    # TODO
    raise NotImplementedError
