"""
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."""
    # TODO
    return 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)."""
    # TODO
    return 0.0


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, ..."""
    # TODO
    return 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."""
    # TODO
    return []


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)."""
    # TODO
    return []


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."""
    # TODO
    return []


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)."""
    # TODO
    return []


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."""
    # TODO
    return []


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."""
    # TODO
    return 0


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."""
    # TODO
    return True
