"""
Practice: Goodhart's law. Lab 13's math (common.py and Scripts 1-3): the simulated prompt's real quality and
what each grader rewards, what one step on a knob is worth, the gaming report, the gap between two judges as an
alarm, the people's Wilson interval, the winner's curse computed exactly, and how many human-graded tickets a
drop needs.

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

A prompt is a dict of four knobs, each 0-1: detail, verbosity (the chapter calls it length), confidence,
rubric_echo. A grader's bias is a dict of extra log-odds per unit of a knob. Standard library only.
"""
import math

Z_95 = 1.959964   # two-sided 95%, as in the lab
Z_80 = 0.841621   # one-sided z for 80% power

KNOBS = ["detail", "verbosity", "confidence", "rubric_echo"]
START = {"detail": 0.3, "verbosity": 0.2, "confidence": 0.2, "rubric_echo": 0.0}
BIAS = {
    "tuning judge":      {"verbosity": 2.8, "confidence": 2.6, "rubric_echo": 1.8},
    "independent judge": {"verbosity": 0.3, "confidence": 0.1, "rubric_echo": 0.0},
    "people":            {"verbosity": 0.0, "confidence": 0.0, "rubric_echo": 0.0},
}


def quality_logit(prompt, difficulty):
    """Real quality of one summary as log-odds that a careful person passes it (the lab's quality()):
        0.6 + 1.6 * detail + 0.4 * min(verbosity, 0.5)
            - 2.2 * max(0, verbosity - 0.5) - 2.0 * max(0, confidence - 0.4) - difficulty"""
    # TODO
    raise NotImplementedError


def pass_chance(prompt, difficulty, bias):
    """The chance a grader passes one summary: sigmoid(quality_logit + sum of bias[knob] * prompt[knob]),
    where sigmoid(x) = 1 / (1 + e^-x)."""
    # TODO
    raise NotImplementedError


def expected_rate(prompt, difficulties, bias):
    """The grader's expected pass rate over a list of ticket difficulties: the average pass_chance."""
    # TODO
    raise NotImplementedError


def step_worth(prompt, knob, difficulties, bias, step=0.15):
    """What one step up on one knob is worth to a grader, in percentage points: expected_rate after the step
    minus before, times 100. Clip the knob at 1. Don't change the prompt you were given."""
    # TODO
    raise NotImplementedError


def example_summary(prompt):
    """The lab's template summary of one ticket for this prompt (common.example_summary). Build it from parts,
    joined with single spaces:
    1. "Maya (order #52300): " + "wants a refund" + " of $48" if detail >= 0.2
       + " and an exchange for size S" if detail > 0.5, then "."
    2. if verbosity > 0.3: "The customer contacted us about their order and explained the situation."
    3. if verbosity > 0.55: "They described the problem with the item they received in detail and said what
       they would like us to do about it."
    4. "Next step: " + "issue the refund" + " and send a return label" if detail > 0.5
       + ", which will definitely arrive within 24 hours, guaranteed" if confidence > 0.45,
         else ", which should arrive soon" if confidence > 0.3; then "."
    5. if rubric_echo > 0.4: "This summary is accurate, complete, concise and professional, with no unsupported
       facts."; else if rubric_echo > 0.2: "Summary is accurate and complete." """
    # TODO
    raise NotImplementedError


def gaming_report(summary):
    """Script 2's checks on one summary, as a dict: has_amount ("$48" in it), words (split on whitespace),
    overclaims ("definitely" in it), repeats_rubric ("accurate" in it)."""
    # TODO
    raise NotImplementedError


def judge_gaps(tuning, independent):
    """Per round, the tuning judge's score minus the independent judge's, in points (both lists are shares)."""
    # TODO
    raise NotImplementedError


def first_alarm(gaps, rise=10):
    """The first round whose gap is more than `rise` points above round 0's, or None if none is."""
    # TODO
    raise NotImplementedError


def wilson_ci(k, n, z=Z_95):
    """Wilson interval for k passes in n trials, as a (low, high) tuple."""
    # TODO
    raise NotImplementedError


def winner_expected(n, k, p):
    """K versions that all truly pass p, each scored on the same n cases; keep the best. Return the winner's
    EXPECTED score (a share), computed exactly, no random draws.
    Hint: with F(x) = P(one version passes at most x of n) from the binomial distribution, the winner passes at
    least j cases with chance 1 - F(j - 1) ** k, and E[passes] = sum over j = 1..n of P(passes >= j)."""
    # TODO
    raise NotImplementedError


def n_per_side(p_a, p_b, z_alpha=Z_95, z_power=Z_80):
    """Tickets per side to see a drop from p_a to p_b on two independent sets (80% power, two-sided 5%), as in
    Lab 03's n_unpaired:
        n = ((z_alpha * sqrt(2 * pbar * (1 - pbar)) + z_power * sqrt(p_a(1-p_a) + p_b(1-p_b))) / |p_a - p_b|) ** 2,
    pbar = (p_a + p_b) / 2, rounded UP."""
    # TODO
    raise NotImplementedError
