"""Tests on Lab 11's recorded results (eval labs, Pairwise Comparisons and Rankings). Everything is simulated:
five versions of a ticket summarizer with true strengths set in the lab, and an AI judge built to favour the
summary it reads first. The strings below are the exact verdicts the lab's scripts produce with their seeds.
Run: pytest test_pairwise_practice.py"""
import math

from pairwise_practice import (bradley_terry, comparisons_needed, expected_tie_rate, swap_outcome, tally, to_elo,
                               verdict, wilson_ci)

# 01_win_rates.py, Exercise 1 (seed 0): the new version (v3) against the old one (v1), 300 tickets per design.
# One fixed order: 1 = the judge picked v3.
NEW_FIRST = ("1101011111111011010111010111011110100101100000000010100111111111111111110001111110101010001110111101"
             "1111010110111111010001100101101111101010010011110011001111101111111011111101110111111101111101100111"
             "0100101001111011111111011011101111011011111111110001100110011101101110111001111101111111111101111111")
OLD_FIRST = ("1111000001010011010100100001000000000001000100100000001001101010001001101001110101110110000000001001"
             "1100100011010001011110111100001011110010111110010110100101000101110001100100010011111010101010100100"
             "1010000101110011001000100011110010010001010111101010010010011110111001011110001011111110010000111000")
# Both orders, one letter per ticket: W = picked v3 both times, L = picked v1 both times,
# F = picked whichever was shown first both times, S = picked whichever was shown second both times.
BOTH = ("WWFWFFFFFWFSFFFWFLWSFWFFWWWWFFFFSLLFFWFFFFFFFLFWWFFFSWWLSWWLWSWSWWSFWWSWSFLLFFWLFFFFWFFLSFLWWWFFWWSL"
        "FWFSSWSFLFFWLFWWFFWWFWSSFFFFWFLLSWWFSWFLWFFFLFWWWWFWSLSLSFFFWLWLLLFWFWSWWSFWWWLFLSFWSWFSLWFSSLFFLWWW"
        "FFFFWFSLFSFFFSFFFFWLFFSFWFFWFLFFFFWSLLFWLFWWLWWWFWFFLWFFWFWFWFFLFSWLWFFWLWLWSFFFFFFWLFFWLFFLFWLFWWWL")
# (pick when v3 is shown first, pick when v1 is shown first), with A = v3 and B = v1
PICKS = {"W": ("A", "A"), "L": ("B", "B"), "F": ("A", "B"), "S": ("B", "A")}

# 02_bradley_terry.py (seed 0): every pair on 150 tickets, both orders = 1,500 comparisons.
# (a, b): (a's total score with ties as half, comparisons)
ROUND_ROBIN = {
    ("v1", "v2"): (72.5, 150), ("v1", "v3"): (52.5, 150), ("v1", "v4"): (56.5, 150), ("v1", "v5"): (56.0, 150),
    ("v2", "v3"): (59.0, 150), ("v2", "v4"): (65.0, 150), ("v2", "v5"): (66.5, 150), ("v3", "v4"): (74.5, 150),
    ("v3", "v5"): (64.5, 150), ("v4", "v5"): (77.5, 150),
}


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


def test_swap_outcome():
    assert swap_outcome("A", "A") == 1.0
    assert swap_outcome("B", "B") == 0.0
    assert swap_outcome("A", "B") == 0.5      # picked the first-shown both times
    assert swap_outcome("B", "A") == 0.5      # picked the second-shown both times: a tie too


def test_one_fixed_order_flatters_whoever_goes_first():
    first = tally([float(c) for c in NEW_FIRST])
    second = tally([float(c) for c in OLD_FIRST])
    assert (first["wins"], first["losses"], first["ties"]) == (210, 90, 0)
    assert close(first["win_rate"], 0.700)
    assert (second["wins"], second["losses"]) == (136, 164)
    assert close(second["win_rate"], 136 / 300)          # 45.3%


def test_both_orders_wins_losses_ties():
    t = tally([swap_outcome(*PICKS[c]) for c in BOTH])
    assert (t["wins"], t["losses"], t["ties"], t["n"]) == (92, 46, 162, 300)
    assert round(t["win_rate"], 3) == 0.577              # ties as half; the truth is 60.7%
    assert round(t["decisive"], 3) == 0.667              # decisive only: too high
    assert BOTH.count("S") == 36                         # 36 of the 162 ties went to the second-shown summary


def test_wilson_and_the_check():
    lo, hi = wilson_ci(92, 138)
    assert close(lo, 0.5844) and close(hi, 0.7399)       # 58-74%: clear of 50%
    assert verdict(92, 46) == "A better"
    assert verdict(122, 96) == "can't tell"              # v4 vs v5, simple tickets
    assert verdict(111, 86) == "can't tell"              # multi-request
    assert verdict(50, 147) == "B better"                # angry customers: v5 better
    assert verdict(208, 199) == "can't tell"             # all tickets
    assert wilson_ci(0, 0) == (0.0, 1.0)


def test_comparisons_needed():
    assert [comparisons_needed(p) for p in (0.55, 0.60, 0.65, 0.75)] == [783, 194, 85, 29]
    assert comparisons_needed(0.45) == comparisons_needed(0.55)


def test_ties_are_not_all_bias():
    assert close(expected_tie_rate(0.0, 0.0), 0.5)       # no bias: a version against itself ties half the time
    assert close(expected_tie_rate(0.0, 0.5), 0.530)     # this judge (+0.5 log-odds for the first): 53.0%
    assert close(expected_tie_rate(0.0, 0.5), 0.6225 ** 2 + 0.3775 ** 2)


def test_bradley_terry_matches_the_lab():
    est = bradley_terry(ROUND_ROBIN)
    lab = {"v5": 0.1919, "v4": 0.1702, "v3": 0.1486, "v2": -0.1720, "v1": -0.3388}
    for v, x in lab.items():
        assert close(est[v], x), (v, est[v])
    assert close(sum(est.values()), 0.0, 1e-9)
    assert sorted(est, key=lambda v: -est[v]) == ["v5", "v4", "v3", "v2", "v1"]


def test_elo_scale():
    elo = to_elo(bradley_terry(ROUND_ROBIN))
    assert [round(elo[v]) for v in ("v5", "v4", "v3", "v2", "v1")] == [1033, 1030, 1026, 970, 941]
    assert close(to_elo({"x": math.log(10), "y": 0.0})["x"] - 1000, 400)
