"""Tests on Lab 12's recorded results (eval-ai-labs, 12_synthetic_realism). Everything is
simulated: three sets of 400 support tickets ("real" stands in for real customer traffic,
"plain" = a model asked for "a realistic support ticket", "grid" = generated from a grid of
mood x issues x channel) and the summarizer, whose chance of a correct summary is a rule.
Run: pytest test_synthetic_practice.py"""
from synthetic_practice import (features, jaccard, majority_baseline, margin, newcombe_diff_ci,
                                pass_probability, permutation_p, reweighted, usage_rule, wilson_ci)

PLAIN_1 = "Hello, I recently purchased a Hiker Socks from your store. Unfortunately, I want a refund for the Hiker Socks. Order #58290. Could you please help me? Thank you in advance."
PLAIN_17 = "Hello, I recently purchased a Trail Runner 2 from your store. Unfortunately, I was charged twice for the same order. Order #47322. Could you please help me? Thank you in advance."
PLAIN_23 = "Hello, I recently purchased a Hiker Socks from your store. Unfortunately, I was charged twice for the same order. Also you sent me the wrong item, I ordered the Hiker Socks. Order #51000. Could you please help me? Thank you for your help."
REAL_29 = "yo can I swap the Ridge Softshell for a medium. Also how do I get a refund on the Ridge Softshell. Also tracknig says in transit since forever, no Ridge Softshell yet. Fix this NOW."
REAL_38 = "hey there are 2 charges on my statement for one order. also i wnat a refund for the camp stove. aslo my camp stove still hasn't arrived and the tracking hasn't moved in days. order #40263. thanks"

# Script 2, Exercise 1: the 100 shuffled-label accuracies of the real-vs-real sanity check
# (two random halves of the real tickets, 200 each), replayed with c2st's own seed.
REAL_VS_REAL_SHUFFLES = [
    0.4675, 0.505, 0.5075, 0.5475, 0.45, 0.5275, 0.5225, 0.47, 0.4875, 0.465, 0.485, 0.5,
    0.5525, 0.4875, 0.535, 0.4525, 0.4575, 0.4975, 0.505, 0.51, 0.4925, 0.525, 0.505, 0.5025,
    0.4825, 0.48, 0.5325, 0.525, 0.5125, 0.5, 0.4825, 0.4675, 0.4975, 0.535, 0.4675, 0.5,
    0.5, 0.55, 0.5175, 0.4525, 0.475, 0.4975, 0.54, 0.5225, 0.4725, 0.4125, 0.555, 0.485,
    0.49, 0.535, 0.5025, 0.4825, 0.4775, 0.4925, 0.5, 0.53, 0.54, 0.5125, 0.4325, 0.48,
    0.49, 0.5325, 0.5575, 0.5325, 0.4775, 0.4925, 0.52, 0.59, 0.495, 0.555, 0.4775, 0.4975,
    0.5025, 0.4775, 0.53, 0.545, 0.4725, 0.4925, 0.48, 0.495, 0.5175, 0.485, 0.49, 0.485,
    0.51, 0.5125, 0.5475, 0.49, 0.4925, 0.4225, 0.54, 0.5, 0.47, 0.5, 0.52, 0.4475,
    0.4775, 0.5125, 0.49, 0.4875,
]

# Script 3, Exercise 3: issues x mood cells. nr / kr = real tickets / passed, nd / kd = grid tickets /
# passed, tr / td = true pass rates (known only because it's a simulation).
CELLS = [
    {"issues": 1, "mood": "calm", "nr": 116, "kr": 90, "tr": 0.8592, "nd": 46, "kd": 38, "td": 0.8885},
    {"issues": 1, "mood": "frustrated", "nr": 73, "kr": 56, "tr": 0.8251, "nd": 44, "kd": 36, "td": 0.8553},
    {"issues": 1, "mood": "angry", "nr": 40, "kr": 28, "tr": 0.7617, "nd": 44, "kd": 31, "td": 0.8074},
    {"issues": 2, "mood": "calm", "nr": 55, "kr": 42, "tr": 0.7465, "nd": 46, "kd": 39, "td": 0.7962},
    {"issues": 2, "mood": "frustrated", "nr": 27, "kr": 20, "tr": 0.7073, "nd": 44, "kd": 27, "td": 0.7457},
    {"issues": 2, "mood": "angry", "nr": 27, "kr": 14, "tr": 0.6447, "nd": 44, "kd": 26, "td": 0.6832},
    {"issues": 3, "mood": "calm", "nr": 27, "kr": 18, "tr": 0.613, "nd": 44, "kd": 27, "td": 0.6545},
    {"issues": 3, "mood": "frustrated", "nr": 19, "kr": 9, "tr": 0.4568, "nd": 44, "kd": 23, "td": 0.5966},
    {"issues": 3, "mood": "angry", "nr": 16, "kr": 5, "tr": 0.463, "nd": 44, "kd": 26, "td": 0.5245},
]


def test_features_of_a_plain_ticket():
    f = features(PLAIN_1)
    assert f["words"] == 29.0 and f["politeness"] == 2.0  # "please" and "Thank"
    assert f["has_order_number"] == 1.0 and f["starts_lowercase"] == 0.0 and f["asks"] == 1.0
    assert features(PLAIN_23)["asks"] == 2.0  # "Also": two issues


