"""Tests on Lab 16's recorded results (eval-ai-labs, 16_input_forms). The refund policy and the
150 cases are made up (00_build.py, seed 16); the answers are real recorded runs of gpt-5.4-nano,
two per case and form (data/results/answers.jsonl). Run: pytest test_forms_practice.py"""
from forms_practice import (aa_flips, blame, cost_per_1k_correct, decide, depth, flip_explains,
                            mcnemar_p, paired_mean_diff, parse_outcome, path, wilson_ci)

LABEL = {"F": "FULL_REFUND", "P": "PARTIAL_REFUND", "R": "REPLACEMENT", "S": "STORE_CREDIT", "X": "REFUSE",
         "?": "INVALID"}

# data/cases.jsonl, sorted by id: (id, days, state, price, member, refund in the last 90 days,
# final sale, right answer as a code from LABEL).
CASES = [
    ("c001", 124, "defective", 120, 1, 1, 0, "S"),
    ("c002", 61, "unopened", 89, 1, 0, 0, "X"),
    ("c003", 80, "opened", 19, 0, 1, 0, "X"),
    ("c004", 8, "defective", 240, 0, 0, 0, "R"),
    ("c005", 93, "defective", 120, 0, 1, 0, "S"),
    ("c006", 145, "unopened", 120, 1, 1, 0, "X"),
    ("c007", 61, "damaged", 199, 1, 0, 1, "R"),
    ("c008", 4, "defective", 240, 1, 0, 0, "R"),
    ("c009", 30, "opened", 199, 0, 0, 0, "P"),
    ("c010", 29, "damaged", 180, 1, 0, 0, "F"),
    ("c011", 19, "damaged", 89, 1, 1, 1, "R"),
    ("c012", 29, "unopened", 35, 0, 0, 1, "X"),
    ("c013", 66, "opened", 89, 0, 1, 0, "X"),
    ("c014", 31, "unopened", 200, 1, 0, 0, "S"),
    ("c015", 29, "defective", 199, 0, 0, 0, "F"),
    ("c016", 59, "unopened", 201, 1, 0, 1, "X"),
    ("c017", 33, "defective", 60, 1, 1, 0, "F"),
    ("c018", 45, "opened", 180, 0, 0, 0, "X"),
    ("c019", 32, "damaged", 35, 0, 1, 0, "F"),
    ("c020", 90, "unopened", 240, 0, 0, 1, "X"),
    ("c021", 15, "unopened", 240, 0, 0, 1, "X"),
    ("c022", 31, "defective", 200, 1, 1, 0, "F"),
    ("c023", 29, "damaged", 89, 1, 0, 1, "R"),
    ("c024", 6, "unopened", 180, 1, 0, 0, "F"),
    ("c025", 91, "damaged", 320, 0, 0, 0, "S"),
    ("c026", 56, "defective", 240, 1, 0, 0, "R"),
    ("c027", 28, "unopened", 89, 1, 0, 0, "F"),
    ("c028", 25, "unopened", 60, 1, 0, 0, "F"),
    ("c029", 59, "defective", 201, 1, 0, 0, "R"),
    ("c030", 147, "opened", 60, 0, 0, 0, "X"),
    ("c031", 91, "defective", 35, 1, 1, 0, "S"),
    ("c032", 90, "damaged", 199, 1, 1, 0, "F"),
    ("c033", 15, "opened", 480, 1, 0, 0, "F"),
    ("c034", 89, "opened", 201, 1, 0, 1, "X"),
    ("c035", 29, "unopened", 240, 1, 0, 1, "X"),
    ("c036", 50, "damaged", 480, 0, 0, 0, "R"),
    ("c037", 14, "unopened", 35, 0, 1, 0, "F"),
    ("c038", 78, "opened", 240, 0, 0, 0, "X"),
    ("c039", 137, "opened", 35, 0, 1, 0, "X"),
    ("c040", 114, "unopened", 145, 0, 0, 0, "X"),
    ("c041", 145, "unopened", 240, 1, 1, 0, "X"),
    ("c042", 90, "damaged", 199, 0, 0, 1, "R"),
    ("c043", 30, "opened", 60, 0, 0, 0, "P"),
    ("c044", 69, "damaged", 19, 0, 0, 0, "F"),
    ("c045", 55, "opened", 60, 0, 0, 0, "X"),
    ("c046", 29, "opened", 120, 1, 0, 0, "F"),
    ("c047", 30, "unopened", 180, 1, 0, 0, "F"),
    ("c048", 59, "opened", 199, 1, 0, 0, "S"),
    ("c049", 29, "defective", 60, 1, 1, 0, "F"),
    ("c050", 110, "damaged", 145, 0, 0, 0, "S"),
    ("c051", 138, "damaged", 19, 1, 0, 0, "S"),
    ("c052", 23, "opened", 320, 0, 0, 1, "X"),
    ("c053", 60, "unopened", 200, 1, 1, 0, "S"),
    ("c054", 89, "damaged", 145, 1, 0, 1, "R"),
    ("c055", 1, "defective", 89, 0, 1, 0, "F"),
    ("c056", 35, "unopened", 19, 0, 1, 0, "X"),
    ("c057", 71, "defective", 19, 1, 1, 0, "F"),
    ("c058", 64, "unopened", 89, 0, 1, 0, "X"),
    ("c059", 61, "defective", 199, 1, 0, 0, "F"),
    ("c060", 61, "damaged", 200, 1, 0, 1, "R"),
    ("c061", 30, "opened", 180, 0, 0, 0, "P"),
    ("c062", 31, "defective", 480, 0, 1, 0, "R"),
    ("c063", 30, "damaged", 201, 0, 0, 0, "R"),
    ("c064", 15, "unopened", 480, 1, 0, 1, "X"),
    ("c065", 9, "defective", 180, 1, 1, 1, "X"),
    ("c066", 61, "defective", 180, 0, 1, 0, "F"),
    ("c067", 89, "defective", 35, 1, 0, 0, "F"),
    ("c068", 148, "opened", 180, 1, 0, 1, "X"),
    ("c069", 71, "damaged", 145, 1, 1, 0, "F"),
    ("c070", 29, "defective", 201, 1, 0, 1, "X"),
    ("c071", 23, "damaged", 180, 0, 0, 1, "R"),
    ("c072", 73, "damaged", 240, 0, 0, 0, "R"),
    ("c073", 91, "opened", 180, 1, 1, 1, "X"),
    ("c074", 90, "damaged", 240, 1, 0, 0, "R"),
    ("c075", 81, "damaged", 180, 0, 1, 1, "R"),
    ("c076", 59, "unopened", 480, 1, 0, 0, "S"),
    ("c077", 144, "unopened", 180, 0, 0, 1, "X"),
    ("c078", 90, "damaged", 480, 1, 0, 0, "R"),
    ("c079", 24, "defective", 89, 1, 1, 1, "X"),
    ("c080", 29, "unopened", 199, 1, 0, 0, "F"),
    ("c081", 3, "defective", 240, 0, 1, 0, "R"),
    ("c082", 59, "opened", 35, 1, 0, 0, "S"),
    ("c083", 146, "damaged", 19, 0, 1, 0, "S"),
    ("c084", 97, "defective", 120, 1, 0, 0, "S"),
    ("c085", 91, "damaged", 240, 0, 0, 0, "S"),
    ("c086", 91, "defective", 200, 0, 1, 0, "S"),
    ("c087", 79, "damaged", 320, 0, 0, 0, "R"),
    ("c088", 14, "unopened", 89, 1, 1, 0, "F"),
    ("c089", 126, "damaged", 35, 0, 0, 1, "R"),
    ("c090", 34, "damaged", 480, 0, 0, 0, "R"),
    ("c091", 105, "damaged", 145, 0, 0, 0, "S"),
    ("c092", 11, "opened", 120, 1, 1, 0, "S"),
    ("c093", 109, "damaged", 145, 0, 0, 0, "S"),
    ("c094", 57, "opened", 240, 1, 0, 0, "S"),
    ("c095", 15, "damaged", 320, 0, 0, 0, "R"),
    ("c096", 120, "damaged", 35, 1, 0, 0, "S"),
    ("c097", 121, "defective", 19, 0, 0, 0, "S"),
    ("c098", 29, "unopened", 199, 0, 0, 0, "F"),
    ("c099", 28, "unopened", 19, 1, 0, 0, "F"),
    ("c100", 141, "damaged", 19, 0, 0, 1, "R"),
    ("c101", 59, "opened", 200, 1, 0, 0, "S"),
    ("c102", 60, "unopened", 120, 1, 0, 0, "S"),
    ("c103", 29, "unopened", 200, 1, 1, 0, "F"),
    ("c104", 60, "opened", 199, 1, 0, 0, "S"),
    ("c105", 47, "damaged", 320, 0, 0, 1, "R"),
    ("c106", 11, "damaged", 180, 0, 1, 1, "R"),
    ("c107", 30, "unopened", 180, 0, 1, 0, "F"),
    ("c108", 29, "unopened", 180, 0, 0, 0, "F"),
    ("c109", 59, "damaged", 199, 0, 0, 1, "R"),
    ("c110", 29, "damaged", 145, 1, 0, 1, "R"),
    ("c111", 29, "unopened", 201, 0, 0, 0, "F"),
    ("c112", 30, "opened", 60, 0, 0, 0, "P"),
    ("c113", 54, "unopened", 120, 1, 0, 0, "S"),
    ("c114", 60, "opened", 201, 1, 0, 0, "S"),
    ("c115", 31, "opened", 240, 1, 0, 0, "S"),
    ("c116", 29, "opened", 180, 1, 0, 0, "F"),
    ("c117", 28, "opened", 19, 0, 1, 0, "S"),
    ("c118", 30, "opened", 200, 0, 1, 0, "S"),
    ("c119", 57, "opened", 60, 1, 0, 0, "S"),
    ("c120", 1, "opened", 240, 1, 1, 0, "S"),
    ("c121", 2, "opened", 89, 0, 0, 0, "P"),
    ("c122", 23, "opened", 35, 0, 0, 0, "P"),
    ("c123", 12, "opened", 180, 1, 0, 0, "F"),
    ("c124", 8, "opened", 120, 1, 0, 0, "F"),
    ("c125", 8, "opened", 35, 0, 0, 0, "P"),
    ("c126", 29, "opened", 35, 1, 0, 0, "F"),
    ("c127", 5, "opened", 60, 0, 1, 0, "S"),
    ("c128", 15, "opened", 480, 0, 0, 0, "P"),
    ("c129", 27, "opened", 240, 0, 0, 0, "P"),
    ("c130", 14, "opened", 145, 1, 0, 0, "F"),
    ("c131", 29, "opened", 480, 0, 0, 0, "P"),
    ("c132", 17, "opened", 120, 1, 0, 0, "F"),
    ("c133", 17, "opened", 320, 0, 0, 0, "P"),
    ("c134", 28, "opened", 240, 0, 0, 0, "P"),
    ("c135", 13, "opened", 120, 1, 1, 0, "S"),
    ("c136", 30, "opened", 145, 0, 1, 0, "S"),
    ("c137", 11, "opened", 89, 0, 0, 0, "P"),
    ("c138", 13, "opened", 60, 0, 1, 0, "S"),
    ("c139", 9, "opened", 180, 1, 1, 0, "S"),
    ("c140", 29, "opened", 480, 1, 0, 0, "F"),
    ("c141", 23, "opened", 480, 1, 1, 0, "S"),
    ("c142", 27, "opened", 145, 1, 0, 0, "F"),
    ("c143", 16, "opened", 19, 1, 0, 0, "F"),
    ("c144", 8, "opened", 240, 0, 1, 0, "S"),
    ("c145", 4, "opened", 35, 1, 0, 0, "F"),
    ("c146", 1, "opened", 19, 0, 1, 0, "S"),
    ("c147", 10, "opened", 145, 1, 0, 0, "F"),
    ("c148", 29, "opened", 19, 0, 1, 0, "S"),
    ("c149", 10, "opened", 89, 0, 1, 0, "S"),
    ("c150", 1, "opened", 19, 1, 0, 0, "F"),
]

