#!/usr/bin/env python3
"""What-if scenarios for docs/CLOUDFLARE-SERVERLESS.md and the R&D page: cold-start timelines, burst response, warm-pool threshold and lead time,
Cloudflare cost under other capacity assumptions, and capacity as clock speed and core count change. Every output is MODELLED (theory with stated
assumptions), except the rows marked basis=measured, which are our own measurements repeated so that a model line can be read against them.

    python3 docs/data/scenarios.py          # rewrites the cloudflare_scen_*.csv files next to it
    python3 docs/data/burst_sim.py          # the campaign-day simulation (cloudflare_burst_day.csv)
    python3 docs/data/costs.py              # the cost model and break-even curves

Change an assumption in the ASSUMPTIONS block below (or in costs.csv for prices), re-run, and rebuild the site: the charts redraw from the CSVs.
No dependencies beyond the Python 3 standard library."""
import csv, io, contextlib, importlib.util, math, os

HERE = os.path.dirname(os.path.abspath(__file__))


def load(name):
    spec = importlib.util.spec_from_file_location(name, os.path.join(HERE, name + ".py"))
    m = importlib.util.module_from_spec(spec)
    with contextlib.redirect_stdout(io.StringIO()):
        spec.loader.exec_module(m)
    return m


def write(name, comment, header, rows):
    with open(os.path.join(HERE, name), "w", newline="") as f:
        for line in comment.strip().split("\n"):
            f.write("# " + line + "\n")
        w = csv.writer(f, lineterminator="\n")   # quotes fields that contain commas (scenario names do)
        w.writerow(header)
        for r in rows:
            w.writerow(r)


# ------------------------------------------------------------------ ASSUMPTIONS (edit and re-run)
# Cold start. The three load times come from our own run of 2026-12-05 (cloudflare_load_timeline.csv): process spawn 0.7 s, then the three streaming workers
# ready at 4.6 s, Whisper small at 6.1 s and Parakeet (loaded after Whisper in each final worker) at 8.7 s.
SPAWN_S, FAST_S, WHISPER_END_S, PARAKEET_S = 0.7, 3.9, 6.1, 2.6
IMAGE_GB = 2.0                      # image size: venv 431 MB + models 1.1 GB + Whisper small + the Go binary (du of the live install)
SCEN_COLD = [   # name, platform overhead in seconds (container start + image pull), loading strategy
    ("Local service, measured", 0.0, "sequential", "measured"),
    ("Cloudflare, image already on the host (start 1 s)", 1.0, "sequential", "modelled"),
    ("Cloudflare, start 2 s + pull 2 GB at 400 MB/s", 2.0 + IMAGE_GB * 1000 / 400, "sequential", "modelled"),
    ("Cloudflare, start 3 s + pull 2 GB at 100 MB/s", 3.0 + IMAGE_GB * 1000 / 100, "sequential", "modelled"),
    ("As the 400 MB/s case, Whisper and Parakeet loaded in parallel", 2.0 + IMAGE_GB * 1000 / 400, "parallel", "modelled"),
    ("As the 400 MB/s case, English route only (Parakeet, no Whisper)", 2.0 + IMAGE_GB * 1000 / 400, "english", "modelled"),
]
# Burst response: a step of N extra streams arrives while the base is full.
STEP_STREAMS = 20
SCEN_BURST = [  # name, reaction delay s (time until the controller notices), warm-up s, streams per instance, instances already warm
    ("Worker router, Cloudflare container (2 streams each), warm-up 20 s", 5, 20, 2, 0),
    ("Load Balancing monitor, Cloudflare container, warm-up 20 s", 60, 20, 2, 0),
    ("Worker router, EC2 spot instance (4 streams each), warm-up 120 s", 5, 120, 4, 0),
    ("Load Balancing monitor, EC2 spot, warm-up 120 s", 60, 120, 4, 0),
    ("Pre-warmed: threshold crossed earlier, 3 spot instances already ready", 5, 120, 4, 3),
]
# Warm-pool grid (burst_sim.simulate): thresholds, lead times in minutes, base sizes in 4-stream units
THRESHOLDS = [0.4, 0.5, 0.65, 0.8, 0.9]
LEADS_MIN = [1, 2, 5, 10]
BASE_SIZES = [3, 4, 6, 8, 10, 12, 16]
# Cost what-if: streams per vCPU of the (undocumented) Cloudflare vCPU
SPV_CASES = [("vCPU like Intel c7i (0.50 streams per vCPU)", 0.50), ("vCPU like AMD c7a (0.83)", 0.83), ("vCPU like Graviton4 (1.17)", 1.167), ("a vCPU twice as fast as c7a (1.66)", 1.66)]
VOLUMES = [10_000, 30_000, 100_000, 300_000, 1_000_000, 3_000_000, 10_000_000]
# Capacity what-if
CLOCKS = [2.0 + 0.25 * i for i in range(0, 13)]       # 2.0 to 5.0 GHz
VCPUS = [4, 8, 16, 24, 48, 96]
SATURATION_PER_DOUBLING = 0.08                         # above 24 vCPUs each doubling loses this share (shared final-pass pool and memory bandwidth): an assumption, not measured


