"""Tests on Lab 06's recorded runs (28 October 2026, Apple M4 Max, Docker Desktop with 16 vCPU):
03_idempotency.py (1,000 payments retried after a 150 ms timeout, with and without an
idempotency key) and 04_deadlines.py (client -> gateway -> orders -> inventory with 4 workers,
at 10 and 40 checkouts a second, 30 s each). The hashes come from the lab's own idempotency.py.
Run: pytest test_retry_practice.py"""
from retry_practice import (busy_share, child_timeout_ms, cut_off_seconds, extra_charges, grill_load,
                            handle, hop_budgets, request_hash, wasted_share)


def test_extra_charges():
    assert extra_charges(1466, 1000) == 466  # slow after saving, no key: one per timeout (466)
    assert extra_charges(1382, 1000) == 382  # slow before saving, no key: 382 from 389 timeouts
    assert extra_charges(1000, 1000) == 0  # with a key, both cases


def test_request_hash():
    body = {"customer_id": 1, "amount_cents": 500, "client_ref": "dup-0"}
    h = request_hash("POST", "/api/payments", body)
    assert h == "513717ad9469d99eaeec27e98e43ba99de65510f54aff6b73059bb31b3c839d8"  # the lab's hash
    reordered = {"client_ref": "dup-0", "amount_cents": 500, "customer_id": 1}
    assert request_hash("post", "/api/payments", reordered) == h  # key order and case don't matter
    other = dict(body, amount_cents=999)
    assert request_hash("POST", "/api/payments", other) == "f8b139a0772f50bc96ad85e83ddc8713a54eb15f28de79928036c600e5c1f980"


def _payments():
    charges = []

    def pay(amount):
        def do_payment():
            charges.append(amount)
            return {"payment_id": len(charges), "amount_cents": amount}
        return do_payment
    return charges, pay


def test_no_key_charges_every_attempt():
    charges, pay = _payments()
    store = {}
    h = request_hash("POST", "/api/payments", {"amount_cents": 500})
    handle(store, None, h, pay(500))  # the answer was slow: the app gave up and retried
    status, body, replayed = handle(store, None, h, pay(500))
    assert (status, replayed) == (200, False)
    assert len(charges) == 2  # charged twice


def test_key_replays_the_saved_answer():
    charges, pay = _payments()
    store = {}
    h = request_hash("POST", "/api/payments", {"amount_cents": 500})
    first = handle(store, "k1", h, pay(500))  # saved, but the app never saw the answer
    second = handle(store, "k1", h, pay(500))  # the retry carries the same key
    assert first == (200, {"payment_id": 1, "amount_cents": 500}, False)
    assert second == (200, {"payment_id": 1, "amount_cents": 500}, True)  # the same payment back
    assert len(charges) == 1


def test_key_reused_for_a_different_request_is_refused():
    charges, pay = _payments()
    store = {}
    handle(store, "k2", request_hash("POST", "/api/payments", {"amount_cents": 500}), pay(500))
    status, body, replayed = handle(store, "k2", request_hash("POST", "/api/payments", {"amount_cents": 999}), pay(999))
    assert status == 422 and not replayed and "error" in body  # the lab: 50 of 50 refused
    assert charges == [500]


def test_two_keys_are_two_payments():
    charges, pay = _payments()
    store = {}
    h = request_hash("POST", "/api/payments", {"amount_cents": 500})
    handle(store, "click-1", h, pay(500))
    handle(store, "click-2", h, pay(500))  # a second click on Pay is a second payment
    assert len(charges) == 2


def test_child_timeout():
    assert child_timeout_ms(298) == 293  # deadline.py: 300 ms, 2 ms spent, 5 ms margin
    assert child_timeout_ms(3) == 0  # never below zero: the next service refuses at once
    assert child_timeout_ms(100, margin_ms=0) == 100


def test_hop_budgets():
    assert hop_budgets(300, [2, 3]) == [300, 293, 285]  # gateway, orders, inventory
    assert hop_budgets(300, []) == [300]
    assert hop_budgets(10, [4, 4]) == [10, 1, 0]


def test_grill_load():
    # 10% of checkouts need 1 s of inventory work, the rest 20 ms, on 4 workers
    assert round(grill_load(40, 0.1, 1.0, 0.02, 4), 2) == 1.18  # more than the 4 workers have
    assert round(grill_load(40, 0.1, 1.0, 0, 4), 2) == 1.0  # the slow ones alone fill all 4
    assert round(grill_load(10, 0.1, 1.0, 0.02, 4), 3) == 0.295
    assert grill_load(40, 0.1, 0.245, 0.02, 4) < 0.5  # cut off at the deadline


def test_busy_and_wasted():
    # 10 req/s without the deadline: every normal checkout in time, most of the work for nobody
    assert round(busy_share(29.76, 30, 4), 2) == 0.25
    assert round(wasted_share(29.76, 18.08), 2) == 0.61
    # 40 req/s without: 99% for nobody; with the deadline passed along: half the work, ~none wasted
    assert round(wasted_share(103.25, 101.95), 2) == 0.99
    assert round(busy_share(50.14, 30, 4), 2) == 0.42
    assert wasted_share(50.14, 0.06) < 0.01
    assert round(50.14 / 103.25, 2) == 0.49


def test_cut_off_seconds():
    # 10 req/s without: 288 normal x 20 ms + 24 slow x 1 s is exactly the work measured
    assert round(cut_off_seconds(29.76, 288, 0.02, 24), 3) == 1.0
    # with the deadline: each slow checkout got about a quarter of a second
    assert round(cut_off_seconds(50.14, 1084, 0.02, 116), 3) == 0.245
    assert round(cut_off_seconds(11.32, 288, 0.02, 24), 3) == 0.232
