"""
Practice: queues and capacity. Lab 03's queueing math (queueing.py, 02_real_vs_model.py,
05_capacity_plan.py): utilization, the one-worker knee, Erlang C for c workers sharing one
line, the p99 of that line, and a capacity plan from a p99 goal.

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

Notation: lam = arrival rate (requests a second), mu = what ONE worker finishes a second
(1 / mean work per request), c = workers sharing one first-come-first-served line.
Times are in seconds.
"""
import math


def utilization(lam, service_s, c=1):
    """How busy each worker is: the work arriving a second (lam x service_s), shared by c workers."""
    # TODO
    return 0.0


def mm1_mean(lam, mu):
    """One worker (M/M/1): mean time in the system (wait + work) = service time / (1 - utilization),
    which is the same as 1 / (mu - lam). Raise ValueError if lam >= mu: the line never clears."""
    # TODO
    return 0.0


def erlang_c(lam, mu, c):
    """The chance an arriving request finds all c workers busy and has to wait (Erlang C).
    Use the stable recurrence: a = lam / mu, B = 1, then for k = 1..c: B = a*B / (k + a*B);
    finally C = B / (1 - rho * (1 - B)) with rho = a / c."""
    # TODO
    return 0.0


def mmc_mean(lam, mu, c):
    """c workers sharing one line (M/M/c): mean time in the system = the mean wait,
    erlang_c / (c*mu - lam), plus the mean work, 1 / mu."""
    # TODO
    return 0.0


def mmc_survival(t, lam, mu, c):
    """P(time in the system > t) for M/M/c. Given: you don't need to change this.
    With chance 1 - C a request starts at once and only works; with chance C it waits an
    exponential time (rate r = c*mu - lam) first, then works."""
    C = erlang_c(lam, mu, c)
    r = c * mu - lam
    if abs(r - mu) < 1e-9 * mu:
        waited = (1 + mu * t) * math.exp(-mu * t)
    else:
        waited = (r * math.exp(-mu * t) - mu * math.exp(-r * t)) / (r - mu)
    return (1 - C) * math.exp(-mu * t) + C * waited


def bisect(f, lo, hi, iters=200):
    """Given: the x in [lo, hi] where an increasing f(x) crosses 0."""
    for _ in range(iters):
        mid = (lo + hi) / 2
        if f(mid) < 0:
            lo = mid
        else:
            hi = mid
    return (lo + hi) / 2


def mmc_p99(lam, mu, c):
    """The p99 of time in the system for M/M/c: the t where mmc_survival(t) = 0.01.
    Hint: start with hi = 1 / mu and double it until mmc_survival(hi) < 0.01, then bisect
    on 0.01 - mmc_survival(t), which grows with t."""
    # TODO
    return 0.0


def workers_needed(lam, mu, p99_limit_s, max_utilization=0.999):
    """The fewest workers that keep utilization <= max_utilization AND the M/M/c p99 within
    p99_limit_s. Start at ceil(lam / (mu * max_utilization)) and add workers until the p99 fits."""
    # TODO
    return 0


def max_rate_for_p99(mu, c, p99_limit_s):
    """The highest arrival rate at which c workers keep the M/M/c p99 within p99_limit_s.
    Bisect lam between 0 and just under c*mu on mmc_p99(lam) - p99_limit_s."""
    # TODO
    return 0.0