# ------------------------------------------------------------------ 1. cold-start timelines
def cold_events(overhead, strategy):
    t0 = overhead
    fast = t0 + SPAWN_S + FAST_S
    if strategy == "sequential":
        ev = [(fast, 3), (t0 + WHISPER_END_S, 5), (t0 + WHISPER_END_S + PARAKEET_S, 7)]; total = 7
    elif strategy == "parallel":
        ev = [(t0 + SPAWN_S + PARAKEET_S, 2), (fast, 5), (t0 + WHISPER_END_S, 7)]; total = 7
    else:
        ev = [(t0 + SPAWN_S + PARAKEET_S, 2), (fast, 5)]; total = 5
    return sorted(ev), total


rows, summ = [], []
for name, overhead, strategy, basis in SCEN_COLD:
    ev, total = cold_events(overhead, strategy)
    pts = [(0.0, 0), (overhead + SPAWN_S, 0)] + ev
    for t, n in pts:
        rows.append((name, round(t, 2), round(100 * n / total), basis))
    ready = ev[-1][0]
    summ.append((name, round(overhead, 1), round(ready - overhead, 1), round(ready, 1), basis))
write("cloudflare_scen_coldstart.csv", """Cold-start timelines under different assumptions (percent of the models a stream needs that are loaded, against seconds since the caller arrived).
status: modelled, except the first scenario (measured). Assumptions: spawn 0.7 s; three streaming workers load in 3.9 s; each final worker loads Whisper small (ready at 6.1 s) then Parakeet (2.6 s); platform overhead = container start (1 to 3 s, Cloudflare FAQ) + image pull of a 2 GB image at the stated speed (pull speed is NOT documented); loading in parallel ignores CPU contention. Re-run: python3 docs/data/scenarios.py""",
      ["scenario", "seconds", "models_loaded_pct", "basis"], rows)
write("cloudflare_scen_coldstart_summary.csv", "Seconds from the caller's arrival to ready, split into platform overhead and loading, for each cold-start scenario (see cloudflare_scen_coldstart.csv for the assumptions). Modelled except the first row.",
      ["scenario", "platform_overhead_s", "loading_s", "ready_s", "basis"], summ)

# ------------------------------------------------------------------ 2. burst response
rows, summ = [], []
for name, react, lead, cap, warm in SCEN_BURST:
    k = math.ceil(STEP_STREAMS / cap) + 1
    cum = 0.0
    for t in range(0, 305, 5):
        ready = warm + (k if t >= react + lead else 0)
        spill = max(0.0, STEP_STREAMS - ready * cap)
        cum += spill * 5 / 60
        rows.append((name, t, round(spill, 1), round(cum, 2), "modelled"))
    summ.append((name, react, lead, round(cum, 1), 0, "modelled"))
dg_min = float([r for r in csv.DictReader(l for l in open(os.path.join(HERE, "costs.csv")) if not l.startswith("#")) if r["key"] == "dg_nova3_mono_stream_payg"][0]["value"])
summ = [(a, b, c, d, round(d * dg_min, 3), f) for (a, b, c, d, e, f) in summ]
write("cloudflare_scen_burst_response.csv", f"""Burst response: {STEP_STREAMS} extra streams arrive at t=0 while the base is full; streams that no warm instance can take go to the hosted provider. status: modelled.
Assumptions: the controller notices after the reaction delay (a Worker reading health: about 5 s; a Load Balancing monitor with retries: about 60 s); it starts enough instances for the step plus one spare; all become ready together after the warm-up (Cloudflare container 20 s, an optimistic guess; EC2 spot 120 s); an instance carries 2 (Cloudflare) or 4 (EC2) streams. spill_streams = streams on the hosted provider at that second; cumulative = stream-minutes so far. Re-run: python3 docs/data/scenarios.py""",
      ["scenario", "seconds", "spill_streams", "cumulative_spill_stream_minutes", "basis"], rows)
