"""Tests on Lab 13's recorded results (eval labs, When the Metric Stops Measuring Quality). Everything is simulated:
a summarizer prompt with four knobs, an AI judge built to like long answers, confident words and its rubric's
phrases, an independent judge with almost none of that, and people who grade real quality only. The per-round
numbers below are what the lab's Script 1 records with its seed (reports/history.json).
Run: pytest test_goodhart_practice.py"""
from statistics import NormalDist

from goodhart_practice import (BIAS, START, example_summary, expected_rate, first_alarm, gaming_report, judge_gaps,
                               n_per_side, pass_chance, quality_logit, step_worth, wilson_ci, winner_expected)

# 2,000 ticket difficulties spread evenly over the lab's mix (normal, mean 0.8, sd 0.9). The lab draws 5,000 at
# random (seed 4); this even spread gives the same rates to within half a point, with no random numbers.
TICKETS = [NormalDist(0.8, 0.9).inv_cdf((i + 0.5) / 2000) for i in range(2000)]

# Script 1 (seed 0): the prompt each round as (detail, verbosity, confidence, rubric_echo), the tuning judge's and
# the independent judge's passes out of the same 300 fresh tickets, and people's passes out of 60 held-out tickets.
KNOBS = [(0.30, 0.20, 0.20, 0.00), (0.30, 0.20, 0.35, 0.00), (0.30, 0.20, 0.35, 0.15), (0.15, 0.20, 0.35, 0.15),
         (0.15, 0.20, 0.35, 0.30), (0.15, 0.35, 0.35, 0.30), (0.15, 0.50, 0.35, 0.30), (0.15, 0.50, 0.50, 0.30),
         (0.30, 0.50, 0.50, 0.30), (0.15, 0.50, 0.50, 0.30), (0.15, 0.50, 0.50, 0.30), (0.15, 0.65, 0.50, 0.30),
         (0.15, 0.65, 0.50, 0.45), (0.15, 0.65, 0.65, 0.45), (0.15, 0.65, 0.50, 0.45)]
PROMPTS = [dict(zip(["detail", "verbosity", "confidence", "rubric_echo"], k)) for k in KNOBS]
TUNING_JUDGE = [225, 256, 262, 255, 265, 274, 283, 289, 285, 282, 289, 296, 289, 296, 288]
INDEPENDENT = [183, 185, 181, 170, 161, 164, 180, 157, 172, 169, 179, 141, 154, 135, 149]
PEOPLE = [38, 37, 36, 28, 25, 25, 27, 33, 32, 29, 34, 29, 30, 24, 26]


def close(x, y, tol=1e-3):
    return abs(x - y) <= tol


def test_quality_logit():
    assert close(quality_logit(START, 0.8), 0.36)               # 0.6 + 0.48 + 0.08 - 0.8
    assert close(quality_logit(PROMPTS[14], 0.8), -0.29)        # less detail, padding and overconfidence: -0.65
    assert close(quality_logit(PROMPTS[13], 0.0), 0.21)         # confidence 0.65: -2.0 * 0.25 more


def test_pass_chance_adds_the_graders_taste():
    assert close(pass_chance(START, 0.8, BIAS["people"]), 0.5890, 1e-4)
    # the tuning judge adds 2.8 * 0.2 + 2.6 * 0.2 = 1.08 log-odds for the same summary
    assert close(pass_chance(START, 0.8, BIAS["tuning judge"]), 0.8085, 1e-4)


def test_score_up_quality_down():
    # round 0 -> round 14: the tuning judge rises, real quality (people's expected rate) falls
    assert close(expected_rate(START, TICKETS, BIAS["people"]), 0.5761)      # recorded on 5,000 tickets: 57.3%
    assert close(expected_rate(START, TICKETS, BIAS["tuning judge"]), 0.7758)
    assert close(expected_rate(PROMPTS[14], TICKETS, BIAS["people"]), 0.4386)  # recorded: 43.5%
    assert close(expected_rate(PROMPTS[14], TICKETS, BIAS["tuning judge"]), 0.9636)
    assert close(expected_rate(PROMPTS[14], TICKETS, BIAS["independent judge"]), 0.4904)
    real = [expected_rate(p, TICKETS, BIAS["people"]) for p in PROMPTS]
    assert max(real[1:]) <= real[0] + 1e-9                     # no round beat the starting prompt