# Every recorded nano answer per form: two letters per case (run 0, run 1), cases in the order above.
ANSWERS = {
    "prose": (
        "SSXSXSRRSSSSRRRRPXFFSSXXSXSXFFXFSSXXSSXXXXSSRRFFRSRRFFFFRRXXSSSSFPRXXXRRSSXXXXXXSXRRXPFRXXFFFFSSSSXX"
        "XXXXSSRRSSSSSSSSSXRRPPSSRRXXSRXSFFXXSSRRRRRRXXRRPR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XX"
        "FFSSSSFSXR?RSSFFRXXRRR?FFFSSFFFFSSSSFFSSPPFFFSFFXFFFSSFFFRFFFFFFPFFRSSSSFXSSSSFFSSFFFFSSFFSSFFSSSSFF"
    ),
    "image": (
        "SSPSSXFRSSSPRXFRSXRRRXXXSSSFFFXRPSSSSSRRXXPPXXFSFRFFSPFPFFXXSSRRPPRRXRFFSSSFXXSSSPRXSSRRSSPSSSFSPPRX"
        "XSXXPPRRRXSSSSSSSPRXSSSSRRRRXRSSFSXXSSRRXXFFXXRRRXFFXXFRRRSSXRPSSSSFFFXSFRPSXRRRRRSPXRPSRRXSXXFFSSXX"
        "PSFSSSPPXXXRSXFSXXXRSFSSSSPFPSSPXXSSPSPFXXXSSSPPXXSSXXSSSSPPXXPPXSFSPPSXSXXPSPSPPSSSSSPSPPXXSSXSXSPX"
    ),
    "image_low": (
        "SXSSXXXFXXXXPXRFFFSRXXXXXXSFFSXXSXFFXXXSFFSXRRSSXFFSSXSSFSXXXSXXSSXXSSRXXXSXXXXXXXXXFSXXSSSSSSSSXSXX"
        "SSXXXSSRPXXXXPXXPSXXSFXSFRSSXXXSXSXXSXRSXXXXXXRRXXSFXXSRSXSSXXXSXXSSFFXXXXSXXXFRXRSSXXSSFRFSXSFFFSXX"
        "SSFSXFXSXXXXXXFFXXRRFXFSPSSFSSSSXXXXSSSSFXSFSSSSSFSSXXXFFFSFSSFSFXFFFSXSXFXXSSSPSSSSSSFXXSXXFSXXXXSS"
    ),
    "image+mermaid": (
        "SXXSSSFRXXXSXRFFXXSSRXRXSSXSSXRXSSXXRRXRRXSSRRSSXSSSSSSSSFXXPXRRSXRXRXRRSSXSSXXXSSRRXXSSXXPXFSXXSSXX"
        "XSXXSSRRSSSSSSSSSSRRXXSSRRRRRRSSSSXXSSRRRRRRXXRRRRFSXXRRRRSSSSXSSSSSXSXXRRSSRRSRXXSSXXSSRRXSXXSSSSXX"
        "XXFSSSXPRRRRSSSSRRRRXSXXSSXXXPXPSSSSSXFSXXXXXXSPXXXXSSXXXXXXXXXXXSXXSSSSXXSSSSXPSSSXXPSSXSSSXXSSSSPX"
    ),
}
# What each form's 300 answers cost in total, in dollars (input + output tokens at the lab's prices).
TOTAL_COST = {"prose": 0.0248164, "json": 0.0391514, "mermaid": 0.0345639, "mermaid_unshared": 0.0359314, "image": 0.13210515, "image_low": 0.0511039, "image+mermaid": 0.15451765}