write("cloudflare_scen_burst_response_summary.csv", "Hosted-provider stream-minutes and their cost in the first 5 minutes after a step of 20 streams, per scenario (Deepgram pay-as-you-go $0.0048 a minute, costs.csv). Modelled.",
      ["scenario", "reaction_delay_s", "warm_up_s", "spill_stream_minutes_in_5_min", "spill_cost_usd", "basis"], summ)

# ------------------------------------------------------------------ 3. warm-pool threshold, lead time and base size over the campaign day
bs = load("burst_sim")
rows = []
RAMPS_MIN = [5, 20, 60]
for ramp in RAMPS_MIN:
    dfn = bs.make_demand(ramp_min=ramp, flash=False)       # no flash crowd here: it is a step and tested separately (burst response)
    for lead in LEADS_MIN:
        for thr in THRESHOLDS:
            minutes, tot = bs.simulate(thresh=thr, lead=lead, demand_fn=dfn)
            c = bs.costs_of(tot); sh = c["stream_hours"]
            rows.append(("threshold_lead_ramp", thr * 100, lead, ramp, bs.BASE_UNITS, round(sh["hosted"], 2), round(sh["inst_min"], 1), tot["starts"], round(c["base"] + c["burst"] + c["hosted"], 2), "modelled"))
for units in BASE_SIZES:
    minutes, tot = bs.simulate(base_units=units)
    c = bs.costs_of(tot, base_units=units); sh = c["stream_hours"]
    rows.append(("base_size", bs.THRESH * 100, bs.LEAD, 20, units, round(sh["hosted"], 2), round(sh["inst_min"], 1), tot["starts"], round(c["base"] + c["burst"] + c["hosted"], 2), "modelled"))
write("cloudflare_scen_threshold_grid.csv", """Warm-pool sensitivity on the simulated campaign day of burst_sim.py: warm-up threshold (percent of the base), warm-up lead time (minutes) and base size (units of 4 streams).
status: modelled. Same day and demand shape as cloudflare_burst_day.csv, with the campaign ramp length (ramp_min) varied and no flash crowd in the ramp studies (base_size uses the full day with the flash crowd); hosted_stream_hours = calls that found no capacity and went to the hosted provider; burst_instance_hours = instance-hours of burst capacity (spot, $0.0873 an hour per 4 streams, third-party price); day_cost_usd = base on demand + burst + hosted at $0.288 a stream-hour. Re-run: python3 docs/data/scenarios.py""",
      ["study", "threshold_pct", "lead_min", "ramp_min", "base_units", "hosted_stream_hours", "burst_instance_hours", "instance_starts", "day_cost_usd", "basis"], rows)

# ------------------------------------------------------------------ 4. cost what-if: how fast is a Cloudflare vCPU, and is CPU billed on active use
cs = load("costs")
rows = []
for name, spv in SPV_CASES:
    cs.cf_cpu_s_stream = 1 / spv                                   # vCPU-seconds per audio second
    cs.cf_streams = max(1, math.floor(4 * spv * cs.P["measured_derate"]))
    for M in VOLUMES:
        for window, kind in ((cs.H_ON, "roundclock"),):
            a, n = cs.cf_always(M, window)
            z, _ = cs.cf_zero(M, window)
            whole = a - max(0, M * 60 * cs.cf_cpu_s_stream - cs.P["cf_container_incl_vcpu_min"] * 60) * cs.P["cf_container_vcpu_s"] + n * 4 * cs.H_ON * 3600 * cs.P["cf_container_vcpu_s"]
            rows.append((name, round(spv, 3), cs.cf_streams, M, round(a, 2), round(z, 2), round(whole, 2), "modelled"))
base = {}
for M in VOLUMES:
    o, _ = cs.cf_options(M, "roundclock")
    base[M] = (o["deepgram"], o["ec2_c8g_on_demand"])
for M in VOLUMES:
    rows.append(("reference: Deepgram pay-as-you-go", "", "", M, round(base[M][0], 2), "", "", "sourced price"))
    rows.append(("reference: EC2 Graviton4 on-demand", "", "", M, round(base[M][1], 2), "", "", "measured capacity, list price"))