def test_what_one_step_is_worth():
    judge = {k: step_worth(START, k, TICKETS, BIAS["tuning judge"]) for k in START}
    real = {k: step_worth(START, k, TICKETS, BIAS["people"]) for k in START}
    assert close(judge["detail"], 3.48, 0.01) and close(real["detail"], 4.92, 0.01)
    assert close(judge["verbosity"], 6.56, 0.01) and close(real["verbosity"], 1.25, 0.01)
    assert close(judge["confidence"], 5.46, 0.01) and close(real["confidence"], 0.0, 1e-9)
    assert close(judge["rubric_echo"], 3.89, 0.01) and close(real["rubric_echo"], 0.0, 1e-9)
    assert min(judge, key=judge.get) == "detail"               # the only real improvement pays the judge least
    assert START["detail"] == 0.3                              # the prompt you passed in is unchanged


def test_example_summaries():
    assert example_summary(PROMPTS[0]) == "Maya (order #52300): wants a refund of $48. Next step: issue the refund."
    assert example_summary(PROMPTS[7]) == (
        "Maya (order #52300): wants a refund. The customer contacted us about their order and explained the "
        "situation. Next step: issue the refund, which will definitely arrive within 24 hours, guaranteed. "
        "Summary is accurate and complete.")
    assert example_summary(PROMPTS[14]).endswith(
        "This summary is accurate, complete, concise and professional, with no unsupported facts.")
    rich = example_summary({"detail": 0.6, "verbosity": 0.0, "confidence": 0.0, "rubric_echo": 0.0})
    assert rich == ("Maya (order #52300): wants a refund of $48 and an exchange for size S. "
                    "Next step: issue the refund and send a return label.")


def test_gaming_report_round_by_round():
    reports = [gaming_report(example_summary(p)) for p in PROMPTS]
    assert [r["has_amount"] for r in reports] == [r in (0, 1, 2, 8) for r in range(15)]
    assert [r["words"] for r in reports] == [13, 17, 17, 15, 20, 31, 31, 35, 37, 35, 35, 57, 64, 64, 64]
    assert [r["overclaims"] for r in reports] == [r >= 7 for r in range(15)]
    assert [r["repeats_rubric"] for r in reports] == [r >= 4 for r in range(15)]


def test_the_gap_between_two_judges():
    gaps = judge_gaps([k / 300 for k in TUNING_JUDGE], [k / 300 for k in INDEPENDENT])
    assert [round(g) for g in gaps] == [14, 24, 27, 28, 35, 37, 34, 44, 38, 38, 37, 52, 45, 54, 46]
    assert first_alarm(gaps, rise=10) == 2       # more than 10 points above round 0's +14: round 2 (+27)
    assert first_alarm(gaps, rise=40) is None    # the largest rise is +39.7 (round 13)


def test_people_are_noisy():
    lo, hi = wilson_ci(38, 60)
    assert close(lo, 0.5068) and close(hi, 0.7438)             # round 0: 63% (51-74%)
    lo, hi = wilson_ci(26, 60)
    assert close(lo, 0.3157) and close(hi, 0.5590)             # round 14: 43% (32-56%)
    halves = [(wilson_ci(k, 60)[1] - wilson_ci(k, 60)[0]) / 2 * 100 for k in PEOPLE]
    assert all(11 < h < 13 for h in halves)                    # about +-12 points every round
    first3, last3 = sum(PEOPLE[:3]) / 180, sum(PEOPLE[-3:]) / 180
    assert round(first3 * 100) == 62 and round(last3 * 100) == 44


def test_winners_curse_exactly():
    assert close(winner_expected(50, 1, 0.75), 0.75, 1e-9)     # one version: no curse
    assert close(winner_expected(50, 5, 0.75), 0.8195, 1e-4)   # the lab simulated 81.9%
    assert close(winner_expected(50, 100, 0.75), 0.8921, 1e-4)  # the lab simulated 89.2%: 14 points too good
    assert close(winner_expected(200, 100, 0.75), 0.8242, 1e-4)
    assert close(winner_expected(1000, 100, 0.75), 0.7839, 1e-4)  # still +3.4 on 1,000 cases


def test_sizing_the_human_check():
    assert n_per_side(0.573, 0.435) == 205       # to see 57% -> 44% in one before/after comparison
    assert n_per_side(0.573, 0.435) > 3 * 60     # the 60-ticket check is far too small for one round
