"""Original CPU scheduler simulation with a constant-cost baseline followed by an occupancy-dependent iteration-cost extension, both without prefill; not an Orca implementation or serving benchmark.
Run with Python 3.10+; standard library only. Writes results.json in the current directory.
"""
requests = [("A", 0, 4), ("B", 0, 1), ("C", 1, 1)]

def simulate(refill):
    waiting = list(requests)
    active = []
    completed = {}
    now = 0
    while waiting or active:
        if refill or not active:
            while len(active) < 2 and waiting and waiting[0][1] <= now:
                name, arrival, tokens = waiting.pop(0)
                active.append((name, tokens))
        if not active:
            now += 1
            continue
        now += 1
        survivors = []
        for name, remaining in active:
            remaining -= 1
            if remaining == 0:
                completed[name] = now
            else:
                survivors.append((name, remaining))
        active = survivors
    return completed

fixed = simulate(False)
flexible = simulate(True)
for label, result in (("fixed", fixed), ("iteration", flexible)):
    print(label + ": " + ", ".join(f"{name}={result[name]}" for name in "ABC"))
assert fixed == {"A": 4, "B": 1, "C": 5}
assert flexible == {"A": 4, "B": 1, "C": 2}

# Extended experiment: deterministic parameter sweep and invariants.
def admission(refill, base, per_active):
    waiting=[('A',0.,4),('B',0.,1),('C',1.,1)]; active=[]; now=0.; rows=[]; completed={}
    while waiting or active:
        if refill or not active:
            while len(active)<2 and waiting and waiting[0][1]<=now+1e-12:
                name,arrival,tokens=waiting.pop(0);active.append((name,tokens))
        if not active:
            now=waiting[0][1];continue
        start=now;now+=base+per_active*len(active)
        assert now>start
        rows.append(dict(start=start,finish=now,active=[name for name,_ in active]))
        survivors=[]
        for name,remaining in active:
            if remaining==1: completed[name]=now
            else: survivors.append((name,remaining-1))
        active=survivors
    return dict(policy='iteration' if refill else 'fixed',base=base,per_active=per_active,
                completed=completed,response_times={name:time-(1 if name=='C' else 0) for name,time in completed.items()},events=rows)
sweep=[admission(refill,base,cost) for base,cost in [(1.,0.),(.7,.1),(.7,.3),(.7,.6),( .7,1.)] for refill in [False,True]]
data=dict(sweep=sweep,capacity=2,requests=[dict(name=n,arrival=a,tokens=t) for n,a,t in [('A',0,4),('B',0,1),('C',1,1)]])
for r in sweep:
    assert len(r['completed'])==3
    assert all(v>0 for v in r['response_times'].values())
    print(f"base={r['base']} per-active={r['per_active']} {r['policy']}: A={r['response_times']['A']:.2f}, C={r['response_times']['C']:.2f} response units")

import json
from pathlib import Path
Path("results.json").write_text(json.dumps(data,indent=2,allow_nan=False)+"\n",encoding="utf-8")
