"""Tests on the capstone's recorded results (eval labs, How Much Is This 92% Worth?). Everything is simulated: a
200-case eval behind a "92%" headline, 6,000 recent support tickets, a summarizer, people who grade perfectly and two
judges with known mistakes. The "true" rates are the simulation's answer key, which a real team never has.
Run: pytest test_audit_practice.py"""
from audit_practice import (consistent, cheapest_judge_design, corrected_margin, judge_cost, margin_at, people_cost,
                            reweight, unmeasured_range, waterfall, wilson_ci, youden_j)

TRAFFIC = {"simple": 0.4221666666666667, "multi-request": 0.3343333333333333, "angry": 0.1915, "spanish": 0.052}


def close(a, b, tol=1e-4):
    return abs(a - b) <= tol


def pts(x):
    return round(x * 100, 1)


def test_youden_j():
    # 02_decompose.py: on 100 calibration labels the cheap judge passed 83 of 87 good summaries and failed 6 of 13 bad
    j = youden_j(83 / 87, 6 / 13)
    assert round(j, 2) == 0.42
    assert round(1 / j, 1) == 2.4  # every error, magnified about 2.4 times
    assert close(youden_j(0.95, 0.88), 0.83)  # the large judge, as planned
    assert youden_j(1.0, 1.0) == 1.0


def test_corrected_margin_perfect_grader_is_the_plain_margin():
    # a grader that is never wrong adds no error: the margin is the plain sample-size margin
    assert close(corrected_margin(0.5, 1.0, 1.0, 1068, 1068), margin_at(0.5, 1068), 1e-9)
    assert pts(margin_at(0.5, 1068)) == 3.0


def test_corrected_margin_large_judge():
    # 03_design.py, Exercise 2: 3,100 cases and 950 calibration labels just reach +/-3
    assert corrected_margin(0.5, 0.95, 0.88, 3100, 950) <= 0.03
    assert corrected_margin(0.5, 0.95, 0.88, 3050, 950) > 0.03
    assert corrected_margin(0.5, 0.95, 0.88, 3100, 925) > 0.03


def test_corrected_margin_cheap_judge_cannot_reach_3():
    # even with all 5,800 tickets judged AND labelled by people: +/-3.6
    m = corrected_margin(0.5, 83 / 87, 6 / 13, 5800, 5800)
    assert pts(m) == 3.6


def test_unmeasured_range():
    # 01_audit.py, Exercise 1: the headline, 184 of 200, has a range of 87.4-95.0% that covers sampling only
    lo, hi = wilson_ci(184, 200)
    assert (pts(lo), pts(hi)) == (87.4, 95.0)
    # 02_decompose.py, step 6: the reweighted range was 44.8-100%; Spanish (5.2% of traffic) has no cases
    lo, hi = unmeasured_range(0.4475579454193761, 1.0, 0.052)
    assert (pts(lo), pts(hi)) == (42.4, 100.0)
    lo, hi = unmeasured_range(0.70, 0.80, 0.10)
    assert close(lo, 0.63) and close(hi, 0.82)  # a missing kind widens even a narrow range


def test_reweight_the_rebuild():
    # 04_rebuild.py: the four kinds' corrected pass rates, weighted by traffic -> 76.8%
    rebuilt = {"simple": 0.8560781231918937, "multi-request": 0.7072733760091722, "angry": 0.7412922572693844,
               "spanish": 0.5413244577304549}
    assert pts(reweight(rebuilt, TRAFFIC)) == 76.8


def test_reweight_renormalizes_over_covered_kinds():
    # 02_decompose.py, step 5: the 40 real tickets have no Spanish, so the other three shares are scaled up
    pilot = {"simple": 0.7897872340425537, "multi-request": 0.9502127659574467, "angry": 0.8700000000000002}
    assert close(reweight(pilot, TRAFFIC), 0.8625681913397376, 1e-9)


def test_waterfall_in_script_order():
    # 02_decompose.py's answer key: 92.0 read by the judge, 86.6 true on the 200 cases, 85.9 without leaks,
    # 76.6 on the 40 real tickets, 76.3 on recent traffic without Spanish, 75.3 on all traffic
    levels = [("headline", 0.92), ("judge", 0.8658744115845307), ("leaks", 0.8588151700889798),
              ("model-written", 0.7660203166069172), ("mix", 0.7626898304547735), ("spanish", 0.752808700070167)]
    w = waterfall(levels)
    assert [name for name, _ in w] == ["judge", "leaks", "model-written", "mix", "spanish"]
    assert [pts(v) for _, v in w] == [5.4, 0.7, 9.3, 0.3, 1.0]
    assert pts(sum(v for _, v in w)) == 16.7


def test_waterfall_depends_on_the_order():
    # mix first: reweight the 190 clean cases to traffic (true 80.85%), then drop the model-written ones (77.44%)
    levels = [("headline", 0.92), ("judge", 0.8658744115845307), ("leaks", 0.8588151700889798),
              ("mix", 0.8085229880774368), ("model-written", 0.7744097248933594), ("leftover", 0.7626898304547735),
              ("spanish", 0.752808700070167)]
    assert [pts(v) for _, v in waterfall(levels)] == [5.4, 0.7, 5.0, 3.4, 1.2, 1.0]


def test_people_cost():
    # 03_design.py, Exercise 2: people grade 1,068 cases; 12 monthly releases
    c = people_cost(1068, 12)
    assert close(c["first"], 2674.272) and close(c["per_release"], 2140.272) and close(c["total"], 26217.264)


def test_judge_cost():
    # the large judge ($0.015 a call): 3,100 cases, 950 calibration labels, 100 fresh labels per release
    c = judge_cost(3100, 950, 0.015, 12)
    assert close(c["first"], 3508.9) and close(c["per_release"], 258.9) and close(c["total"], 6356.8)
    # for one run people are cheaper; from the second release on, the judge is
    assert people_cost(1068, 1)["total"] < judge_cost(3100, 950, 0.015, 1)["total"]
    assert people_cost(1068, 2)["total"] > judge_cost(3100, 950, 0.015, 2)["total"]


def test_cheapest_judge_design():
    # 03_design.py, Exercise 2: the large judge, planned with its assumed catch rates
    d = cheapest_judge_design(0.95, 0.88, 0.015)
    assert (d["cases"], d["labels"]) == (3100, 950) and close(d["first"], 3508.9)
    assert cheapest_judge_design(83 / 87, 6 / 13, 0.002) is None  # the cheap judge: impossible at any size


def test_held_out_check():
    # 04_rebuild.py, Exercise 3: 200 people-only tickets 78.5% (72.3-83.6%) vs the rebuilt 76.8% (74.1-79.4%)
    held = 157 / 200
    held_ci = wilson_ci(157, 200)
    assert (pts(held_ci[0]), pts(held_ci[1])) == (72.3, 83.6)
    assert consistent(held, held_ci, 0.7679790521223151, (0.7409647922915048, 0.7935938166791537))
    # a judge that drifted 15 points lenient: people say 62.0%, the judge-based number still says 76.8%
    assert not consistent(124 / 200, wilson_ci(124, 200), 0.7679790521223151, (0.7409647922915048, 0.7935938166791537))
