"""
Practice: how long readers see an old value, and how to keep it short. Lab 08's logic for
scripts 03_staleness.py and 05_cdn.py (staleness.py and the guarded fill in service/cache_logic.py):
measure stale windows from a probe's reads and writes, write a cache fill that refuses old
versions, and work out what an edge cache sends to the origin.

Fill in the TODOs, then run the tests:
    pytest test_stale_practice.py        (locally)
or press "Run tests" on the chapter page.
"""
import math


def stale_windows(reads, writes):
    """One stale window per write, in seconds, as in the lab's staleness.py.

    reads: list of (sent, version): when a read was sent and which version it got.
    writes: list of (acked, version): when a write was confirmed and which version it made.
    A read is stale for a write if it was sent at or after the write's confirmation and got an
    older version. The window is the last such read's send time minus the confirmation (0.0 if
    there is none)."""
    out = []
    for acked, v in writes:
        stale = [sent for sent, got in reads if sent >= acked and got < v]
        out.append(max(stale) - acked if stale else 0.0)
    return out


def percentile(values, q):
    """The q-th percentile (0-100) with linear interpolation, numpy's default (the one the lab
    reports): sort, then take position (n - 1) * q / 100 and interpolate between neighbours."""
    if not values:
        raise ValueError("percentile of an empty sample")
    x = sorted(values)
    h = (len(x) - 1) * q / 100
    lo, hi = math.floor(h), math.ceil(h)
    return x[lo] + (h - lo) * (x[hi] - x[lo])


def summarize(windows):
    """{"writes", "writes_with_stale", "p50_ms", "max_ms"} over all writes, zeros included,
    from windows in seconds."""
    return {"writes": len(windows), "writes_with_stale": sum(1 for w in windows if w > 0),
            "p50_ms": percentile(windows, 50) * 1000, "max_ms": max(windows) * 1000}


def read_cached(board, key):
    """A cache-aside read of the board (a dict standing in for Redis): the cached value, or None
    on a miss. A tombstone ({"min_version": v}) counts as a miss."""
    v = board.get(key)
    if v is None or "min_version" in v:
        return None
    return v


def fill(board, key, value, guarded):
    """Copy a value read from the database ({"version": v, ...}) up to the board.

    Plain: always write it. Guarded (the lab's GUARDED_SET Lua script): look at what's there; if
    it has a "min_version" (a tombstone) or else a "version", and the new value's version is
    older than that, refuse. Return True if written, False if refused."""
    if guarded:
        cur = board.get(key)
        if cur is not None:
            newest = cur.get("min_version", cur.get("version"))
            if newest is not None and value["version"] < newest:
                return False
    board[key] = value
    return True


def origin_share(full, not_modified, requests):
    """The share of requests that reached the origin: full pages (200s) plus 304s."""
    return (full + not_modified) / requests


def revalidation_share(full, not_modified):
    """Of the requests that reached the origin, the share answered 304 ("unchanged", no body)."""
    total = full + not_modified
    return not_modified / total if total else 0.0


def worst_case_stale_s(max_age_s, purge_arrived, grace_s=0):
    """How long an edge can serve the old page after a change: about nothing if its purge arrived,
    otherwise the rest of its timer, at most max_age_s, plus any window in which it may serve
    expired copies (stale-while-revalidate or the CDN's own grace)."""
    return 0 if purge_arrived else max_age_s + grace_s
