"""Tests on Lab 08's recorded runs (31 October 2026, Apple M4 Max, Docker Desktop with 16 vCPU,
Postgres 18.6 on half a CPU, Redis 7.4.2): 01_hit_ratio.py (100,000 keys, Zipf skew), 02_cache_speedup.py
(no cache vs Redis cache-aside) and 04_stampede.py (one hot key; 5,000 keys expiring together).
Run: pytest test_cache_practice.py"""
import math
import random

from cache_practice import (db_reads_per_s, half_second_steps, jittered_ttl, lfu_hits, lru_hits,
                            recomputes_per_expiry, top_share, xfetch_should_refresh)

# 04_stampede.py, database reads a second in 100 ms bins from 3 s before the mass expiry (round 1)
NO_JITTER = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 640, 4000,
             3280, 3620, 3150, 3080, 2800, 2850, 2620, 2540, 2770, 2540, 2240, 1410, 1730, 1810, 1600, 1840,
             1610, 1740, 1400, 550, 860, 1360, 1380, 1190, 1060, 890, 560, 170, 140, 1180, 1020, 700, 930, 570,
             190, 0, 130, 0, 0, 720, 710, 690, 490, 360, 150, 0, 50, 0, 0, 0, 0, 60, 30, 440, 320, 230, 140, 140,
             170]
WITH_JITTER = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 120, 210, 180, 430, 380, 430, 410, 550, 520, 560, 710, 850, 710, 860,
               850, 850, 1010, 1040, 870, 1110, 1040, 1210, 1060, 990, 1010, 1090, 1110, 1160, 1070, 1010, 1240,
               1160, 1190, 1180, 1110, 1260, 1190, 1210, 1340, 1100, 1220, 1090, 970, 780, 710, 750, 720, 430, 650,
               500, 550, 560, 400, 430, 430, 240, 320, 290, 290, 190, 280, 310, 200, 190, 110, 250, 80, 130, 130,
               100, 100, 80, 110, 80, 100, 70, 90, 70, 30, 50]


def test_top_share():
    # the "best possible" column: the top 1% of 100,000 items
    assert abs(top_share(100_000, 0.0, 1_000) - 0.010) < 1e-9  # every item equally popular
    assert abs(top_share(100_000, 0.6, 1_000) - 0.1519) < 0.0005
    assert abs(top_share(100_000, 0.9, 1_000) - 0.4742) < 0.0005  # the 47% in the video
    assert abs(top_share(100_000, 1.2, 1_000) - 0.8516) < 0.0005
    assert abs(top_share(100_000, 0.9, 25_000) - 0.8155) < 0.0005


def test_lru_hits_small():
    # capacity 2: a, b fill it; a hits; c evicts b (least recently used); b misses; a was evicted by b
    assert lru_hits(["a", "b", "a", "c", "b", "a"], 2) == 1
    assert lru_hits(["a", "a", "a"], 1) == 2
    assert lru_hits(["a", "b", "a", "b"], 2, warmup=2) == 2  # the first 2 requests aren't counted


def test_lfu_keeps_the_popular_key():
    # "a" is popular; a burst of one-off keys passes through a cache of 2
    stream = ["a", "a", "a"] + ["x1", "x2", "x3", "x4"] + ["a"]
    assert lru_hits(stream, 2) == 2  # the burst pushed "a" out: only its first two repeats hit
    assert lfu_hits(stream, 2) == 3  # LFU kept it: the last request hits too
    # ties: among keys with the lowest count, the least recently used goes
    assert lfu_hits(["a", "b", "c", "b", "a"], 2) == 1  # c evicts a (count 1, older than b); b hits; a misses


def test_lfu_beats_lru_on_skew():
    # a smaller version of 01_hit_ratio.py: 10,000 items, s = 0.9, a cache of 1%
    n, s = 10_000, 0.9
    rng = random.Random(1)
    weights = [1 / r ** s for r in range(1, n + 1)]
    stream = rng.choices(range(n), weights=weights, k=60_000)
    warm = 20_000
    lru = lru_hits(stream, 100, warmup=warm) / (len(stream) - warm)
    lfu = lfu_hits(stream, 100, warmup=warm) / (len(stream) - warm)
    best = top_share(n, s, 100)
    assert lru < lfu < best + 0.01
    assert lfu - lru > 0.05  # the lab's real Redis: 30.3% vs 43.4% at 100,000 items


def test_db_reads_per_s():
    # Redis cache-aside at 3,000 a second: 91.5% from the cache; the app's log counted 257 reads a second
    assert abs(db_reads_per_s(3_015, 0.915) - 257) < 3
    assert db_reads_per_s(1_000, 0.0) == 1_000
    # a 95% hit ratio, then the cache disappears: 20 times the database reads
    assert abs(db_reads_per_s(5_000, 0.0) / db_reads_per_s(5_000, 0.95) - 20) < 1e-9


def test_half_second_steps():
    steps = half_second_steps(NO_JITTER)
    assert len(steps) == 18
    assert [round(x) for x in steps[:8]] == [0, 0, 0, 0, 0, 128, 3426, 2716]  # zero to 3,426 in one step
    assert max(NO_JITTER) == 4_000  # the 100 ms peak
    assert round(max(half_second_steps(WITH_JITTER))) == 1_220  # jitter: no half-second above 1,220
    assert max(WITH_JITTER) == 1_340


def test_jittered_ttl():
    assert jittered_ttl(10_000, 0.2, 0.0) == 8_000
    assert jittered_ttl(10_000, 0.2, 1.0) == 12_000
    assert jittered_ttl(10_000, 0.2, 0.5) == 10_000
    assert jittered_ttl(10_000, 0.0, 0.9) == 10_000
    assert jittered_ttl(1, 0.5, 0.0) == 1  # never below 1 ms
    for bad in (-0.1, 1.0):
        try:
            jittered_ttl(10_000, bad, 0.5)
        except ValueError:
            pass
        else:
            raise AssertionError("jitter outside [0, 1) must raise ValueError")


def test_xfetch():
    # the last recompute took 51 ms; the copy expires at t = 3.0 s
    assert xfetch_should_refresh(0.051, 3.0, 3.0, 1.0, 0.5)  # at or past expiry: always
    assert not xfetch_should_refresh(0.051, 3.0, 2.0, 1.0, 0.5)  # a second early: no
    # 20 ms early: refresh when -ln(u) >= 20/51, i.e. u <= exp(-20/51)
    edge = math.exp(-0.020 / 0.051)
    assert xfetch_should_refresh(0.051, 3.0, 2.98, 1.0, edge * 0.99)
    assert not xfetch_should_refresh(0.051, 3.0, 2.98, 1.0, edge * 1.01)
    # a slower recompute makes early refreshes likelier at the same moment
    assert xfetch_should_refresh(0.300, 3.0, 2.98, 1.0, 0.5)


def test_recomputes_per_expiry():
    # 500 requests a second for 20 s, copy lasts 3 s: 7 expiries
    assert recomputes_per_expiry(91, 20, 3) == 13.0  # no protection, round 1
    assert abs(recomputes_per_expiry(230, 20, 3) - 32.857) < 0.001  # round 2
    assert recomputes_per_expiry(7, 20, 3) == 1.0  # the lock
    assert abs(recomputes_per_expiry(27, 20, 3) - 3.857) < 0.001  # early refresh
    assert recomputes_per_expiry(5, 2, 3) == 5  # shorter than one TTL: at least one expiry
