"""Deterministic chunk-indexed throughput and buffer arithmetic for two hand-coded rules; no trained Pensieve policy, live streaming, or packet-level transport model.
Run with Python 3.10+; standard library only. Writes results.json in the current directory.
"""
traces = {
    "steady": [3.0] * 6,
    "bursty": [6.0, 0.75, 6.0, 0.75, 6.0, 0.75],
    "low-throughput": [3.0, 3.0, 0.25, 0.25, 3.0, 3.0],
}

def simulate(bandwidths, rule):
    buffer = 2.0
    previous = 1.0
    score = total_stall = total_bitrate = 0.0
    history = []
    for bandwidth in bandwidths:
        bitrate = 3.0 if rule == "high" or buffer >= 4.0 else 1.0
        download = 2.0 * bitrate / bandwidth
        stall = max(download - buffer, 0.0)
        buffer = min(8.0, max(buffer - download, 0.0) + 2.0)
        score += bitrate - 4.0 * stall - 0.5 * abs(bitrate - previous)
        total_stall += stall
        total_bitrate += bitrate
        history.append((bitrate, round(buffer, 2), round(stall, 2)))
        previous = bitrate
        assert 0.0 <= buffer <= 8.0 and stall >= 0.0
    return score, total_stall, total_bitrate / len(bandwidths), history

for name, bandwidths in traces.items():
    for rule in ["high", "buffer"]:
        score, stall, bitrate, history = simulate(bandwidths, rule)
        print(f"{name}/{rule}: score={score:.2f} stall={stall:.2f}s "
              f"mean_bitrate={bitrate:.2f}Mbps")
        print("  (bitrate, buffer, stall):", history)

assert simulate(traces["steady"], "high")[1] == 0.0

# Extended experiment: deterministic parameter sweep and invariants.
from itertools import combinations
def stream(bandwidths,rule):
    buffer=2.;previous=1.;score=stall_sum=bitrate_sum=0.;history=[]
    for index,bandwidth in enumerate(bandwidths):
        before=buffer;bitrate=3. if rule=='high' or buffer>=4 else 1.
        download=2*bitrate/bandwidth;stall=max(download-buffer,0.)
        buffer=min(8.,max(buffer-download,0.)+2.)
        score+=bitrate-4*stall-.5*abs(bitrate-previous)
        stall_sum+=stall;bitrate_sum+=bitrate
        history.append(dict(chunk=index+1,bandwidth=bandwidth,bitrate=bitrate,buffer_before=before,
                            buffer_after=buffer,download_seconds=download,stall_seconds=stall))
        previous=bitrate
    return dict(rule=rule,bandwidths=bandwidths,mean_bandwidth=sum(bandwidths)/len(bandwidths),
                score=score,total_stall_seconds=stall_sum,mean_bitrate=bitrate_sum/len(bandwidths),history=history)
permutations=[]
for high_positions in combinations(range(6),3):
    bandwidths=[6. if i in high_positions else .75 for i in range(6)]
    for rule in ['high','buffer']:permutations.append(stream(bandwidths,rule))
assert len(permutations)==40 and all(r['mean_bandwidth']==3.375 for r in permutations)
selected=[stream(traces['bursty'],rule) for rule in ['high','buffer']]
data=dict(permutation_sweep=permutations,selected=selected,
          trace_model='Bandwidth held constant during each chunk download; values indexed by chunk, not wall-clock time.',
          chunk_seconds=2,initial_buffer_seconds=2,maximum_buffer_seconds=8)
for rule in ['high','buffer']:
    rows=[r for r in permutations if r['rule']==rule]
    print(f"20 equal-mean permutations, {rule}: stalls range {min(r['total_stall_seconds'] for r in rows):.3f}–{max(r['total_stall_seconds'] for r in rows):.3f} s")

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