"""Reproduce a stale cache fill and reject it with a version floor.

Run with Python 3.10 or newer: python3 07-caching-strategies-invalidation.py
This standard-library lab schedules interleavings explicitly. No Redis required.
"""

from dataclasses import dataclass


@dataclass(frozen=True)
class Record:
    version: int
    body: str


@dataclass(frozen=True)
class Entry:
    record: Record
    expires_at: int


class Cache:
    def __init__(self) -> None:
        self.entries: dict[str, Entry] = {}
        self.minimum_versions: dict[str, int] = {}

    def get(self, key: str, now: int) -> Record | None:
        entry = self.entries.get(key)
        if entry is None:
            return None
        if now >= entry.expires_at:
            del self.entries[key]
            return None
        return entry.record

    def invalidate(self, key: str, version: int) -> None:
        """Retain the highest observed invalidation, even for an empty key."""
        floor = max(version, self.minimum_versions.get(key, 0))
        self.minimum_versions[key] = floor
        entry = self.entries.get(key)
        if entry is not None and entry.record.version < floor:
            del self.entries[key]

    def fill(self, key: str, record: Record, now: int, ttl: int) -> bool:
        """Atomically compare and store in this single-threaded simulation."""
        if ttl <= 0:
            raise ValueError("ttl must be positive")
        floor = self.minimum_versions.get(key, 0)
        current = self.get(key, now)
        if current is not None:
            floor = max(floor, current.version)
        if record.version < floor:
            return False
        self.entries[key] = Entry(record, now + ttl)
        return True


def backend_reads_for_burst(count: int, *, coalesce: bool) -> int:
    """All requests arrive together for one absent key and one cache scope."""
    return int(count > 0) if coalesce else count


def main() -> None:
    key = "schedule:stage-2"
    before = Record(7, "Studio A")
    after = Record(8, "Studio B")

    # A misses at t=0 and starts reading v7. B commits v8 at t=1 and
    # invalidates the empty key. A's delayed result arrives at t=2.
    naive = {}
    naive.pop(key, None)
    naive[key] = Entry(before, expires_at=62)
    assert naive[key].record.version == 7

    guarded = Cache()
    guarded.invalidate(key, after.version)
    assert not guarded.fill(key, before, now=2, ttl=60)
    assert guarded.get(key, now=2) is None
    assert guarded.fill(key, after, now=3, ttl=60)
    guarded.invalidate(key, before.version)  # Delayed old invalidation.
    assert guarded.get(key, now=62) == after
    assert guarded.get(key, now=63) is None
    assert not guarded.fill(key, before, now=64, ttl=60)
    assert backend_reads_for_burst(100, coalesce=False) == 100
    assert backend_reads_for_burst(100, coalesce=True) == 1
    print("Stale fill reproduced and rejected. Expiry and burst checks passed.")

    # Try it yourself:
    # 1. Omit invalidation to model a delayed or lost event. What remains stale?
    # 2. Simulate losing the minimum version during a cache restart.
    # 3. Split the burst across four independent per-process coalescers.


if __name__ == "__main__":
    main()
