"""
Practice: scaling and bottlenecks. Lab 03's arithmetic for scripts 03_scaling.py and
04_bottleneck.py (queueing.usl, capacity.stop_paying_off, and the pipeline math): the most a
locked row allows, the Universal Scalability Law, where one more worker stops paying off, and
how to find the stage that sets a pipeline's pace without changing anything.

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


def speedups(throughputs):
    """Each throughput as a multiple of the first one (the one-worker throughput)."""
    return [x / throughputs[0] for x in throughputs]


def lock_ceiling(held_ms):
    """The most requests a second that can pass through a lock held `held_ms` per request.
    Only one request holds it at a time, so at most 1 s ÷ held time."""
    return 1000.0 / held_ms


def usl(n, lam1, sigma, kappa):
    """Universal Scalability Law: throughput with n workers,
    X(n) = lam1 * n / (1 + sigma * (n - 1) + kappa * n * (n - 1))."""
    return lam1 * n / (1 + sigma * (n - 1) + kappa * n * (n - 1))


def usl_peak(sigma, kappa):
    """The worker count with the highest USL throughput: sqrt((1 - sigma) / kappa).
    With kappa == 0 throughput never falls: return math.inf."""
    if kappa <= 0:
        return math.inf
    return math.sqrt((1 - sigma) / kappa)


def stop_paying_off(lam1, sigma, kappa, gain=0.05, n_max=256):
    """The first worker count n where going to n + 1 workers adds less than `gain` times one
    worker's throughput (lam1), by the USL. Return n_max if it never happens below n_max."""
    for n in range(1, n_max):
        if usl(n + 1, lam1, sigma, kappa) - usl(n, lam1, sigma, kappa) < gain * lam1:
            return n
    return n_max


def stage_capacity(workers, service_ms):
    """Requests a second a stage can finish when it's never idle: workers ÷ time per request."""
    return workers * 1000.0 / service_ms


def utilization(throughput, service_ms, workers):
    """How busy a stage is: throughput x time per request ÷ workers (1.0 = busy all the time)."""
    return throughput * service_ms / 1000.0 / workers


def bottleneck(stages, throughput):
    """`stages` maps a stage name to (workers, service_ms). Return the pipeline's predicted
    throughput (the smallest stage capacity) and the name of the busiest stage at the measured
    `throughput`, as a tuple (predicted, name)."""
    predicted = min(stage_capacity(w, ms) for w, ms in stages.values())
    name = max(stages, key=lambda s: utilization(throughput, stages[s][1], stages[s][0]))
    return predicted, name
