"""Runnable versions of classic CS fundamentals interview exercises. Python 3.8+, standard library only."""
from __future__ import annotations

import ipaddress
import threading
import time
from collections import OrderedDict, deque


# ---------- Operating systems: CPU scheduling ----------

def schedule(jobs: list[tuple[str, int, int]], policy: str = "fcfs", quantum: int = 2) -> dict[str, int]:
    """Return waiting time per job. jobs = [(name, arrival, burst)]. policy: fcfs | sjf | rr.

    sjf is non-preemptive shortest-job-first. rr is round robin with the given quantum.
    """
    jobs = sorted(jobs, key=lambda j: (j[1], j[0]))
    burst = {n: b for n, _, b in jobs}
    finish: dict[str, int] = {}
    t = 0
    if policy in ("fcfs", "sjf"):
        pending = list(jobs)
        while pending:
            ready = [j for j in pending if j[1] <= t] or [min(pending, key=lambda j: j[1])]
            job = ready[0] if policy == "fcfs" else min(ready, key=lambda j: (j[2], j[1]))
            pending.remove(job)
            t = max(t, job[1]) + job[2]
            finish[job[0]] = t
    elif policy == "rr":
        remaining = dict(burst)
        queue: deque = deque()
        i = 0
        while len(finish) < len(jobs):
            while i < len(jobs) and jobs[i][1] <= t:
                queue.append(jobs[i][0]); i += 1
            if not queue:
                t = jobs[i][1]
                continue
            name = queue.popleft()
            run = min(quantum, remaining[name])
            t += run
            remaining[name] -= run
            while i < len(jobs) and jobs[i][1] <= t:  # arrivals during the slice go first
                queue.append(jobs[i][0]); i += 1
            if remaining[name] == 0:
                finish[name] = t
            else:
                queue.append(name)
    else:
        raise ValueError(policy)
    arrival = {n: a for n, a, _ in jobs}
    return {n: finish[n] - arrival[n] - burst[n] for n in burst}


# ---------- Operating systems: page replacement ----------

def page_faults(refs: list[int], frames: int, policy: str = "lru") -> int:
    """Count page faults for FIFO, LRU or OPT (Belady's optimal)."""
    mem: list[int] = []
    faults = 0
    for i, page in enumerate(refs):
        if page in mem:
            if policy == "lru":
                mem.remove(page); mem.append(page)
            continue
        faults += 1
        if len(mem) == frames:
            if policy in ("fifo", "lru"):
                mem.pop(0)
            elif policy == "opt":
                future = refs[i + 1:]
                victim = max(mem, key=lambda p: future.index(p) if p in future else len(future) + 1)
                mem.remove(victim)
            else:
                raise ValueError(policy)
        mem.append(page)
    return faults


# ---------- Operating systems: deadlock avoidance ----------

def bankers_safe(available: list[int], max_need: list[list[int]], allocation: list[list[int]]) -> list[int] | None:
    """Banker's algorithm. Returns a safe order of process indexes, or None if the state is unsafe."""
    work = list(available)
    need = [[m - a for m, a in zip(mr, ar)] for mr, ar in zip(max_need, allocation)]
    done = [False] * len(max_need)
    order: list[int] = []
    progressed = True
    while progressed:
        progressed = False
        for p, finished in enumerate(done):
            if not finished and all(n <= w for n, w in zip(need[p], work)):
                work = [w + a for w, a in zip(work, allocation[p])]
                done[p] = True
                order.append(p)
                progressed = True
    return order if all(done) else None


# ---------- Concurrency ----------

class BoundedBuffer:
    """Producer-consumer queue built from a lock and two condition variables."""

    def __init__(self, capacity: int):
        self.items: deque = deque()
        self.capacity = capacity
        lock = threading.Lock()
        self.not_full = threading.Condition(lock)
        self.not_empty = threading.Condition(lock)

    def put(self, item) -> None:
        with self.not_full:
            while len(self.items) >= self.capacity:  # while, not if: spurious wakeups
                self.not_full.wait()
            self.items.append(item)
            self.not_empty.notify()

    def get(self):
        with self.not_empty:
            while not self.items:
                self.not_empty.wait()
            item = self.items.popleft()
            self.not_full.notify()
            return item


class LRUCache:
    """O(1) get/put LRU cache (hash map + ordered linked list), thread-safe."""

    def __init__(self, capacity: int):
        self.capacity = capacity
        self.data: OrderedDict = OrderedDict()
        self.lock = threading.Lock()

    def get(self, key, default=None):
        with self.lock:
            if key not in self.data:
                return default
            self.data.move_to_end(key)
            return self.data[key]

    def put(self, key, value) -> None:
        with self.lock:
            self.data[key] = value
            self.data.move_to_end(key)
            if len(self.data) > self.capacity:
                self.data.popitem(last=False)


class TokenBucket:
    """Rate limiter: `rate` tokens per second, bursts up to `capacity`."""

    def __init__(self, rate: float, capacity: float, clock=time.monotonic):
        self.rate, self.capacity, self.clock = rate, capacity, clock
        self.tokens = capacity
        self.last = clock()
        self.lock = threading.Lock()

    def allow(self, cost: float = 1.0) -> bool:
        with self.lock:
            now = self.clock()
            self.tokens = min(self.capacity, self.tokens + (now - self.last) * self.rate)
            self.last = now
            if self.tokens >= cost:
                self.tokens -= cost
                return True
            return False


# ---------- Networking ----------

def subnet_info(cidr: str) -> dict:
    net = ipaddress.ip_network(cidr, strict=False)
    hosts = net.num_addresses - 2 if net.version == 4 and net.prefixlen < 31 else net.num_addresses
    return {"network": str(net.network_address), "broadcast": str(net.broadcast_address),
            "netmask": str(net.netmask), "addresses": net.num_addresses, "usable_hosts": hosts}


def same_subnet(ip_a: str, ip_b: str, prefix: int) -> bool:
    return ipaddress.ip_network(f"{ip_a}/{prefix}", strict=False) == ipaddress.ip_network(f"{ip_b}/{prefix}", strict=False)
