"""
Practice: sample size and paired comparisons. Lab 03's planning math (evalkit/planning.py,
01_sample_size.py, 02_comparisons.py, 03_cost.py): how many test cases a margin costs, what
that costs in labels, and how many cases a comparison of two versions needs, on different
cases or on the same cases (paired).

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

Rates are shares (0.9 = 90%), margins too (0.02 = 2 points).
"""
import math
from statistics import NormalDist

# The lab's example unit costs (data/costs.json): a label is 1.5 minutes at $40 an hour = $1,
# one model + judge run is $0.006.
LABEL_USD = 1.5 / 60 * 40
LABEL_MINUTES = 1.5
RUN_USD = 0.004 + 0.002


def z_for(confidence):
    """Given: the two-sided z for a confidence level (0.95 -> 1.96)."""
    return NormalDist().inv_cdf((1 + confidence) / 2)


def z_one_sided(q):
    """Given: the z with P(Z <= z) = q (0.80 -> 0.842, used for power)."""
    return NormalDist().inv_cdf(q)


def n_for_margin(p, margin, confidence=0.95):
    """Test cases needed so the +-margin is at most `margin` if the score is about p:
    n = z^2 * p(1-p) / margin^2, rounded UP to a whole case (use math.ceil(n - 1e-9) so
    floating-point noise doesn't add a case)."""
    z = z_for(confidence)
    return math.ceil(z * z * p * (1 - p) / (margin * margin) - 1e-9)


def margin_at(p, n, confidence=0.95):
    """The +-margin n cases actually give if the true score is p: z * sqrt(p(1-p)/n)."""
    return z_for(confidence) * math.sqrt(p * (1 - p) / n)


def cost(cases, versions=1, new_labels=None):
    """Dollars and hours for running `versions` versions on `cases` cases.
    Model + judge runs: cases x versions, at RUN_USD each. Labels: `new_labels` (default: all
    the cases) at LABEL_USD and LABEL_MINUTES each; reused labels are free.
    Return a dict with runs, labels, total_usd and labeling_hours."""
    labels = cases if new_labels is None else new_labels
    runs = cases * versions
    return {
        "runs": runs,
        "labels": labels,
        "total_usd": runs * RUN_USD + labels * LABEL_USD,
        "labeling_hours": labels * LABEL_MINUTES / 60,
    }


def n_unpaired(p_a, p_b, power=0.80, alpha=0.05):
    """Cases PER VERSION to compare two versions on DIFFERENT cases with the given power:
    d = |p_b - p_a|, p_bar = (p_a + p_b) / 2,
    top = z_for(1 - alpha) * sqrt(2 p_bar (1 - p_bar)) + z_one_sided(power) * sqrt(p_a(1-p_a) + p_b(1-p_b)),
    n = ceil(top^2 / d^2)."""
    d = abs(p_b - p_a)
    p_bar = (p_a + p_b) / 2
    top = (z_for(1 - alpha) * math.sqrt(2 * p_bar * (1 - p_bar))
           + z_one_sided(power) * math.sqrt(p_a * (1 - p_a) + p_b * (1 - p_b)))
    return math.ceil(top * top / (d * d))


def discordance(p_a, p_b, rho):
    """On one shared case, the chance only A is right and the chance only B is right, (a_only, b_only),
    when A's and B's right/wrong results correlate at rho (how alike the versions are case by case):
    both = p_a p_b + rho * sqrt(p_a(1-p_a) p_b(1-p_b)); a_only = p_a - both; b_only = p_b - both.
    Raise ValueError if either is negative (two rates that far apart can't be that alike)."""
    both = p_a * p_b + rho * math.sqrt(p_a * (1 - p_a) * p_b * (1 - p_b))
    a_only, b_only = p_a - both, p_b - both
    if a_only < 0 or b_only < 0:
        raise ValueError("rho too high for these pass rates")
    return a_only, b_only


def n_paired(a_only, b_only, power=0.80, alpha=0.05):
    """Shared cases (each run on both versions) for the given power, from the disagreement chances:
    d = |b_only - a_only|, psi = a_only + b_only (the share of cases that disagree),
    top = z_for(1 - alpha) * sqrt(psi) + z_one_sided(power) * sqrt(psi - d^2),
    n = ceil(top^2 / d^2)."""
    d = abs(b_only - a_only)
    psi = a_only + b_only
    top = z_for(1 - alpha) * math.sqrt(psi) + z_one_sided(power) * math.sqrt(psi - d * d)
    return math.ceil(top * top / (d * d))


def cost_over_changes(p_a, d, rho, changes):
    """Total dollars to check `changes` changes, each +d over p_a with 80% power, two ways.
    Different cases: the first comparison labels 2 x n_unpaired cases (one version each); every later
    change labels n_unpaired fresh cases for the new version.
    Paired: the first comparison labels n_paired cases and runs both versions on them; every later
    change runs only the new version on the same cases, with no new labels.
    Return (different_cases_usd, paired_usd)."""
    nu = n_unpaired(p_a, p_a + d)
    npd = n_paired(*discordance(p_a, p_a + d, rho))
    unpaired = cost(2 * nu)["total_usd"] + (changes - 1) * cost(nu)["total_usd"]
    paired = cost(npd, versions=2)["total_usd"] + (changes - 1) * cost(npd, new_labels=0)["total_usd"]
    return unpaired, paired
