"""Tests on Lab 15's recorded results (eval labs, Does the Prompt Style Help?). The summaries are real
gpt-5.4-nano runs that the lab recorded; the 120 conversations are Lab 09's simulated support chats. Nothing here
calls a model. Run: pytest test_style_practice.py"""
from style_practice import (contrasts, effects, fact_present, flesch, null_band, per_conversation, syllables,
                            verdict, words)

ARMS = ["normal", "ste", "pc", "both"]

# One conversation from the lab's test set (Jordan, a damaged fleece), run 1 of each arm, and the Flesch
# score 04_score.py recorded for it.
JORDAN = {
    "normal": ("Jordan (order #44339) reported that the Alpine Fleece arrived damaged with a crushed box; it was a birthday gift for his daughter, adding urgency. He requested a refund of $120. The agent apologized, said they’d review order #44339, and promised to issue the $120 refund within 3–5 days.", 58.942499999999995, 48),
    "ste": ("Jordan reported that Alpine Fleece (order #44339) arrived damaged. The shipping box was crushed. Jordan asked for a refund of $120 because it was a birthday gift for his daughter. I said I will take care of it by issuing the $120 refund in 3–5 days.", 75.61902173913046, 46),
    "pc": ("Evidence: Customer said “Jordan” and “Alpine Fleece (order #44339)” and “arrived damaged” with “box was crushed.” (Next agent needs product, order number, damage description, and customer name.) Evidence: Customer requested “refund of $120” and stated it was a “birthday gift for my daughter” (adds urgency: gift date implied but no date given). Evidence: Agent promised “refund of $120 to be issued (3–5 days)” (what to do next: process refund and ensure timing). Evidence: Customer only said “Thanks” (no further requests).", 39.120833333333366, 80),
    "both": ("Jordan said his Alpine Fleece (order #44339) arrived damaged and the box was crushed. He asked for a refund of $120. He said it was a birthday gift for his daughter. The agent said they would handle a refund of $120 with an issue time of 3–5 days. The agent did not confirm the damage cause or give return steps in this chat.", 83.9317142857143, 63),
}

# All 120 conversations, one block each: the number of key facts (n), then for each of the 12 summaries
# (normal x3, STE x3, point-and-call x3, both x3) how many of the n facts the coverage rule found, then 12
# digits for the simulated reader (1 = all 4 questions right). From data/results/scores.jsonl.
CONVERSATIONS = " ".join([
    "4444444444444111111111111 3333333333333111111111111 3333333333333111111111111 3333333333333011111111111",
    "3333333333333111111111111 3333333333333111111101111 4444444444444111111111111 4444444444444111111101111",
    "4444444444444110111111111 4444444444444111111111110 4333333343344111110110101 2222222222222111111111111",
    "5555444444445111111111110 5555555555555110111111111 4444444444444111111111111 3222222332233111111110101",
    "4444444444444111111111111 5555555555555000000111110 4444444444444111111110111 3333333333333111111111111",
    "3333333333333111111111111 4444444444444001001111111 3333333333333100111001010 2222222222222111111111111",
    "2222222222222111111111111 5555555555555111111111111 3333333333333111111111111 3333333333333111111111111",
    "4444444444444001110000111 3222222223222111111111111 2222111222222111111111111 4444444444444111111111111",
    "5554555555555111010111111 4343333333333111111111111 5555555555555111111111111 3333333333333111111110111",
    "4444444444444001110111100 4444444444444110111011111 4444444444444101111011111 3333333333333111111111101",
    "2222222222222111111111101 3333333333333011111111100 4444444444444111111111111 4444444444444111111111011",
    "4444444444444111111111111 2111111212112101000010000 3333333333333111111011111 2222222222222111111111111",
    "3333333333333111111111111 2222222222222001111100101 4444444444444111111111111 4444444444444111111111111",
    "3333333333333111111111111 3333333333333111110111101 5555555555555111111011111 4344333334333111111111111",
    "4444444444444111111111111 4444444444444111011110111 4444444444444111111111111 4444444444444100010111111",
    "3333333333333111111011111 4444444444444000000010010 4333333444333111110111111 4444444444444111111111111",
    "3333333333333111111101111 5444444455444000101111111 4444444444444011000111111 4444444444444001111111111",
    "5555555555555111111111111 4444444444444101111111011 4333333343434111111111111 4444444444444101111111111",
    "3333333333333110000000010 3333333333333010000100101 3333333333333001110011111 2222222222222111111111111",
    "4433333333443111111111111 5554555555555111101110111 3333333333333011001111101 4444444444444111111111111",
    "4333333334334111111111010 5555555555555110100110001 3333333333333111111111111 4444444444444111111111110",
    "2222222222222101100111101 3333333333333111111111111 4444444444444111010000000 4444444444444101111111111",
    "5555555555555111111011111 3322222222233111101111111 5555555555555011011111110 2222222222222010111011111",
    "3333333333333111111110101 5555555555555111101101100 4444444444444111111111111 4334343434344111111111101",
    "4433333333334111111111110 2222222222222100011110010 2222222222222011111111111 4444444444444111111111111",
    "5555555555555111111111111 2222222222222111111111111 3333333333333111101110001 3333333333333111111101111",
    "2222222222222000111101011 3333333333333001100000100 4444333433444111111111110 4433334344443111111111111",
    "4444333443334111000110100 4444444444444111111111111 5555555555555110111111111 4444444444444111010110111",
    "2222222222222111111111111 5555555555555111111111111 3333333333333011111111111 5555555555555111111111111",
    "3333333333333111111111111 3333333333333000000110000 5555555555555111111111111 4444444444444111111111111",
]).split()


