"""
Practice: the judge as a measuring instrument. Lab 10's judge math (evalkit/judge.py, evalkit/stats.py and
Scripts 1-2): a judge's two catch rates against human labels, their Wilson intervals, how many labels calibration
needs, the corrected pass rate (Rogan-Gladen), the raw score a judge is expected to read, and how often a set of
error bars holds the truth.

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

Convention, as in the lab: 1 = pass, 0 = fail, for both the judge and the person. Standard library only.
"""
import math

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


def catch_rates(judge, human):
    """Compare a judge's verdicts with a person's on the same outputs (two lists of 0/1).
    Return a dict with:
      n_pass, n_fail: how many outputs the person passed / failed
      tp: of the person's passes, how many the judge passed too
      tn: of the person's failures, how many the judge failed too
      tpr = tp / n_pass  (catches good ones),  tnr = tn / n_fail  (catches bad ones)
    """
    n_pass = sum(1 for h in human if h == 1)
    n_fail = sum(1 for h in human if h == 0)
    tp = sum(1 for j, h in zip(judge, human) if h == 1 and j == 1)
    tn = sum(1 for j, h in zip(judge, human) if h == 0 and j == 0)
    return {"n_pass": n_pass, "n_fail": n_fail, "tp": tp, "tn": tn,
            "tpr": tp / n_pass if n_pass else float("nan"),
            "tnr": tn / n_fail if n_fail else float("nan")}


def wilson_ci(k, n, z=Z_95):
    """95% Wilson interval for k successes out of n (Chapter 1). Return (low, high); (0.0, 1.0) if 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)."""
    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 n_for_margin(p, margin, z=Z_95):
    """Cases needed so a rate near p is known to +/- margin: ceil(z^2 p (1 - p) / margin^2) (Chapter 2)."""
    return math.ceil(z * z * p * (1 - p) / (margin * margin) - 1e-9)


def labels_needed(margin, expected_tpr, expected_tnr, fail_share):
    """Human labels to know TPR and TNR each to +/- margin. TPR comes only from passes and TNR only from
    failures, so each needs its own count. Sampling at random, the rarer class sets the total:
    total_random = ceil(max(n_pass / (1 - fail_share), n_fail / fail_share)).
    Return {"n_pass": .., "n_fail": .., "total_random": ..}."""
    n_pass = n_for_margin(expected_tpr, margin)
    n_fail = n_for_margin(expected_tnr, margin)
    total = math.ceil(max(n_pass / (1 - fail_share), n_fail / fail_share))
    return {"n_pass": n_pass, "n_fail": n_fail, "total_random": total}


def flagged_design(target_fails, fail_rate_flagged, extra_passes):
    """Label user-flagged outputs until you have target_fails failures (ceil(target_fails / fail_rate_flagged)
    flagged labels), plus extra_passes random passes for TPR. Return the total number of labels."""
    return math.ceil(target_fails / fail_rate_flagged) + extra_passes


def corrected_pass_rate(raw, tpr, tnr):
    """Rogan-Gladen: (raw + tnr - 1) / (tpr + tnr - 1), clipped to [0, 1].
    If tpr + tnr - 1 <= 0.05 the judge is barely better than a coin: raise ValueError instead of returning
    a misleading number (the lab does the same)."""
    youden = tpr + tnr - 1
    if youden <= 0.05:
        raise ValueError(f"TPR + TNR - 1 = {youden:.2f}: too close to random to correct")
    return min(1.0, max(0.0, (raw + tnr - 1) / youden))


def expected_raw(true_pass, tpr, tnr):
    """The pass rate a judge reads on average: the true passes it catches (tpr * true_pass) plus the
    failures it lets through ((1 - tnr) * (1 - true_pass))."""
    return tpr * true_pass + (1 - tnr) * (1 - true_pass)


def holds(intervals, truth):
    """How many of the (low, high) intervals contain truth (low <= truth <= high)."""
    return sum(1 for lo, hi in intervals if lo <= truth <= hi)