def test_features_of_real_tickets():
    f = features(REAL_29)
    assert (f["words"], f["starts_lowercase"], f["has_order_number"], f["politeness"], f["asks"]) == (35.0, 1.0, 0.0, 0.0, 3.0)
    # a feature is only an approximation: this ticket has 3 issues, but the typo "aslo" hides one "also"
    assert features(REAL_38)["asks"] == 2.0
    assert features(REAL_38)["politeness"] == 1.0  # "thanks"


def test_near_twins():
    # two plain tickets about different problems still share most of their words
    assert round(jaccard(PLAIN_1, PLAIN_17), 4) == 0.6562 and jaccard(PLAIN_1, PLAIN_17) >= 0.6
    # two real tickets share few
    assert jaccard(REAL_29, REAL_38) == 0.16
    # order numbers are masked: only the number differs, so it's a perfect match
    assert jaccard("Order #12345 is late", "order #99 is LATE") == 1.0
    assert jaccard("", "") == 1.0


def test_the_simulated_summarizer():
    assert round(pass_probability(1, "calm", True, 0, False), 4) == 0.9002  # the easiest ticket
    assert round(pass_probability(3, "angry", False, 1, False), 4) == 0.3659  # the angry 3-issue chat ticket
    assert round(pass_probability(3, "calm", True, 2, False), 4) == 0.6225
    assert round(pass_probability(1, "calm", True, 0, True), 4) == 0.7685  # Spanish
    assert pass_probability(1, "calm", True, 9, False) == pass_probability(1, "calm", True, 4, False)  # typos cap at 4


def test_chance_is_not_always_fifty_percent():
    # Script 2, Exercise 2: one-issue tickets, 229 real vs 134 grid
    assert round(majority_baseline(229, 134), 3) == 0.631
    assert round(majority_baseline(109, 134), 3) == 0.551
    assert majority_baseline(400, 400) == 0.5


def test_the_sanity_check_is_just_chance():
    acc = 0.4425  # real vs real: 177 of 400 held-out tickets sorted right
    assert min(REAL_VS_REAL_SHUFFLES) == 0.4125 and max(REAL_VS_REAL_SHUFFLES) == 0.59
    assert sum(s < acc for s in REAL_VS_REAL_SHUFFLES) == 3  # only 3 of 100 shuffles scored lower
    assert round(permutation_p(acc, REAL_VS_REAL_SHUFFLES), 2) == 0.97
    assert round(margin(acc, REAL_VS_REAL_SHUFFLES) * 100, 1) == -5.8  # 44.2% vs a 50.0% baseline
    # real vs plain: 99.9%, above every shuffle: p = 1/101, the smallest 100 shuffles allow
    assert round(permutation_p(0.99875, REAL_VS_REAL_SHUFFLES), 4) == 0.0099


def test_overall_score_gaps():
    # Script 3, Exercise 1: real 282/400, plain 345/400, grid 273/400
    lo, hi = wilson_ci(282, 400)
    assert (round(lo, 2), round(hi, 2)) == (0.66, 0.75)
    lo, hi = newcombe_diff_ci(282, 400, 345, 400)  # plain - real: +15.8
    assert (round(lo * 100, 1), round(hi * 100, 1)) == (10.1, 21.3)
    lo, hi = newcombe_diff_ci(282, 400, 273, 400)  # grid - real: -2.2, includes zero
    assert (round(lo * 100, 1), round(hi * 100, 1)) == (-8.6, 4.1) and lo < 0 < hi


def test_per_group_gaps_are_too_noisy():
    # Script 3, Exercise 2: every measured gap's range includes zero
    for kr, nr, kd, nd, want in [(174, 229, 105, 134, (-6.9, 10.9)), (76, 109, 92, 134, (-12.5, 10.6)),
                                 (32, 62, 76, 132, (-8.7, 20.6))]:
        lo, hi = newcombe_diff_ci(kr, nr, kd, nd)
        assert (round(lo * 100, 1), round(hi * 100, 1)) == want and lo < 0 < hi


def test_reweighting_to_the_real_mix():
    assert sum(c["nr"] for c in CELLS) == 400 and sum(c["nd"] for c in CELLS) == 400
    measured = reweighted(CELLS, lambda c: c["kd"] / c["nd"])
    true = reweighted(CELLS, lambda c: c["td"])
    assert round(measured, 3) == 0.747  # vs real 70.5% measured
    assert round(true, 3) == 0.794  # vs real 75.1% true: about 4 points too optimistic
    real_true = reweighted(CELLS, lambda c: c["tr"])
    assert round(real_true, 3) == 0.751
    # weighting the grid by its OWN mix gives back its raw score, 273 / 400
    as_generated = sum(c["nd"] / 400 * c["kd"] / c["nd"] for c in CELLS)
    assert round(as_generated, 4) == 0.6825
    assert reweighted([{"nr": 5, "nd": 0, "td": 0.1}, {"nr": 5, "nd": 4, "td": 0.8}], lambda c: c["td"]) == 0.4


def test_the_usage_rule():
    # Script 4: margin and (true) score gap per group of the grid set
    assert usage_rule(229, 134, 0.035, 0.020) == "measure"  # 1 issue
    assert usage_rule(109, 134, 0.166, 0.031) == "find failures, measure on real"  # 2 issues
    assert usage_rule(62, 132, 0.061, 0.065) == "find failures only"  # 3 issues
    assert usage_rule(20, 0, 0.0, 0.0) == "coverage gap"  # Spanish: the generator wrote none
    assert usage_rule(12, 40, 0.0, 0.0) == "too few to judge"
    assert usage_rule(100, 100, 0.02, -0.04) == "find failures, measure on real"  # |gap| counts