def case(row):
    return {"days": row[1], "state": row[2], "price": row[3], "member": bool(row[4]),
            "prior_refund": bool(row[5]), "final_sale": bool(row[6])}


def answers(form):
    s = ANSWERS[form]
    return {row[0]: [LABEL[s[2 * i]], LABEL[s[2 * i + 1]]] for i, row in enumerate(CASES)}


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


def test_engine_gives_every_cases_recorded_answer():
    assert all(decide(case(r)) == LABEL[r[7]] for r in CASES)


def test_one_day_changes_the_outcome():
    # the video's worked example: unopened, $180, not a member, a refund in the last 90 days
    c = case(next(r for r in CASES if r[0] == "c107"))
    assert c["days"] == 30 and decide(c) == "FULL_REFUND"
    assert decide(dict(c, days=31)) == "REFUSE"
    steps, outcome = path(c)
    assert steps == [("Final-sale item?", False), ("Arrived damaged or defective?", False),
                     ("Delivered 30 days ago or less?", True), ("Opened?", False)]


def test_depths_and_paths():
    depths = [depth(case(r)) for r in CASES]
    assert {k: depths.count(k) for k in range(2, 7)} == {2: 28, 3: 14, 4: 67, 5: 14, 6: 27}
    paths = {}
    for r in CASES:
        key = tuple(path(case(r))[0])
        paths[key] = paths.get(key, 0) + 1
    assert len(paths) == 11 and sorted(set(paths.values())) == [13, 14]   # stratified by path