write("cloudflare_scen_cost_whatif.csv", """Cloudflare container cost against monthly minutes if the (undocumented) vCPU were slower or faster, traffic round the clock, 4 vCPU / 8 GiB containers. status: modelled; the two reference rows are the sourced Deepgram price and the EC2 Graviton4 figure (measured capacity, list price).
Assumptions: streams per container = floor(4 x streams per vCPU x 0.85); CPU seconds per audio second = 1 / streams per vCPU (the measured knee); CPU billed on active use only (always_warm_usd, scale_to_zero_usd) or, in always_warm_if_billed_whole_time_usd, on the whole running time of every container (the pricing page does not define 'active'); other assumptions as costs.csv (cf_ rows). Generated with the functions of costs.py. Re-run: python3 docs/data/scenarios.py""",
      ["scenario", "streams_per_vcpu", "streams_per_container", "minutes", "always_warm_usd", "scale_to_zero_usd", "always_warm_if_billed_whole_time_usd", "basis"], rows)

# ------------------------------------------------------------------ 5. capacity what-if: clock speed and core count
inst = list(csv.DictReader(open(os.path.join(HERE, "instances.csv"), newline="")))
fam = {}
for r in inst:
    if r["measured_parakeet_streams_per_vcpu"] and r["family"] not in fam:
        fam[r["family"]] = dict(spv=float(r["measured_parakeet_streams_per_vcpu"]), ghz=float(r["clock_all_core_ghz"]), ipc=float(r["ipc_vs_i9"]), cpu=r["cpu"], inst=r["instance"])
derate = cs.P["measured_derate"]
rows = []
for f, d in fam.items():
    k = d["spv"] / (d["ghz"] * d["ipc"])                           # streams per vCPU per GHz of clock x IPC, from the measurement
    for ghz in CLOCKS:
        for v in VCPUS:
            eff = 1.0 if v <= 24 else max(0.0, 1 - SATURATION_PER_DOUBLING * math.log2(v / 24))
            knee = v * k * ghz * d["ipc"] * eff
            rows.append((f, ghz, v, round(knee, 2), round(knee * derate, 2), "modelled"))
    rows.append((f, d["ghz"], 24, round(24 * d["spv"], 2), round(24 * d["spv"] * derate, 2), "measured"))
write("cloudflare_scen_capacity_whatif.csv", f"""Live streams on one server as the clock speed and the number of vCPUs change. status: modelled; the rows with basis=measured are the knees we measured on EC2 (streams per vCPU at the knee, times 24 vCPUs) at the clock listed in instances.csv.
Model: streams per vCPU = K x clock(GHz) x IPC, with K fitted so that the line passes through the measured point of each CPU family (c8g Graviton4, c7a AMD, c7i Intel, 1 vCPU = 1 thread on Intel); streams scale linearly with vCPUs up to 24 and lose {int(SATURATION_PER_DOUBLING * 100)}% per doubling above 24 (shared final-pass pool, assumption, not measured). planned = knee x {derate} (planning derate). Clock x IPC is the same estimate the cost model uses (instances.csv). Re-run: python3 docs/data/scenarios.py""",
      ["family", "clock_ghz", "vcpus", "streams_at_knee", "streams_planned", "basis"], rows)
# ------------------------------------------------------------------ 6. latency budget of the edge hop
FIRST_PARTIAL_S = 0.95        # measured median first partial after speech starts (PERFORMANCE.md)
HOP_MS = (10, 60)             # assumption: extra Worker, Durable Object and container legs, per direction (not measured)
rows = [("direct to the service", "measured", FIRST_PARTIAL_S, 0, FIRST_PARTIAL_S, "median first partial after speech starts")]
for label, ms in (("low", HOP_MS[0]), ("high", HOP_MS[1])):
    extra = round(2 * ms / 1000, 3)
    rows.append((f"through the Cloudflare edge: {label}", "modelled", FIRST_PARTIAL_S, extra, round(FIRST_PARTIAL_S + extra, 3), f"{ms} ms each way"))
write("cloudflare_latency_budget.csv", """Time to the first partial (seconds): the service alone, and with the extra network legs of a Cloudflare route. The service figure is measured (0.95 s median, 24-vCPU layout, PERFORMANCE.md). The extra path is modelled: an assumed 10 to 60 ms each way for the Worker, Durable Object and container legs (not measured); only the client to edge connect was measured (21 to 59 ms, three samples, 2026-12-05). Re-run: python3 docs/data/scenarios.py""",
      ["path", "status", "service_first_partial_s", "extra_path_s", "total_s", "note"], rows)
print("wrote cloudflare_scen_*.csv and cloudflare_latency_budget.csv")
