"""
Solution: Lab 09's logic for scripts 01_lag.py, 03_read_your_writes.py and 04_monotonic_reads.py
(consistency.py, percentiles.py and the read routing in service/app.py).
"""
import math


def wilson(k, n, z=1.96):
    """Wilson score interval for k violations out of n reads, as in the lab's consistency.py."""
    if n <= 0:
        raise ValueError("n must be positive")
    if not 0 <= k <= n:
        raise ValueError("need 0 <= k <= n")
    p = k / n
    denom = 1 + z * z / n
    centre = (p + z * z / (2 * n)) / denom
    half = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denom
    return max(0.0, centre - half), min(1.0, centre + half)


def monotonic_violations(values):
    """One reader's reads in order: how many returned a value below the highest already seen."""
    best = -math.inf
    count, worst = 0, 0
    for v in values:
        if v < best:
            count += 1
            worst = max(worst, best - v)
        else:
            best = v
    return {"reads": len(values), "violations": count, "worst_step_back": worst}


def percentile(values, q):
    """Linear interpolation between closest ranks (numpy's default)."""
    x = sorted(values)
    if not x:
        raise ValueError("percentile of an empty sample")
    h = (len(x) - 1) * q / 100
    lo, hi = math.floor(h), math.ceil(h)
    return x[lo] + (h - lo) * (x[hi] - x[lo])


def lag_summary(lags_ms):
    """{"n", "p50", "p99", "max"} of heartbeat lags in ms; infinite lags (never seen) are dropped."""
    x = [v for v in lags_ms if math.isfinite(v)]
    if not x:
        raise ValueError("no finite lag samples")
    return {"n": len(x), "p50": percentile(x, 50), "p99": percentile(x, 99), "max": max(x)}


def parse_lsn(text):
    """A Postgres LSN like '0/BDBA518': two hex numbers, the high and low 32 bits of a WAL position."""
    hi, lo = text.split("/")
    return (int(hi, 16) << 32) | int(lo, 16)


def route_lsn(replay_lsn, min_lsn):
    """The lab's `lsn` policy for bookings: replica1 if it has replayed at least `min_lsn` (the
    receipt from the user's last write), else the primary. No receipt: replica1."""
    if not min_lsn:
        return "replica1"
    return "replica1" if parse_lsn(replay_lsn) >= parse_lsn(min_lsn) else "primary"


def route_window(now_ms, last_write_ms, window_ms):
    """The lab's `sticky` policy: the primary for `window_ms` after this user's last write
    (None: never wrote), else replica1."""
    if last_write_ms is not None and now_ms - last_write_ms < window_ms:
        return "primary"
    return "replica1"


def route_monotonic(replay, seen_lsn, order):
    """The lab's `lsn` policy for the counter: try the replicas in `order` (names in `replay`, a
    dict of name -> replay LSN text) and take the first that has replayed at least `seen_lsn`
    (the position of the last answer this reader got; None: any will do), else the primary."""
    for name in order:
        if not seen_lsn or parse_lsn(replay[name]) >= parse_lsn(seen_lsn):
            return name
    return "primary"