def test_flip_explains():
    c = case(next(r for r in CASES if r[0] == "c107"))
    # 11 of the 14 nano answers on this case were store credit: one flip gives it
    assert flip_explains(c, "STORE_CREDIT") == ["Opened?"]
    # refuse: two different flips give it (calling it final sale, or reading day 30 as "over 30 days")
    assert flip_explains(c, "REFUSE") == ["Final-sale item?", "Delivered 30 days ago or less?"]
    assert flip_explains(c, "REPLACEMENT") == []          # off the path: no single flip


def test_blame_takes_the_deepest_and_handles_invalid():
    c = {"days": 120, "state": "damaged", "price": 100, "member": False, "prior_refund": False,
         "final_sale": False}                                  # right answer: store credit
    assert decide(c) == "STORE_CREDIT"
    assert flip_explains(c, "REFUSE") == ["Arrived damaged or defective?"]
    assert blame(c, "REFUSE") == "Arrived damaged or defective?"
    two = {"days": 20, "state": "opened", "price": 100, "member": False, "prior_refund": False,
           "final_sale": False}                                  # right answer: partial refund
    assert decide(two) == "PARTIAL_REFUND"
    assert flip_explains(two, "FULL_REFUND") == ["Arrived damaged or defective?", "Opened?", "Member?"]
    assert blame(two, "FULL_REFUND") == "Member?"     # three flips explain it; the lab blames the deepest
    assert blame(c, "INVALID") == "none" and blame(c, "PARTIAL_REFUND") == "none"


