#!/usr/bin/env python3
"""Offline synthetic scheduler comparison; no network, files, or proxy activity."""
from dataclasses import dataclass
from typing import Dict, Iterable, List, Tuple


@dataclass(frozen=True)
class Job:
    name: str
    source: str
    arrival: int
    service: int
    deadline: int
    order: int


GLOBAL_SLOTS = 2
RESERVATIONS = {"slow": 1, "healthy": 1}
MIXED_JOBS = (
    Job("S1", "slow", 0, 8, 9, 0),
    Job("S2", "slow", 0, 8, 9, 1),
    Job("H1", "healthy", 1, 1, 3, 2),
    Job("H2", "healthy", 1, 1, 4, 3),
)
IDLE_SOURCE_JOBS = (
    Job("S1", "slow", 0, 8, 9, 0),
    Job("S2", "slow", 0, 8, 9, 1),
)


def require_jobs(jobs: Iterable[Job], slots: int, reservations: Dict[str, int] = None) -> Tuple[Job, ...]:
    rows = tuple(jobs)
    if isinstance(slots, bool) or not isinstance(slots, int) or slots <= 0:
        raise ValueError("global slots must be a positive integer")
    if not rows:
        raise ValueError("at least one job is required")
    names = set()
    for job in rows:
        if not isinstance(job, Job):
            raise ValueError("every row must be a Job")
        if not job.name or job.name in names or not job.source:
            raise ValueError("job names must be unique and names/sources must be non-empty")
        names.add(job.name)
        if any(isinstance(value, bool) or not isinstance(value, int) for value in (job.arrival, job.service, job.deadline, job.order)):
            raise ValueError("arrival, service, deadline, and order must be integers")
        if job.arrival < 0 or job.service <= 0 or job.deadline < job.arrival:
            raise ValueError("invalid arrival, service, or deadline")
        if reservations is not None and job.source not in reservations:
            raise ValueError("every source needs a reservation")
    if reservations is not None:
        values = tuple(reservations.values())
        if any(isinstance(value, bool) or not isinstance(value, int) or value <= 0 for value in values) or sum(values) != slots:
            raise ValueError("reservations must be positive integers that sum to global slots")
    return rows


def simulate(jobs: Iterable[Job], slots: int, reservations: Dict[str, int] = None):
    """Non-preemptive discrete-event model. A completion releases its slot immediately."""
    rows = tuple(jobs)
    if reservations is None:
        require_jobs(rows, slots)
        reserved = False
    else:
        require_jobs(rows, slots, reservations)
        reserved = True
    waiting: List[Job] = []
    running: List[Tuple[int, Job]] = []
    completed = []
    remaining = sorted(rows, key=lambda job: (job.arrival, job.order))
    now = 0
    active_by_source: Dict[str, int] = {source: 0 for source in (reservations or {})}

    while remaining or waiting or running:
        if not waiting and not running and remaining:
            now = remaining[0].arrival
        while remaining and remaining[0].arrival <= now:
            waiting.append(remaining.pop(0))
        # FIFO scans in arrival/order order; a blocked source does not consume a global slot.
        started = True
        while started and len(running) < slots:
            started = False
            for index, job in enumerate(waiting):
                if not reserved or active_by_source[job.source] < reservations[job.source]:
                    waiting.pop(index)
                    finish = now + job.service
                    running.append((finish, job))
                    active_by_source[job.source] = active_by_source.get(job.source, 0) + 1
                    started = True
                    break
        if running:
            next_finish = min(finish for finish, _ in running)
            next_arrival = remaining[0].arrival if remaining else None
            now = min(next_finish, next_arrival) if next_arrival is not None and next_arrival < next_finish else next_finish
            done = [(finish, job) for finish, job in running if finish == now]
            running = [(finish, job) for finish, job in running if finish != now]
            for finish, job in sorted(done, key=lambda item: item[1].order):
                active_by_source[job.source] -= 1
                completed.append((job, finish))
        elif waiting and not remaining:
            raise AssertionError("waiting jobs must be runnable when no jobs are running")
    if {job.name for job, _ in completed} != {job.name for job in rows} or len(completed) != len(rows):
        raise AssertionError("every scheduled job must be completed exactly once")
    return tuple(sorted(completed, key=lambda item: item[0].order))


def score(completed):
    by_source = {}
    for job, finish in completed:
        on_time, total = by_source.get(job.source, (0, 0))
        by_source[job.source] = (on_time + (finish <= job.deadline), total + 1)
    drain = max(finish for _, finish in completed)
    return by_source, drain


def summary(label, completed):
    by_source, drain = score(completed)
    return f"{label}: healthy={by_source.get('healthy', (0, 0))[0]}/{by_source.get('healthy', (0, 0))[1]} on-time; slow={by_source['slow'][0]}/{by_source['slow'][1]} on-time; drain={drain}; accounted={len(completed)}/{len(completed)}"


def main():
    shared = simulate(MIXED_JOBS, GLOBAL_SLOTS)
    partitioned = simulate(MIXED_JOBS, GLOBAL_SLOTS, RESERVATIONS)
    shared_idle = simulate(IDLE_SOURCE_JOBS, GLOBAL_SLOTS)
    partitioned_idle = simulate(IDLE_SOURCE_JOBS, GLOBAL_SLOTS, RESERVATIONS)
    assert summary("shared FIFO", shared) == "shared FIFO: healthy=0/2 on-time; slow=2/2 on-time; drain=9; accounted=4/4"
    assert summary("partitioned", partitioned) == "partitioned: healthy=2/2 on-time; slow=1/2 on-time; drain=16; accounted=4/4"
    assert summary("shared FIFO / healthy idle", shared_idle) == "shared FIFO / healthy idle: healthy=0/0 on-time; slow=2/2 on-time; drain=8; accounted=2/2"
    assert summary("partitioned / healthy idle", partitioned_idle) == "partitioned / healthy idle: healthy=0/0 on-time; slow=1/2 on-time; drain=16; accounted=2/2"
    for bad in ((), (Job("bad", "slow", 0, 0, 1, 0),)):
        try:
            simulate(bad, GLOBAL_SLOTS, RESERVATIONS)
        except ValueError:
            pass
        else:
            raise AssertionError("bad input must fail")
    print("offline synthetic scheduler experiment; network_requests=0")
    print("global_slots=2; mixed jobs=S1,S2 arrive 0/service 8/deadline 9; H1,H2 arrive 1/service 1/deadlines 3,4")
    print(summary("shared FIFO", shared))
    print(summary("partitioned slow=1 healthy=1", partitioned))
    print("one-source-idle jobs=S1,S2 only; healthy reservation is idle")
    print(summary("shared FIFO / healthy idle", shared_idle))
    print(summary("partitioned slow=1 healthy=1 / healthy idle", partitioned_idle))
    print("PASS: every scheduled job completed exactly once; reservation protects healthy deadlines but can lengthen slow-source drain")


if __name__ == "__main__":
    main()
