"""Tests on Lab 10's logic and recorded runs (2 November 2026, Apple M4 Max, Docker Desktop with
16 vCPU): 03_resharding.py (adding s5 to four Postgres shards under 1,000 reads and 200 writes a
second) and 04_ids.py (Snowflake IDs on a controlled clock). The ring numbers come from the lab's
partitioner.py over the same users; the ID counts from its snowflake.py.
Run: pytest test_reshard_practice.py"""
from reshard_practice import (FakeClock, NaiveSnowflake, Snowflake, ClockWentBackwards, add, build_ring,
                              check_balances, expected_misses, modulo_shard, move_row, moved_users, read,
                              shard_for)

OLD = ["s1", "s2", "s3", "s4"]
NEW = OLD + ["s5"]


def rings():
    """The lab's two rings: 64 marks per shard, before and after s5 joins."""
    return build_ring(OLD, 64), build_ring(NEW, 64)


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


def test_ring_has_a_mark_per_vnode_and_is_sorted():
    OLD_RING, NEW_RING = rings()
    assert len(OLD_RING) == 256 and len(NEW_RING) == 320
    assert OLD_RING == sorted(OLD_RING)


def test_shard_for_matches_the_lab():
    OLD_RING, NEW_RING = rings()
    # users 1-8 on the lab's rings (partitioner.py, 64 marks per shard)
    assert [shard_for(OLD_RING, u) for u in range(1, 9)] == ["s2", "s2", "s4", "s4", "s2", "s3", "s3", "s4"]
    assert shard_for(NEW_RING, 4) == "s5" and shard_for(NEW_RING, 3) == "s4"


def test_only_the_new_shards_stretches_move():
    OLD_RING, NEW_RING = rings()
    moved = moved_users(OLD_RING, NEW_RING, range(1, 20_001))
    # the lab's partitioner on users 1-20,000: 3,529 move, every one to s5, from every old shard
    assert {s: len(v) for s, v in moved.items()} == {"s1": 327, "s2": 1736, "s3": 621, "s4": 845}
    assert all(shard_for(NEW_RING, u) == "s5" for v in moved.values() for u in v)


def test_the_remainder_moves_four_in_five():
    users = range(1, 20_001)
    moved = sum(modulo_shard(u, OLD) != modulo_shard(u, NEW) for u in users)
    assert moved == 15_977                                  # 79.9%; the ring moved 3,529
    assert modulo_shard(7, OLD) in OLD


def test_expected_misses_is_the_readme_estimate():
    # 35,775 of 200,000 users (17.9%) missing at the switch, falling evenly to 0 over a 12.76 s copy
    share = 35_775 / 200_000
    assert round(expected_misses(1000, 12.761314, share)) == 1141   # recorded: 1,044 reads failed
    assert round(expected_misses(200, 12.761314, share)) == 228     # recorded: 202 writes failed
    assert close(expected_misses(1000, 10, 0.2), 1000.0)


def store_with(uid, shard, balance):
    s = {name: {} for name in NEW}
    s[shard][uid] = balance
    return s


def test_switch_then_copy_fails_a_moved_user():
    OLD_RING, NEW_RING = rings()
    store = store_with(4, "s4", 100)                        # user 4 moves s4 -> s5, not copied yet
    assert read(store, 4, NEW_RING) is None                 # 404: "no such user here"
    assert add(store, 4, 1, NEW_RING) is False              # refused, and the client is told so
    assert store["s4"][4] == 100                            # nothing lost


def test_dual_ring_reads_the_old_shard():
    OLD_RING, NEW_RING = rings()
    store = store_with(4, "s4", 100)
    assert read(store, 4, NEW_RING, OLD_RING) == 100
    assert store["s4"] == {4: 100} and store["s5"] == {}    # a read moves nothing


def test_dual_ring_moves_the_row_on_a_write():
    OLD_RING, NEW_RING = rings()
    store = store_with(4, "s4", 100)
    assert add(store, 4, 1, NEW_RING, OLD_RING) is True
    assert store["s5"] == {4: 101} and store["s4"] == {}    # writes only ever land on the new shard


def test_move_row_does_nothing_if_the_copy_job_got_there_first():
    # the split second: the copy job put user 4 on s5 between the write's miss and the move
    store = store_with(4, "s4", 100)
    store["s5"][4] = 100
    move_row(store, 4, "s4", "s5")
    assert store["s5"][4] == 100 and 4 not in store["s4"]   # not 200: "do nothing", not "add"


def test_balance_check_finds_lost_doubled_missing_and_duplicated_rows():
    initial = {1: 10, 2: 20, 3: 30, 4: 40, 5: 50}
    acked = {1: 2, 2: 1}
    store = {"s1": {1: 12, 2: 20, 4: 40}, "s5": {4: 40, 5: 100}}
    out = check_balances(store, initial, acked)
    # 1 fine; 2 lost its acknowledged +1; 3 missing; 4 on two shards (and over); 5 doubled
    assert out == {"missing": 1, "on_two_shards": 1, "short": 1, "over": 2}


def test_balance_check_after_a_clean_move():
    initial = {1: 10, 2: 20}
    store = {"s1": {1: 11}, "s5": {2: 20}}
    assert check_balances(store, initial, {1: 1}) == {"missing": 0, "on_two_shards": 0, "short": 0, "over": 0}


def run(gen_cls, step, n=60_000, every=20_000, per_ms=20, **kw):
    clock = FakeClock(reads_per_ms=per_ms)
    gen = gen_cls(3, clock, **kw)
    ids = []
    for i in range(n):
        if i and i % every == 0:
            clock.jump(-step)
        ids.append(gen.next_id())
    return ids, gen


def test_naive_generator_repeats_the_milliseconds_it_reenters():
    # 20 IDs a millisecond x the step x 2 jumps (the lab: x 9 jumps -> 180 / 900 / 9,000)
    for step, dup in ((1, 40), (5, 200), (50, 2000)):
        ids, _ = run(NaiveSnowflake, step)
        assert len(ids) - len(set(ids)) == dup


def test_fixed_generator_waits_instead():
    for step, waited in ((5, 9), (50, 99)):                 # 5 + 4, 50 + 49: as the lab's 37 and 442 for 9 jumps
        ids, gen = run(Snowflake, step, max_wait_ms=100)
        assert len(set(ids)) == len(ids) and ids == sorted(ids)
        assert gen.waited_ms == waited


def test_fixed_generator_refuses_a_big_step_back():
    clock = FakeClock()
    gen = Snowflake(1, clock, max_wait_ms=50)
    gen.next_id()
    clock.jump(-1000)
    try:
        gen.next_id()
    except ClockWentBackwards:
        return
    assert False, "expected ClockWentBackwards"


def test_layout_and_counter():
    clock = FakeClock(reads_per_ms=1_000_000)               # the clock stands still
    gen = Snowflake(513, clock)
    a, b = gen.next_id(), gen.next_id()
    assert b == a + 1                                       # same millisecond: the counter goes up by one
    assert (b >> 12) & 1023 == 513 and b >> 22 == clock.ms  # 12 bits of counter, 10 of machine, then time
