#!/usr/bin/env python3
"""Warm-pool simulation for the base-plus-burst design (docs/CLOUDFLARE-SERVERLESS.md section 7): one campaign day, one-minute steps,
a fluid model of streams. Writes cloudflare_burst_day.csv (every 5 minutes) and prints the day's totals. status: modelled (a model, not a measurement).

    python3 docs/data/burst_sim.py

Model: the base carries BASE streams (6 Graviton4 units of 4). A controller looks at demand extrapolated LEAD minutes ahead; when that passes THRESH of the base it
starts enough burst instances (4 streams each) to cover the forecast plus one spare. An instance serves calls only after LEAD minutes (start, health check, test
transcript). Instances beyond what the load needs for DRAIN minutes are released, one a minute. Calls the base and the ready burst instances cannot take go to the hosted provider."""
import csv, math, os

HERE = os.path.dirname(os.path.abspath(__file__))
P = {}
with open(os.path.join(HERE, "costs.csv"), newline="") as f:
    for r in csv.DictReader(l for l in f if not l.startswith("#")):
        try: P[r["key"]] = float(r["value"])
        except ValueError: pass
BASE_UNITS, UNIT_STREAMS = 6, 4.0
BASE = BASE_UNITS * UNIT_STREAMS            # 24 streams
THRESH = P["hy_base_threshold"]             # 0.65
LEAD = int(P["hy_warm_lead_ec2_min"])       # 2 minutes
DRAIN = int(P["hy_drain_min"])              # 2 minutes
SPOT_H = 0.349 / 4                          # c8g.xlarge spot, scaled from the 4xlarge third-party figure (costs.csv note)
OD_H = 0.15952                              # c8g.xlarge on-demand
DG_H = P["dg_nova3_mono_stream_payg"] * 60


def make_demand(ramp_min=20, flash=True):
    """streams at minute t of the day: a business-day shape, a campaign from 12:40 to 16:20 at about four times the load with ramps of ramp_min minutes, and (optionally) a flash crowd at 14:30"""
    def demand(t):
        h = t / 60
        day = 0.0
        if 8 <= h < 18:
            day = 5 + 6 * math.sin((h - 8) / 10 * math.pi)             # 5 to 11 streams
        day += 3 * max(0.0, 1 - abs(h - 12.5) / 4)
        if 12.67 <= h < 16.33:
            ramp = min(1.0, (h - 12.67) * 60 / ramp_min, (16.33 - h) * 60 / ramp_min)
            day += 28 * ramp                                            # campaign plateau about 40 streams
        if flash and 14.5 <= h < 14.6:
            day += 30                                                   # flash crowd: 30 more streams for 6 minutes
        return day + 0.5
    return demand


demand = make_demand()


def simulate(thresh=THRESH, lead=LEAD, drain=DRAIN, base_units=BASE_UNITS, unit_streams=UNIT_STREAMS, demand_fn=demand):
    """one day in one-minute steps; returns (per-minute rows, totals). A row is (demand, base_served, burst_served, hosted, ready, starting)."""
    base = base_units * unit_streams
    ready, starting, idle, hist, minutes = 0, [], 0, [], []
    tot = {"demand": 0.0, "base": 0.0, "burst": 0.0, "hosted": 0.0, "inst_min": 0.0, "starts": 0}
    for t in range(0, 1440):
        d = demand_fn(t); hist.append(d)
        slope = (d - hist[max(0, len(hist) - 6)]) / min(5, len(hist) - 1 or 1)
        forecast = d + max(0.0, slope) * lead
        starting = [x - 1 for x in starting]
        arrived = sum(1 for x in starting if x <= 0)
        starting = [x for x in starting if x > 0]
        ready += arrived
        want = 0
        if forecast > thresh * base:   # past the threshold: one spare instance is warmed; the forecast overflow is covered in full, plus a second spare near full
            want = math.ceil(max(0.0, forecast - base) / unit_streams) + 1 + (1 if forecast > base * 0.95 else 0)
        if want > ready + len(starting):
            n_new = want - ready - len(starting); starting += [max(1, round(lead))] * n_new; tot["starts"] += n_new
        base_served = min(d, base)
        burst_served = min(max(0.0, d - base), ready * unit_streams)
        hosted = max(0.0, d - base - burst_served)
        need_now = math.ceil(max(0.0, forecast - base) / unit_streams) + (1 if forecast > thresh * base else 0) + (1 if forecast > 0.95 * base else 0)
        if ready > need_now:   # more instances than the load needs: release one per minute after `drain` minutes of surplus
            idle += 1
            if idle >= drain: ready -= 1
        else:
            idle = 0
        minutes.append((d, base_served, burst_served, hosted, ready, len(starting)))
        tot["demand"] += d; tot["base"] += base_served; tot["burst"] += burst_served; tot["hosted"] += hosted; tot["inst_min"] += ready + len(starting)
    return minutes, tot


def costs_of(tot, base_units=BASE_UNITS, peak=None):
    sh = {k: v / 60 for k, v in tot.items() if k != "starts"}
    return {"base": base_units * OD_H * 24, "burst": sh["inst_min"] * SPOT_H, "hosted": sh["hosted"] * DG_H, "stream_hours": sh}


if __name__ == "__main__":
    minutes, tot = simulate()
    rows, win = [], []
    for t, m in enumerate(minutes):
        win.append(m)
        if t % 5 == 4:   # one row per 5 minutes: the mean of the five one-minute values (counts: the largest)
            t0 = t - 4; n = len(win); mean = lambda i: sum(w[i] for w in win) / n
            rows.append((t0, f"{t0 // 60:02d}:{t0 % 60:02d}", round(mean(0), 2), round(mean(1), 2), round(mean(2), 2), round(mean(3), 2), round(100 * mean(1) / BASE, 1), max(w[4] for w in win), max(w[5] for w in win)))
            win = []
    with open(os.path.join(HERE, "cloudflare_burst_day.csv"), "w", newline="") as f:
        f.write("# One campaign day of the base-plus-burst design, simulated by burst_sim.py (status: modelled; a fluid model of streams, not a measurement). Base 24 streams (six 4-stream Graviton4 units), burst instances of 4 streams ready 2 minutes after start, released after 2 idle minutes, hosted provider for the rest. Rows are 5-minute means (instance counts: the largest in the window).\n")
        f.write("minute,clock,demand_streams,base_served,burst_served,hosted_served,base_utilisation_pct,burst_ready,burst_starting\n")
        for r in rows: f.write(",".join(str(x) for x in r) + "\n")
    c = costs_of(tot); sh = c["stream_hours"]
    peak = max(m[0] for m in minutes); units_peak = math.ceil(peak / UNIT_STREAMS)
    print(f"peak demand {peak:.0f} streams; stream-hours: base {sh['base']:.1f}, burst {sh['burst']:.1f}, hosted {sh['hosted']:.1f} of {sh['demand']:.1f}")
    print(f"burst instance-hours {sh['inst_min']:.1f}; day cost: hybrid ${c['base'] + c['burst'] + c['hosted']:.0f} (base ${c['base']:.0f}, burst ${c['burst']:.0f}, hosted ${c['hosted']:.0f}); fleet sized for the peak ({units_peak} units) ${units_peak * OD_H * 24:.0f}; all Deepgram ${sh['demand'] * DG_H:.0f}")
