"""
Solution: pairwise comparisons. Lab 11's pairwise math (evalkit/pairwise.py and Scripts 1-3), standard library only.
Scores are always for version A: 1 = A won, 0 = A lost (B won), 0.5 = tie.
"""
import math

Z_95 = 1.959964   # two-sided 95%, as in the lab
Z_80 = 0.841621   # one-sided z for 80% power


def swap_outcome(pick_ab, pick_ba):
    """Same pick in both orders: that version wins. Different picks: a tie."""
    if pick_ab == pick_ba:
        return 1.0 if pick_ab == "A" else 0.0
    return 0.5


def tally(scores):
    """Wins, losses, ties, the win rate with ties as half, and the decisive win rate."""
    wins = sum(1 for s in scores if s == 1)
    losses = sum(1 for s in scores if s == 0)
    ties = sum(1 for s in scores if s == 0.5)
    n = len(scores)
    decisive = wins / (wins + losses) if wins + losses else None
    return {"wins": wins, "losses": losses, "ties": ties, "n": n,
            "win_rate": sum(scores) / n if n else None, "decisive": decisive}


def wilson_ci(k, n, z=Z_95):
    if n == 0:
        return 0.0, 1.0
    p = k / n
    denom = 1 + z * z / n
    centre = (p + z * z / (2 * n)) / denom
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
    return max(0.0, centre - half), min(1.0, centre + half)


def verdict(wins, losses):
    lo, hi = wilson_ci(wins, wins + losses)
    if lo > 0.5:
        return "A better"
    if hi < 0.5:
        return "B better"
    return "can't tell"


def comparisons_needed(p_win, z_alpha=Z_95, z_power=Z_80):
    d = abs(p_win - 0.5)
    top = z_alpha * 0.5 + z_power * math.sqrt(p_win * (1 - p_win))
    return math.ceil((top / d) ** 2)


def _sigmoid(x):
    return 1 / (1 + math.exp(-x))


def expected_tie_rate(gap, bias):
    p_ab = _sigmoid(gap + bias)       # A shown first: picks the first (A)
    p_ba = _sigmoid(-gap + bias)      # B shown first: picks the first (B)
    return p_ab * p_ba + (1 - p_ab) * (1 - p_ba)


def bradley_terry(results, prior=0.5, iters=2000):
    wins, games, names = {}, {}, set()
    for (a, b), (score_a, n) in results.items():
        names |= {a, b}
        wins[a] = wins.get(a, 0.0) + score_a + prior / 2
        wins[b] = wins.get(b, 0.0) + (n - score_a) + prior / 2
        key = tuple(sorted((a, b)))
        games[key] = games.get(key, 0.0) + n + prior
    opponents = {k: [] for k in names}
    for (a, b), n in games.items():
        opponents[a].append((b, n))
        opponents[b].append((a, n))
    s = {k: 1.0 for k in names}
    for _ in range(iters):
        new = {i: wins[i] / sum(n / (s[i] + s[j]) for j, n in opponents[i]) for i in names}
        g = math.exp(sum(math.log(v) for v in new.values()) / len(new))
        new = {k: v / g for k, v in new.items()}
        done = max(abs(new[k] - s[k]) for k in names) < 1e-10
        s = new
        if done:
            break
    return {k: math.log(v) for k, v in s.items()}


def to_elo(log_strengths, base=1000.0):
    return {k: base + 400 * v / math.log(10) for k, v in log_strengths.items()}
