"""Tests on Lab 09's logic and recorded runs (31 October and 2 November 2026, Apple M4 Max, Docker
Desktop with 16 vCPU, Postgres 18.6 with two streaming replicas): 01_lag.py, 03_read_your_writes.py
and 04_monotonic_reads.py. The interval and violation cases are the lab's own tests; the counts
are the recorded results.
Run: pytest test_replica_practice.py"""
from replica_practice import (lag_summary, monotonic_violations, parse_lsn, percentile, route_lsn,
                              route_monotonic, route_window, wilson)


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


def test_wilson_known_values():
    lo, hi = wilson(10, 100)
    assert close(lo, 0.0552, 1e-3) and close(hi, 0.1744, 1e-3)
    lo, hi = wilson(0, 100)
    assert lo == 0 and close(hi, 0.0370, 1e-3)


def test_wilson_recorded_rates():
    # replica1 at idle: 700 of 15,275 reads missed the user's own booking -> 4.26%-4.93%
    lo, hi = wilson(700, 15275)
    assert close(lo, 0.04262) and close(hi, 0.04926)
    # replica2 under 4,000 updates/s: 4,277 of 8,395 -> 49.88%-52.02%
    lo, hi = wilson(4277, 8395)
    assert close(lo, 0.49877) and close(hi, 0.52016)


def test_zero_is_not_never():
    # the receipt number at idle: 0 of 13,997 missed, but the interval still allows up to 0.03%
    lo, hi = wilson(0, 13997)
    assert lo == 0 and close(hi, 0.000274, 1e-5)


def test_wilson_errors():
    for k, n in ((1, 0), (6, 5)):
        try:
            wilson(k, n)
        except ValueError:
            continue
        raise AssertionError("expected ValueError")


def test_monotonic_violations_lab_case():
    m = monotonic_violations([1, 2, 2, 5, 3, 4, 6, 1])
    assert m["violations"] == 3 and m["worst_step_back"] == 5     # 3 < 5, 4 < 5, 1 < 6
    assert monotonic_violations([1, 1, 2, 3])["violations"] == 0
    assert monotonic_violations([])["reads"] == 0


def test_alternating_copies_go_back():
    # copy 1 is 42 values ahead of copy 2; a reader alternates between them
    reads = [1042, 1000, 1052, 1010, 1062, 1020]
    m = monotonic_violations(reads)
    assert m["violations"] == 3 and m["worst_step_back"] == 42


def test_percentile_is_linear():
    assert percentile([0.0, 1.0], 50) == 0.5
    assert percentile([3.0, 1.0, 2.0], 50) == 2.0
    assert close(percentile([0.0, 10.0], 99), 9.9, 1e-9)


def test_median_hides_the_big_update():
    # a 40 s run: 750 heartbeats about 0.67 ms behind, one 976 ms behind after one big UPDATE
    s = lag_summary([0.67] * 750 + [976.0])
    assert s["n"] == 751 and s["p50"] == 0.67 and s["max"] == 976.0
    assert s["p99"] == 0.67      # even the p99 misses a single bad moment; the max doesn't


def test_lag_summary_drops_never_seen():
    s = lag_summary([1.0] * 500 + [10.0] * 4 + [float("inf")])
    assert s["n"] == 504 and s["p50"] == 1.0 and s["max"] == 10.0


def test_parse_lsn():
    assert parse_lsn("0/BDBA518") == 0xBDBA518          # the token 00_setup.py got back
    assert parse_lsn("0/9") < parse_lsn("0/10")          # hex, not text: as strings, "0/9" > "0/10"
    assert parse_lsn("1/0") > parse_lsn("0/FFFFFFFF")    # the high part counts first


def test_route_lsn():
    assert route_lsn("0/BDBA600", "0/BDBA518") == "replica1"   # replayed past the receipt
    assert route_lsn("0/BDBA518", "0/BDBA518") == "replica1"   # exactly there is enough
    assert route_lsn("0/BDBA400", "0/BDBA518") == "primary"    # behind: ask the primary
    assert route_lsn("0/BDBA400", None) == "replica1"          # no receipt yet


def test_route_window():
    assert route_window(1000.5, 1000.0, 1) == "primary"    # 0.5 ms after the write, 1 ms window
    assert route_window(1001.0, 1000.0, 1) == "replica1"   # the window is over
    assert route_window(1000.0, None, 50) == "replica1"    # this user never wrote
    assert route_window(1000.0, 1000.0, 0) == "replica1"   # a 0 ms window: always replica1


def test_route_monotonic():
    replay = {"replica1": "0/2000", "replica2": "0/1F00"}
    assert route_monotonic(replay, None, ["replica2", "replica1"]) == "replica2"      # first read: any copy
    assert route_monotonic(replay, "0/1F80", ["replica2", "replica1"]) == "replica1"  # replica2 is behind
    assert route_monotonic(replay, "0/1F00", ["replica2", "replica1"]) == "replica2"  # far enough
    assert route_monotonic(replay, "0/2100", ["replica1", "replica2"]) == "primary"   # both behind
