"""
Practice: how far behind a replica is, and which reads that breaks. 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): summarize lag without letting the median hide the bad
seconds, count violations with an interval, and route reads by log position (LSN) or by a timer.

Fill in the TODOs, then run the tests:
    pytest test_replica_practice.py        (locally)
or press "Run tests" on the chapter page.
"""
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."""
    # TODO
    raise NotImplementedError


def monotonic_violations(values):
    """One reader's reads in order: how many returned a value below the highest already seen."""
    # TODO
    raise NotImplementedError


def percentile(values, q):
    """Linear interpolation between closest ranks (numpy's default)."""
    # TODO
    raise NotImplementedError


def lag_summary(lags_ms):
    """{"n", "p50", "p99", "max"} of heartbeat lags in ms; infinite lags (never seen) are dropped."""
    # TODO
    raise NotImplementedError


def parse_lsn(text):
    """A Postgres LSN like '0/BDBA518': two hex numbers, the high and low 32 bits of a WAL position."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError


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."""
    # TODO
    raise NotImplementedError
