"""
Practice: a load test with a known answer. Lab 02's arithmetic (lab_utils.py, loadgen.py,
hdr.py, 03_vs_k6.py): the right answer for a service that freezes 1 s of every 10, a
closed-loop, a paced and an open-loop tester against it, the clock started when a request
was sent or when it was due, and the checks on k6.

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

STALL_S, EVERY_S = 1.0, 10.0      # the service freezes for the first 1 s of every 10 s


def percentile(xs, q):
    """The q-th percentile (0-100), numpy's default ("linear") way. Given (Chapter 1's)."""
    s = sorted(xs)
    h = (len(s) - 1) * q / 100
    lo = math.floor(h)
    hi = min(lo + 1, len(s) - 1)
    return s[lo] + (h - lo) * (s[hi] - s[lo])


def known_answer(q, stall_s=STALL_S, every_s=EVERY_S):
    """Latency (seconds) at percentile q for the freezing service, ignoring the normal ~1 ms.
    A share stall_s / every_s of arrivals lands in a freeze, at a uniform point in it, and
    waits for the rest of it, so P(latency > x) = (stall_s - x) / every_s for 0 <= x <= stall_s.
    Below the frozen share, the answer is 0."""
    tail = 1 - q / 100
    frac = stall_s / every_s
    return max(0.0, stall_s - tail * every_s) if tail < frac else 0.0


def share_slower(x, stall_s=STALL_S, every_s=EVERY_S):
    """The known share of requests slower than x seconds (0 <= x)."""
    return max(0.0, stall_s - x) / every_s


def wait_at(t, stall_s=STALL_S, every_s=EVERY_S):
    """How long a request arriving at time t (seconds) waits for the freeze to end:
    the rest of the freeze if t falls in one, else 0. Freezes start at 0, 10, 20, ..."""
    phase = t % every_s
    return stall_s - phase if phase < stall_s else 0.0


def in_freeze(t, stall_s=STALL_S, every_s=EVERY_S):
    """True if time t falls inside a freeze."""
    return t % every_s < stall_s


def server_done(t, service_s):
    """When a request that reaches the server at t is answered: after any freeze, plus the
    normal service time. (This server never queues, so there's no backlog after a freeze.)"""
    return t + wait_at(t) + service_s


def closed_loop(workers, duration, service_s=0.001):
    """Closed loop: each worker sends at time 0, and sends its next request the moment the last
    reply comes back, until `duration`. Returns a list of (sent, done) pairs, one per request.
    There's no schedule, so there's nothing to be late for: latency is done - sent."""
    out = []
    for _ in range(workers):
        t = 0.0
        while t < duration:
            done = server_done(t, service_s)
            out.append((t, done))
            t = done
    return out


def paced_loop(workers, rate, duration, service_s=0.001):
    """Paced: `workers` workers share a target of `rate` requests a second, so each has a schedule
    of one request every workers / rate seconds, starting at 0. A worker can't send while it waits
    for a reply, so after a freeze it sends late, then catches up. Returns (due, sent, done)
    triples: sent = max(due, when the worker is free)."""
    interval = workers / rate
    out = []
    for _ in range(workers):
        free, k = 0.0, 0
        while k * interval < duration:
            due = k * interval
            sent = max(due, free)
            done = server_done(sent, service_s)
            out.append((due, sent, done))
            free, k = done, k + 1
    return out


def open_loop(rate, duration, service_s=0.001):
    """Open loop: one request due every 1 / rate seconds from 0, each sent on time whatever is
    still waiting (like users who don't know each other). Returns (due, sent, done) triples."""
    n = int(round(rate * duration))
    out = []
    for k in range(n):
        due = k / rate
        out.append((due, due, server_done(due, service_s)))
    return out


def latencies(records, start="due"):
    """Latency of each record: done minus its start. start="sent" uses the sent time, "due" the due
    time. Records are (sent, done) pairs (closed loop: start must be "sent") or (due, sent, done)."""
    if len(records[0]) == 2:
        if start != "sent":
            raise ValueError("a closed loop has no due times")
        return [d - s for s, d in records]
    i = 0 if start == "due" else 1
    return [r[2] - r[i] for r in records]


def corrected(latencies_us, interval_us):
    """HdrHistogram's after-the-fact correction for a client that meant to send every interval_us:
    for each latency v, keep v and add v - interval, v - 2*interval, ... while it stays >= interval
    (the requests the stuck client should have sent). Integers in microseconds."""
    out = []
    for v in latencies_us:
        out.append(v)
        missing = v - interval_us
        while missing >= interval_us:
            out.append(missing)
            missing -= interval_us
    return out


def vus_needed(rate, worst_latency_s):
    """Virtual users k6 needs so it never runs out: one per request in flight, at least
    rate x the worst latency you want to see (Little's law). Round up."""
    return math.ceil(rate * worst_latency_s - 1e-9)


def can_trust(dropped):
    """k6 counts requests it was too busy to send (dropped_iterations). Any above zero means
    its latency report left out requests, so don't trust it."""
    return dropped == 0