def test_blame_counts_match_the_lab():
    for form, wrong_total, none, top in [
        ("prose", 86, 7, ("Delivered 90 days ago or less?", 25)),
        ("image", 217, 34, ("Delivered 30 days ago or less?", 35)),
        ("mermaid_unshared", 144, 8, ("Delivered 90 days ago or less?", 27)),   # 3 of the 8 are unreadable
    ]:
        counts = {}
        for r in CASES:
            for got in answers(form)[r[0]]:
                if got != LABEL[r[7]]:
                    b = blame(case(r), got)
                    counts[b] = counts.get(b, 0) + 1
        assert sum(counts.values()) == wrong_total
        assert counts["none"] == none
        assert max((v, k) for k, v in counts.items() if k != "none") == (top[1], top[0])


def test_parse_outcome():
    assert parse_outcome('{"outcome": "STORE_CREDIT"}') == "STORE_CREDIT"
    assert parse_outcome('{"outcome": "store credit"}') == "STORE_CREDIT"
    assert parse_outcome("I would REFUSE this one") == "REFUSE"
    assert parse_outcome('{"outcome": "REFUND"}') == "INVALID"
    assert parse_outcome("") == "INVALID"
    assert parse_outcome('["FULL_REFUND"]') == "FULL_REFUND"     # JSON, but not an object


def test_accuracy_and_wilson():
    right = {f: sum(g == LABEL[r[7]] for r in CASES for g in answers(f)[r[0]]) for f in ANSWERS}
    assert right == {"prose": 214, "json": 168, "mermaid": 127, "mermaid_unshared": 156, "image": 83,
                     "image_low": 97, "image+mermaid": 114}
    lo, hi = wilson_ci(214, 300)
    assert (round(lo, 2), round(hi, 2)) == (0.66, 0.76)
    lo, hi = wilson_ci(83, 300)
    assert (round(lo, 2), round(hi, 2)) == (0.23, 0.33)
    assert wilson_ci(0, 0) == (0.0, 1.0)


def test_paired_differences_and_aa():
    runs = {f: {i: [g == LABEL[r[7]] for g in answers(f)[i]] for r in CASES for i in [r[0]]} for f in ANSWERS}
    assert round(100 * paired_mean_diff(runs["prose"], runs["json"]), 1) == 15.3
    assert round(100 * paired_mean_diff(runs["mermaid_unshared"], runs["mermaid"]), 1) == 9.7
    assert round(100 * paired_mean_diff(runs["image+mermaid"], runs["image"]), 1) == 10.3
    assert aa_flips(runs["prose"]) == 22 and aa_flips(runs["mermaid"]) == 47 and aa_flips(runs["image"]) == 41


def test_mcnemar():
    assert round(mcnemar_p(29, 8), 3) == 0.001        # prose vs JSON on nano, run 0
    assert round(mcnemar_p(15, 13), 3) == 0.851       # prose vs JSON on the bigger model: no clear difference
    assert round(mcnemar_p(4, 14), 3) == 0.031        # Mermaid, shared vs own boxes, bigger model
    assert mcnemar_p(23, 23) == 1.0 and mcnemar_p(0, 0) == 1.0


def test_cost_per_correct_answer():
    prose = cost_per_1k_correct(TOTAL_COST["prose"], 214)
    image = cost_per_1k_correct(TOTAL_COST["image"], 83)
    assert (round(prose, 3), round(image, 3)) == (0.116, 1.592)
    assert round(image / prose, 1) == 13.7
    assert close(cost_per_1k_correct(0.5, 0), 500.0)
