"""
Practice: race conditions. Lab 05's checks and fixes from scripts 01_lost_updates.py,
03_isolation.py and 04_hot_row.py: the bank's three checks (bank.violations), the booking
checks (booking.booking_violations), two clerks playing a lost update and two doctors playing
write skew, and the arithmetic of the lab's tables (medians of 3 runs, change against the
broken code).

The two "play" functions are a model, not the database: they replay one fixed order of
steps (A reads, B reads, A writes, B writes) the way 03_isolation.py's Exercise 1 does, so
you can see what each fix changes.

Fill in the TODOs, then run the tests:
    pytest test_race_practice.py        (locally)
or press "Run tests" on the chapter page.
"""
from collections import Counter


def violations(balances, ledger, initial=1000):
    """The bank's three checks, after a run.

    balances: {account id: final balance}. ledger: a list of (src, dst, amount), one per
    transfer the bank recorded. Every account started at `initial`.
    Return a dict:
      money_created    final total - starting total (must be 0)
      negative         how many accounts are below zero (must be 0)
      ledger_mismatch  how many accounts differ from start + what the ledger says came in
                       - what went out (must be 0)
      misplaced        the sum over accounts of |balance - what the ledger says it should be|
      ok               True only if the three "must be 0" values are all 0
    """
    expected = Counter({a: initial for a in balances})
    for src, dst, amount in ledger:
        expected[src] -= amount
        expected[dst] += amount
    created = sum(balances.values()) - initial * len(balances)
    negative = sum(1 for b in balances.values() if b < 0)
    mismatch = sum(1 for a, b in balances.items() if b != expected[a])
    misplaced = sum(abs(b - expected[a]) for a, b in balances.items())
    return {"money_created": created, "negative": negative, "ledger_mismatch": mismatch,
            "misplaced": misplaced, "ok": created == 0 and negative == 0 and mismatch == 0}


def gained_and_lost(misplaced, created):
    """Split the misplaced coins into those that appeared and those that vanished.
    appeared - vanished = created, and appeared + vanished = misplaced.
    Return (appeared, vanished)."""
    gained = (misplaced + created) // 2
    return gained, misplaced - gained


def play_withdrawals(start, a, b, mode):
    """Two clerks withdraw `a` and `b` from one account holding `start`, at the same moment.
    The order of steps: A reads, B reads, A writes and commits, B writes and commits.
    A withdrawal only goes ahead if the balance the clerk sees covers it; otherwise that
    clerk answers "insufficient" and writes nothing.

    mode:
      "naive"    each clerk writes (what she read - her amount)
      "atomic"   each clerk asks the database for "balance - amount if balance >= amount":
                 no read, the database works from the current balance
      "lock"     A reads with a lock; B's read waits until A commits, then sees A's result
      "version"  each write only goes ahead if the version is still the one the clerk read;
                 if A wrote, B's write finds it changed, so B retries once: reads again,
                 then writes from the new balance (or answers "insufficient")

    Return {"balance": final balance, "answers": [A's answer, B's answer], "retries": n},
    where an answer is "ok" or "insufficient".
    """
    if mode == "naive":
        read_a, read_b = start, start                  # both copy the same balance
        bal, answers = start, []
        for seen, amt in ((read_a, a), (read_b, b)):
            if seen < amt:
                answers.append("insufficient")
            else:
                bal = seen - amt                       # writes what it read, adjusted
                answers.append("ok")
        return {"balance": bal, "answers": answers, "retries": 0}
    if mode in ("atomic", "lock", "version"):
        bal, answers = start, []
        for amt in (a, b):                             # each one effectively sees the current balance
            if bal < amt:
                answers.append("insufficient")
            else:
                bal -= amt
                answers.append("ok")
        # version: B's write finds the version changed only if A actually wrote
        retries = 1 if mode == "version" and answers[0] == "ok" and start >= b else 0
        return {"balance": bal, "answers": answers, "retries": retries}
    raise ValueError(mode)


def play_doctors(mode):
    """Two doctors on call; the rule is that at least one stays. Each counts the doctors on
    call and goes off call (writes only her own row) if she sees at least 2.
    The order: A counts, B counts, A goes off, B goes off, then both commit.

    mode:
      "read committed" or "repeatable read"  both counts see 2, both go off
      "serializable"  B's commit fails (her count read A's row, which A changed); B retries:
                      counts again and stays
      "lock"          A counts with FOR UPDATE; B's count waits until A commits, then sees 1

    Return (doctors still on call, retries).
    """
    if mode in ("read committed", "repeatable read"):
        return 0, 0
    if mode == "serializable":
        return 1, 1
    if mode == "lock":
        return 1, 0
    raise ValueError(mode)


def booking_check(capacity, seats):
    """The booking checks. seats: the seat number of every booking stored.
    Return a dict:
      bookings     how many bookings were stored
      oversold     bookings beyond the capacity (0 if none)
      distinct     how many different seats were taken
      on_taken     bookings that landed on a seat that already had one
      ok           True if nothing was oversold, no seat has two bookings, and every
                   seat number is between 1 and capacity
    """
    distinct = len(set(seats))
    on_taken = len(seats) - distinct
    oversold = max(0, len(seats) - capacity)
    in_range = all(1 <= s <= capacity for s in seats)
    return {"bookings": len(seats), "oversold": oversold, "distinct": distinct, "on_taken": on_taken,
            "ok": oversold == 0 and on_taken == 0 and in_range}


def median_and_range(runs):
    """The lab's tables: the median of an odd number of runs, with the lowest and highest.
    Return (median, lowest, highest)."""
    s = sorted(runs)
    return s[len(s) // 2], s[0], s[-1]


def change(value, base):
    """How much higher (positive) or lower (negative) `value` is than `base`, as a fraction
    of `base`. 110 against 100 is 0.1; 80 against 100 is -0.2."""
    return (value - base) / base
