"""A sampled persistence detector, queue-drain arithmetic, and separate control-law spacing calculation; not full CoDel, a responsive TCP simulation, or a Linux benchmark.
Run with Python 3.10+; standard library only. Writes results.json in the current directory.
"""
import math

target_ms = 5
interval_ms = 40
traces = {
    "transient": [1, 12, 18, 10, 3, 1, 1, 1, 1, 1],
    "persistent": [1, 8, 8, 8, 8, 8, 8, 8, 8, 8],
}

def first_persistent_sample(delays):
    above_since = None
    for index, delay in enumerate(delays):
        now_ms = 10 * index
        if delay < target_ms:
            above_since = None
        elif above_since is None:
            above_since = now_ms
        elif now_ms - above_since >= interval_ms:
            return now_ms
    return None

for name, delays in traces.items():
    print(f"{name}: peak={max(delays)}ms "
          f"first_persistent={first_persistent_sample(delays)}")
assert first_persistent_sample(traces["transient"]) is None
assert first_persistent_sample(traces["persistent"]) == 50

for queued_bytes in [40_000, 1_000_000]:
    delay_ms = 1000 * 8 * queued_bytes / 10_000_000
    print(f"queued_bytes={queued_bytes}: drain_time={delay_ms:.1f}ms")
spacings = [round(interval_ms / math.sqrt(count), 2) for count in range(1, 5)]
print("Illustrative successive signal spacings (ms):", spacings)

# Extended experiment: deterministic parameter sweep and invariants.
def detect(delays,target,interval):
    start=None
    for index,delay in enumerate(delays):
        t=index*10
        if delay<target:start=None
        elif start is None:start=t
        elif t-start>=interval:return t
    return None
sweep=[]
for name,delays in traces.items():
    for target in [2,5,8,10]:
        for interval in [10,20,30,40,60,80]:
            sweep.append(dict(trace=name,target_ms=target,interval_ms=interval,first_trigger_ms=detect(delays,target,interval)))
spacing=[dict(signal_count=count,spacing_ms=40/math.sqrt(count)) for count in range(1,17)]
data=dict(traces=traces,sample_interval_ms=10,target_ms=5,interval_ms=40,
          detector_sweep=sweep,signal_spacings=spacing,
          drain_times=[dict(queued_bytes=b,drain_ms=1000*8*b/10_000_000) for b in [40000,1000000]])
assert detect(traces['transient'],5,20)==30
assert detect(traces['transient'],5,40) is None
print('Transient trace triggers with a 20 ms interval (at 30 ms), but not with a 40 ms interval.')
print('The persistence interval changes the question; peak delay alone cannot answer it.')

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