"""Compare request routing and model fixed-capacity failover.

Run with Python 3.10 or newer: python3 06-load-balancing-horizontal-scaling.py
All request costs, times, and probe results are deterministic. No network needed.
"""

from dataclasses import dataclass
from math import ceil


def fleet_size(peak_rps: int, safe_rps: int, unavailable: int) -> int:
    """Size a homogeneous pool with enough ready survivors for peak demand."""
    return ceil(peak_rps / safe_rps) + unavailable


@dataclass
class ProbeState:
    ready: bool = True
    successes: int = 0
    failures: int = 0

    def record(self, passed: bool) -> None:
        """Require two consecutive successes or failures for a transition."""
        if passed:
            self.successes += 1
            self.failures = 0
            if self.successes >= 2:
                self.ready = True
        else:
            self.failures += 1
            self.successes = 0
            if self.failures >= 2:
                self.ready = False


def simulate(costs: list[int], *, policy: str) -> tuple[list[list[int]], list[int]]:
    """Return assignments and completion times for a burst at time zero.

    Three identical workers run one request at a time, in arrival order.
    The router knows the count queued or running, but cannot see request cost.
    """
    queues: list[list[int]] = [[], [], []]
    available_at = [0, 0, 0]
    completion_times = []
    for sequence, cost in enumerate(costs):
        if policy == "round robin":
            worker = sequence % len(queues)
        elif policy == "least outstanding":
            worker = min(range(len(queues)), key=lambda i: len(queues[i]))
        else:
            raise ValueError(f"unknown routing policy: {policy}")
        queues[worker].append(cost)
        available_at[worker] += cost
        completion_times.append(available_at[worker])
    return queues, completion_times


def main() -> None:
    assert fleet_size(2400, 500, 1) == 6
    # Six replicas in three equal zones leave four survivors after one zone fails.
    assert 4 * 500 < 2400
    assert 6 * 500 >= 2400  # Nine total, with three lost.

    costs = [80, 10, 10, 80, 10, 10]
    for policy in ("round robin", "least outstanding"):
        queues, completion = simulate(costs, policy=policy)
        assert queues == [[80, 80], [10, 10], [10, 10]]
        assert completion == [80, 10, 10, 160, 20, 20]
        print(f"{policy}: queues {queues}, last completion {max(completion)} ms")

    probe = ProbeState()
    for passed in (False, True, False):
        probe.record(passed)
        assert probe.ready
    probe.record(False)
    assert not probe.ready
    probe.record(True)
    assert not probe.ready
    probe.record(True)
    assert probe.ready

    # Try it yourself: change the burst order, then allow arrivals over time.
    # Remove completed jobs from counts before routing each new arrival.
    # Add a rejected-request counter for a pool with no ready targets.
    print("Routing, survivor capacity, and probe threshold checks passed.")


if __name__ == "__main__":
    main()