def runs(outcome):
    """{arm: [[run1, run2, run3] per conversation]} for "coverage" or "reader"."""
    out = {a: [] for a in ARMS}
    for c in CONVERSATIONS:
        n, hits, reader = int(c[0]), c[1:13], c[13:25]
        vals = [int(h) / n for h in hits] if outcome == "coverage" else [float(r) for r in reader]
        for i, a in enumerate(ARMS):
            out[a].append(vals[3 * i:3 * i + 3])
    return out


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


def test_syllables():
    assert syllables("the") == 1
    assert syllables("issued") == 2
    assert syllables("replacement") == 3          # silent e before -ment
    assert syllables("simple") == 2               # ends in -le: the e is kept
    assert syllables("") == 1                 # a number counts as one word sound


def test_flesch_matches_the_lab():
    for arm, (text, recorded, n_words) in JORDAN.items():
        assert len(words(text)) == n_words, arm
        assert close(flesch(text), recorded, 1e-9), arm
    assert flesch(JORDAN["ste"][0]) > flesch(JORDAN["normal"][0])   # short sentences: easier to read


def test_coverage_keyword_rule():
    order = ["44339"]
    refund = ["refund", ""]
    assert fact_present(JORDAN["normal"][0], order) and fact_present(JORDAN["normal"][0], refund)
    assert not fact_present("Jordan wants his money back.", refund)
    # Hana's parcel hasn't arrived. The STE summary asks where it is in plain words; the rule wants a keyword.
    ste = "Hana has order #60924 for a Merino Beanie. She says it still has not arrived after 10 days. She asked where the package actually is. The agent said they will look up order #60924, opened a carrier trace, and will update Hana within 48 hours."
    normal = "Hana (order #60924) says her Merino Beanie hasn’t arrived after 10 days and asked where the package is. She requested the delivery status/location. Agent apologized, checked the order, opened a carrier tracking trace, and promised to update her within 48 hours."
    assert fact_present(normal, ["tracking|delivery"])
    assert not fact_present(ste, ["tracking|delivery"])
    assert fact_present(ste, ["tracking|delivery|where"])


