module MM1

using Random, Statistics

export mean_wait, confidence_interval

"""
    mean_wait(λ, μ, n; rng = Random.default_rng(), warmup = 1_000)

Simulate an M/M/1 queue (arrival rate λ, service rate μ) with Lindley's recursion and return
the mean waiting time in queue of `n` customers, after discarding the first `warmup` customers.
"""
function mean_wait(λ, μ, n; rng = Random.default_rng(), warmup = 1_000)
    0 < λ < μ || throw(ArgumentError("the queue is stable only if 0 < λ < μ"))
    w = 0.0                         # waiting time of the current customer
    total = 0.0
    for k in 1:(warmup + n)
        k > warmup && (total += w)
        service = randexp(rng) / μ  # exponential, mean 1/μ
        gap = randexp(rng) / λ      # time until the next arrival, mean 1/λ
        w = max(0.0, w + service - gap)
    end
    return total / n
end

"""
    confidence_interval(x; z = 1.96)

Mean of the replications `x` and half-width of its normal confidence interval.
"""
function confidence_interval(x; z = 1.96)
    return mean(x), z * std(x) / sqrt(length(x))
end

end
