"""
Practice: retries, idempotency keys and deadlines. Lab 06's logic for scripts 03_idempotency.py
and 04_deadlines.py (idempotency.py and deadline.py): count the extra charges, make a retry safe
with an idempotency key, pass a deadline along a chain of services, and check how busy the last
service gets when nobody stops it.

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


def extra_charges(charges_stored, payments):
    """Charges beyond one per payment the customer meant to make."""
    return charges_stored - payments


def request_hash(method, path, body):
    """A fingerprint of one request, as in the lab's idempotency.py: sha256 of
    "<METHOD> <path>\\n<body as JSON with sorted keys and no spaces>", as hex.
    The same request gives the same hash whatever the key order in the body."""
    canonical = json.dumps(body, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(f"{method.upper()} {path}\n{canonical}".encode()).hexdigest()


def handle(store, key, req_hash, do_payment):
    """Run one attempt of a payment; return (status, body, replayed).

    store: a dict, key -> (req_hash, saved body). It stands in for the idempotency_keys table.
    key: the idempotency key sent by the client, or None.
    do_payment(): makes the charge and returns the answer body.

    - No key: every attempt runs: (200, do_payment(), False).
    - Key already saved with a different req_hash: refuse, (422, {"error": ...}, False).
    - Key already saved with the same req_hash: a retry, send back the saved body, (200, body, True).
    - Otherwise: run do_payment(), save (req_hash, body) under the key, (200, body, False).
    (In the lab the key and the payment are saved in one database transaction; a dict in one
    thread doesn't need that.)"""
    if key is None:
        return 200, do_payment(), False
    if key in store:
        saved_hash, saved_body = store[key]
        if saved_hash != req_hash:
            return 422, {"error": "Idempotency-Key reused with a different request"}, False
        return 200, saved_body, True
    body = do_payment()
    store[key] = (req_hash, body)
    return 200, body, False


def child_timeout_ms(remaining_ms, margin_ms=5):
    """What a service gives the next one: the time it has left minus a margin for its own work
    and the response, never below 0."""
    return max(0.0, remaining_ms - margin_ms)


def hop_budgets(client_ms, spent_ms, margin_ms=5):
    """The time limit each service in a chain receives (the x-timeout-ms header).
    client_ms: what the client gives the first service. spent_ms[i]: how long service i works
    before calling service i + 1. Return a list with one budget per service: len(spent_ms) + 1."""
    budgets = [float(client_ms)]
    for spent in spent_ms:
        budgets.append(child_timeout_ms(budgets[-1] - spent, margin_ms))
    return budgets


def grill_load(rate, slow_share, slow_s, quick_s, workers):
    """How busy a pool of workers is, on average: rate a second x the average work per request
    (slow_share of them take slow_s, the rest quick_s) ÷ workers. Above 1.0 the line never clears."""
    return rate * (slow_share * slow_s + (1 - slow_share) * quick_s) / workers


def busy_share(work_s, seconds, workers):
    """Measured: the work done, summed over all workers, ÷ the time they had (seconds x workers)."""
    return work_s / (seconds * workers)


def wasted_share(work_s, work_after_s):
    """The share of the work done after the client had already given up."""
    return work_after_s / work_s


def cut_off_seconds(work_s, normal_n, quick_s, slow_n):
    """The average work a slow request got before the deadline stopped it: the total work minus
    the normal requests' work (normal_n x quick_s), ÷ the number of slow requests."""
    return (work_s - normal_n * quick_s) / slow_n
