"""
Solution: 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.

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"""
    return (0.6 + 1.6 * prompt["detail"] + 0.4 * min(prompt["verbosity"], 0.5)
            - 2.2 * max(0.0, prompt["verbosity"] - 0.5) - 2.0 * max(0.0, prompt["confidence"] - 0.4) - difficulty)


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)."""
    logit = quality_logit(prompt, difficulty) + sum(b * prompt[k] for k, b in bias.items())
    return 1 / (1 + math.exp(-logit))


def expected_rate(prompt, difficulties, bias):
    """The grader's expected pass rate over a list of ticket difficulties: the average pass_chance."""
    return sum(pass_chance(prompt, d, bias) for d in difficulties) / len(difficulties)


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."""
    after = dict(prompt)
    after[knob] = min(1.0, after[knob] + step)
    return (expected_rate(after, difficulties, bias) - expected_rate(prompt, difficulties, bias)) * 100


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." """
    d, v, c, r = (prompt[k] for k in KNOBS)
    ask = "wants a refund" + (" of $48" if d >= 0.2 else "") + (" and an exchange for size S" if d > 0.5 else "")
    parts = [f"Maya (order #52300): {ask}."]
    if v > 0.3:
        parts.append("The customer contacted us about their order and explained the situation.")
    if v > 0.55:
        parts.append("They described the problem with the item they received in detail and said what they "
                     "would like us to do about it.")
    step = "issue the refund" + (" and send a return label" if d > 0.5 else "")
    if c > 0.45:
        step += ", which will definitely arrive within 24 hours, guaranteed"
    elif c > 0.3:
        step += ", which should arrive soon"
    parts.append(f"Next step: {step}.")
    if r > 0.4:
        parts.append("This summary is accurate, complete, concise and professional, with no unsupported facts.")
    elif r > 0.2:
        parts.append("Summary is accurate and complete.")
    return " ".join(parts)


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)."""
    return {"has_amount": "$48" in summary, "words": len(summary.split()),
            "overclaims": "definitely" in summary, "repeats_rubric": "accurate" in summary}


def judge_gaps(tuning, independent):
    """Per round, the tuning judge's score minus the independent judge's, in points (both lists are shares)."""
    return [(t - i) * 100 for t, i in zip(tuning, independent)]


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."""
    for r, g in enumerate(gaps):
        if g - gaps[0] > rise:
            return r
    return None


def wilson_ci(k, n, z=Z_95):
    """Wilson interval for k passes in n trials, as a (low, high) tuple."""
    p = k / n
    centre = (p + z * z / (2 * n)) / (1 + z * z / n)
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
    return (centre - half, centre + half)


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)."""
    cdf, acc = [], 0.0
    for x in range(n + 1):
        acc += math.comb(n, x) * p ** x * (1 - p) ** (n - x)
        cdf.append(min(acc, 1.0))
    return sum(1 - cdf[j - 1] ** k for j in range(1, n + 1)) / n


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."""
    pbar = (p_a + p_b) / 2
    top = z_alpha * math.sqrt(2 * pbar * (1 - pbar)) + z_power * math.sqrt(p_a * (1 - p_a) + p_b * (1 - p_b))
    return math.ceil(top * top / (p_a - p_b) ** 2)