def test_per_conversation():
    per = per_conversation({"normal": [[1, 0.5, 0], [1, 1, 1]]})
    assert per == {"normal": [0.5, 1.0]}


def test_contrasts_one_conversation():
    c = contrasts([0.80], [0.90], [0.85], [0.85])
    assert close(c["STE"][0], 0.05)                # (+0.10 + 0.00) / 2
    assert close(c["point-and-call"][0], 0.0)     # (+0.05 - 0.05) / 2
    assert close(c["interaction"][0], -0.10)      # 0.00 - 0.10: together, less than the sum


def test_coverage_effects_match_05_effects():
    per = per_conversation(runs("coverage"))
    assert close(sum(per["normal"]) / 120, 0.969676)
    assert close(sum(per["ste"]) / 120, 0.956389)
    e = effects(per)
    assert close(e["STE"], -0.006458333)              # -0.6 points
    assert close(e["point-and-call"], 0.012708333)    # +1.3
    assert close(e["interaction"], 0.013657407)      # +1.4


def test_reader_effects_match_05_effects():
    e = effects(per_conversation(runs("reader")))
    assert close(e["STE"], -0.004166667)              # -0.4 points: Flesch +14 didn't help
    assert close(e["point-and-call"], 0.015277778)    # +1.5
    assert close(e["interaction"], -0.019444444)      # -1.9


def test_null_band():
    rows = []
    for c in CONVERSATIONS:
        n = int(c[0])
        rows.append([int(h) / n for h in c[1:13]])
    lo, hi = null_band(rows, n_perm=400, seed=1)
    assert lo < 0 < hi
    assert 0.008 < hi - lo < 0.016               # the lab's band: -0.56 to +0.57 points


# 05_effects.py, Exercise 1: (estimate, low, high) for the four deciding outcomes.
PLAN = {"coverage": (0.05, 1), "conditions_kept": (0.10, 1), "unbacked_status": (0.05, -1), "reader_correct": (0.10, 1)}
STE = {
    "coverage": (-0.006458, -0.013171, -0.000624),
    "conditions_kept": (0.000231, -0.001389, 0.002083),
    "unbacked_status": (0.001389, -0.002778, 0.006944),
    "reader_correct": (-0.004167, -0.040278, 0.030556),
}
PC = {
    "coverage": (0.012708, 0.005046, 0.021737),
    "conditions_kept": (0.000231, -0.001389, 0.002083),
    "unbacked_status": (-0.001389, -0.006944, 0.002778),
    "reader_correct": (0.015278, -0.022222, 0.054167),
}


def test_the_rule_as_written():
    assert verdict(STE, PLAN) == "reject"            # a 0.6-point coverage drop, interval below zero
    assert verdict(PC, PLAN) == "no clear effect"    # +1.3 coverage is under the 5-point bar


def test_a_harm_bar_changes_the_verdict():
    assert verdict(STE, PLAN, harm_share=0.5) == "no clear effect"
    assert verdict(PC, PLAN, harm_share=0.5) == "no clear effect"


def test_rule_other_cases():
    plan = {"coverage": (0.05, 1), "unbacked_status": (0.05, -1)}
    assert verdict({"coverage": (0.08, 0.03, 0.12), "unbacked_status": (0.0, -0.01, 0.01)}, plan) == "adopt"
    assert verdict({"coverage": (0.08, 0.03, 0.12), "unbacked_status": (0.06, 0.02, 0.10)}, plan) == "trade-off"
    # lower is better: a drop in unbacked status is not a harm
    assert verdict({"coverage": (0.0, -0.01, 0.01), "unbacked_status": (-0.06, -0.10, -0.02)}, plan) == "adopt"
    # a gain past the bar whose interval includes zero doesn't count
    assert verdict({"coverage": (0.06, -0.01, 0.13), "unbacked_status": (0.0, -0.01, 0.01)}, plan) == "no clear effect"
