#!/usr/bin/env python3
"""Cost and capacity model for unidatum-speech. Reads costs.csv and instances.csv, rewrites the generated
tables inside docs/COSTS.md (between <!-- BEGIN:name --> and <!-- END:name --> markers) and the charts in docs/img/.

    python3 docs/data/costs.py            # needs matplotlib for the charts; tables work without it
    python3 docs/data/costs.py --no-charts

Change a price or an assumption in costs.csv / instances.csv, re-run, commit the doc and the PNGs."""
import csv, math, os, re, sys

HERE = os.path.dirname(os.path.abspath(__file__))
DOC = os.path.join(HERE, "..", "COSTS.md")
IMG = os.path.join(HERE, "..", "img")

# ---------------------------------------------------------------- inputs
P = {}
with open(os.path.join(HERE, "costs.csv"), newline="") as f:
    for row in csv.DictReader(l for l in f if not l.startswith("#")):
        try:
            P[row["key"]] = float(row["value"])
        except ValueError:
            pass  # text values (e.g. an instance type) are read through P_STR
INST = {}
with open(os.path.join(HERE, "instances.csv"), newline="") as f:
    for row in csv.DictReader(f):
        INST[row["instance"]] = row
REGIONS = ["us_east_1", "us_east_2", "us_west_2"]

P_STR = {}
with open(os.path.join(HERE, "costs.csv"), newline="") as f:
    for row in csv.DictReader(l for l in f if not l.startswith("#")):
        P_STR[row["key"]] = row["value"]
UTIL = P["util_target"]
ROUTES = {"parakeet": P["cpu_s_per_audio_s_parakeet"], "whisper": P["cpu_s_per_audio_s_whisper"],
          "fast": P["cpu_s_per_audio_s_fast_only"]}
H_ON, H_BIZ = P["hours_always_on"], P["hours_business"]


def price(t, mode="od", region="us_east_1"):
    if mode == "spot":
        return float(INST[t]["spot_use1_vantage"])
    return float(INST[t][f"{mode}_{region}"])


def vcpu(t): return float(INST[t]["vcpu"])
REF_GHZ = P["i9_ref_ghz"]
SMT_SHARE = P["smt_vcpu_share"]


def core_factor(t, clock="all"):
    """speed of one core of this type against one i9-14900K P-core (= 1.0): clock ratio x IPC ratio (estimate).
    'all' uses the all-core clock (a busy instance), 'max' the max-turbo clock (one stream on a quiet instance)"""
    i = INST[t]
    ghz = float(i["clock_all_core_ghz"] if clock == "all" else i["clock_max_ghz"])
    return ghz / REF_GHZ * float(i["ipc_vs_i9"])


def vfac(t):
    """i9 threads per vCPU on a busy instance: core factor, times the SMT share where a vCPU is a hyperthread"""
    return core_factor(t) * (SMT_SHARE if int(INST[t]["smt"]) else 1.0)


def lat_fac(t):
    """single-thread speed against the i9 for one stream on a lightly loaded instance (max turbo, SMT sibling idle)"""
    return core_factor(t, "max")


def measured(t, key):
    """measured streams (or speakers) per vCPU from the EC2 runs of 2026-12-05, or None for a type that was not run"""
    v = INST[t].get(key, "")
    return float(v) if v else None


def streams(t, route="parakeet", util=UTIL):
    """concurrent full channels one instance carries: for c7a and c7i the measured knee per vCPU times the planning derate;
    for the other types the estimate (clock x IPC) at the CPU utilisation target"""
    m = measured(t, {"parakeet": "measured_parakeet_streams_per_vcpu", "whisper": "measured_whisper_streams_per_vcpu"}.get(route, ""))
    if m is not None:
        return vcpu(t) * m * P["measured_derate"]
    return vcpu(t) * vfac(t) * util / (ROUTES[route] * P["overhead_os"] * P["speech_duty"])


def tts_speakers(t, util=UTIL):
    m = measured(t, "measured_tts_speakers_per_vcpu")
    if m is not None:
        return vcpu(t) * m
    return vcpu(t) * vfac(t) * util / (P["cpu_s_per_audio_s_tts"] * P["overhead_os"])


def var_per_stream_hour():
    """load balancer bytes dimension + egress, per connected stream-hour"""
    lcu = P["audio_bytes_per_hour"] / P["aws_alb_lcu_bytes_per_hour"] * P["aws_alb_lcu_hour"]
    egress = P["stt_egress_bytes_per_hour"] / 1e9 * P["aws_dto_gb"]
    return lcu + egress


def fixed_per_instance_hour(n_fleet=2):
    ebs = P["ebs_gb"] * P["aws_ebs_gp3_gb_month"] / H_ON
    alb = (P["aws_alb_hour"] + 2 * P["aws_ipv4_hour"] + P["cloudwatch_month"] / H_ON) / n_fleet
    return ebs + alb


def ops_month(n):
    return (P["ops_hours_base"] + P["ops_hours_per_instance"] * n) * P["ops_rate"]


def usd(x, d=2):
    if x >= 1000: return f"${x:,.0f}"
    if x >= 100: return f"${x:,.0f}"
    if x >= 10: return f"${x:.1f}"
    return f"${x:.{d}f}"


def usd4(x): return f"${x:.4f}" if x < 0.1 else f"${x:.3f}"


def md(headers, rows, align=None):
    def num(col):
        vals = [str(r[col]) for r in rows]
        return sum(v[:1] in "$0123456789" for v in vals) > len(vals) / 2
    out = ["| " + " | ".join(headers) + " |",
           "|" + "|".join("---" if c == 0 or not num(c) else "---:" for c in range(len(headers))) + "|"]
    out += ["| " + " | ".join(str(c) for c in r) + " |" for r in rows]
    return "\n".join(out)


T = {}

# ---------------------------------------------------------------- capacity
order = ["c7i.xlarge", "c7i.2xlarge", "c7i.4xlarge", "c7i.8xlarge", "m7i.4xlarge", "c8i.4xlarge", "c6i.4xlarge",
         "c7a.4xlarge", "c8a.4xlarge", "c7g.4xlarge", "c8g.4xlarge"]
rows = []
for t in order:
    i = INST[t]
    rows.append([t, i["cpu"], int(vcpu(t)), i["mem_gib"], f'{vfac(t):.2f}', f"{streams(t):.1f}",
                 f"{streams(t) / vcpu(t):.2f}", f"{streams(t, 'whisper'):.1f}", f"{streams(t, 'fast'):.1f}",
                 f"{tts_speakers(t):.1f}"])
T["capacity"] = md(["Instance", "CPU", "vCPU", "GiB", "i9-thread per vCPU", "English Parakeet streams", "per vCPU",
                    "Whisper-small streams", "Fast-only streams", "Kokoro speakers"], rows)

# ---------------------------------------------------------------- clock, IPC, latency
clk_rows = []
for t in ["c6i.4xlarge", "c7i.4xlarge", "c8i.4xlarge", "c7a.4xlarge", "c8a.4xlarge", "c7g.4xlarge", "c8g.4xlarge"]:
    i = INST[t]
    clk_rows.append([t, f'{float(i["clock_all_core_ghz"]):.1f} / {float(i["clock_max_ghz"]):.1f}', f'{float(i["ipc_vs_i9"]):.2f}',
                     f"{core_factor(t):.2f}", f"{core_factor(t, 'max'):.2f}", "yes" if int(i["smt"]) else "no", f"{vfac(t):.2f}"])
clk_rows.insert(0, ["i9-14900K P-core (measured)", f"{REF_GHZ:.1f} / 6.0", "1.00", "1.00", "1.00", "yes (idle sibling)", "1.00"])
T["clock_factors"] = md(["Instance (or reference)", "Clock GHz all-core / max", "IPC vs i9 (estimate)", "Core speed, busy (all-core x IPC)",
                         "Core speed, one stream (max x IPC)", "vCPU is a hyperthread", "i9 threads per vCPU (busy)"], clk_rows)

EP, PP = "ecore_parakeet_cores_1", "pcore_parakeet_cores_1"
cal = []
for lab, e, p_, el, pl in [("Parakeet, 1 stream", "ecore_parakeet_cores_1", "pcore_parakeet_cores_1", "ecore_parakeet_lag_1", "pcore_parakeet_lag_1"),
                           ("Whisper small, 1 stream", "ecore_whisper_cores_1", "pcore_whisper_cores_1", "ecore_whisper_lag_1", "pcore_whisper_lag_1")]:
    cpu_speed = P[p_] / P[e]
    lag_speed = (P[pl] - P["endpoint_s"]) / (P[el] - P["endpoint_s"])
    cal.append([lab, f"{P[p_]:.2f} / {P[e]:.2f}", f"{cpu_speed:.2f}", f"{P[pl]:.2f} / {P[el]:.2f} s", f"{lag_speed:.2f}",
                f"{cpu_speed / (P['i9_ecore_ghz'] / 5.7):.2f}"])
T["ecore_calibration"] = md(["Measured, same code, one core type against the other", "Cores busy P / E", "CPU speed of E-core vs P-core",
                             "Final lag P / E", "Speed of the compute part of the lag", "Implied IPC of E-core (CPU speed / 0.77 clock)"], cal)

lrows = []
for t in ["c6i.4xlarge", "c7i.4xlarge", "c8i.4xlarge", "c7a.4xlarge", "c8a.4xlarge", "c7g.4xlarge", "c8g.4xlarge"]:
    L, B = lat_fac(t), vfac(t)
    def lag(idle, f, k=1.0):
        return P["endpoint_s"] + (idle - P["endpoint_s"]) / (f ** k)
    lrows.append([t,
                  f"{lag(P['final_lag_parakeet_idle_s'], L):.2f} - {lag(P['final_lag_parakeet_idle_s'], L, 1.5):.2f} s",
                  f"{lag(P['final_lag_parakeet_idle_s'], B):.2f} s",
                  f"{lag(P['final_lag_whisper_idle_s'], L):.2f} s",
                  f"{P['cpu_s_per_audio_s_tts'] / L:.2f}", f"{P['tts_first_audio_s'] / L:.2f} s"])
lrows.insert(0, ["i9-14900K desktop i9-14900K (measured)", f"{P['final_lag_parakeet_idle_s']:.2f} s", "0.87 s (8 streams)", f"{P['final_lag_whisper_idle_s']:.2f} s", f"{P['cpu_s_per_audio_s_tts']:.2f}", f"{P['tts_first_audio_s']:.2f} s"])
T["latency"] = md(["Instance", "Parakeet final lag, one stream (best - pessimistic)", "Parakeet lag at the 65% load point (best)", "Whisper small final lag, one stream (best)",
                   "Kokoro RTF, 1 thread", "Kokoro first audio"], lrows)

# ---------------------------------------------------------------- prices and $/stream-hour
rows = []
for t in order:
    s = streams(t)
    od, s1, s3 = price(t), price(t, "sp1y"), price(t, "sp3y")
    sp = INST[t]["spot_use1_vantage"]
    rows.append([t, usd4(od), usd4(s1), usd4(s3), usd4(float(sp)) if sp else "n/a",
                 usd4(od / s), usd4(s1 / s), usd4(s3 / s), usd4(float(sp) / s) if sp else "n/a"])
T["prices"] = md(["Instance", "On-demand $/h", "1-yr Compute SP", "3-yr Compute SP", "Spot (Vantage, estimate)",
                  "$/stream-h on-demand", "1-yr SP", "3-yr SP", "Spot"], rows)

rows = []
for t in ["c7i.4xlarge", "c7a.4xlarge", "c8g.4xlarge", "c7g.4xlarge", "c8i.4xlarge", "c6i.4xlarge"]:
    rows.append([t] + [f"{usd4(price(t, 'od', r))} / {usd4(price(t, 'sp1y', r))}" for r in REGIONS])
T["regions"] = md(["Instance", "us-east-1 (od / 1-yr SP)", "us-east-2", "us-west-2"], rows)

# ---------------------------------------------------------------- utilisation tables
CONFIGS = [("c7a.4xlarge", "od", "AMD Zen 4, on-demand"), ("c7a.4xlarge", "sp1y", "AMD Zen 4, 1-yr SP"),
           ("c8a.4xlarge", "od", "AMD Zen 5, on-demand"), ("c8a.4xlarge", "sp1y", "AMD Zen 5, 1-yr SP"),
           ("c8a.4xlarge", "sp3y", "AMD Zen 5, 3-yr SP"), ("c8g.4xlarge", "od", "Graviton4, on-demand"),
           ("c8g.4xlarge", "sp1y", "Graviton4, 1-yr SP"), ("c8g.4xlarge", "sp3y", "Graviton4, 3-yr SP"),
           ("c7i.4xlarge", "od", "Intel, on-demand")]
UTILS = [0.10, 0.30, 0.60, 0.90]


def per_stream_hour(t, mode, u, eff_hours=1.0, with_overhead=True, route="parakeet"):
    """$ per connected stream-hour when `u` of the provisioned channels are busy; eff_hours scales u when the instance
    runs more hours than the traffic exists (always-on with business-hours traffic)"""
    cap = streams(t, route)
    h = price(t, mode) + (fixed_per_instance_hour() if with_overhead else 0)
    return h / (cap * u * eff_hours) + (var_per_stream_hour() if with_overhead else 0)


rows = []
for t, mode, label in CONFIGS:
    rows.append([f"{t} {label}", f"{streams(t):.1f}", usd4(price(t, mode)) + "/h"] +
                [f"{usd4(per_stream_hour(t, mode, u))}" for u in UTILS])
T["util_stream_hour"] = md(["Config", "Streams", "Instance"] + [f"{int(u * 100)}% busy" for u in UTILS], rows)

rows = []
for t, mode, label in CONFIGS:
    rows.append([f"{t} {label}"] + [f"${per_stream_hour(t, mode, u) / 60 * 1000:.2f}" for u in UTILS])
dg_pay = P["dg_nova3_mono_stream_payg"] * 1000
dg_gr = P["dg_nova3_mono_stream_growth"] * 1000
rows.append(["Deepgram Nova-3 PAYG (any utilisation)"] + [f"${dg_pay:.2f}"] * 4)
rows.append(["Deepgram Nova-3 Growth (any utilisation, after the $4,000/yr commitment)"] + [f"${dg_gr:.2f}"] * 4)
T["util_1000min"] = md(["Config, scheduled on only when needed"] + [f"{int(u * 100)}% busy" for u in UTILS], rows)

# utilisation at which one instance costs the same per 1,000 minutes as Deepgram (the lines in the chart cross the flat Deepgram lines here)
rows = []
for t, mode, label in CONFIGS:
    cells = []
    for dg in (dg_pay, dg_gr):
        target = dg / 1000 * 60 - var_per_stream_hour()      # $ per stream-hour left for the instance
        u_be = (price(t, mode) + fixed_per_instance_hour()) / (streams(t) * target)
        cells.append(f"{u_be * 100:.0f}%")
    rows.append([f"{t} {label}"] + cells)
T["util_breakeven"] = md(["Config", "Cheaper than Deepgram PAYG above this utilisation", "Cheaper than Deepgram Growth above this utilisation"], rows)

BIZ = H_BIZ / H_ON
rows = []
for t, mode, label in [CONFIGS[0], CONFIGS[2], CONFIGS[3]]:
    for name, eff in [("always-on", BIZ), ("business hours only", 1.0)]:
        rows.append([f"{t} {label}", name] + [f"${per_stream_hour(t, mode, u, eff) / 60 * 1000:.2f}" for u in UTILS])
T["always_vs_biz"] = md(["Config", "Run pattern"] + [f"{int(u * 100)}% busy while open" for u in UTILS], rows)

# overhead explainer
t0 = "c8g.4xlarge"
T["overhead"] = md(["Item", "Basis", "Cost"], [
    ["EBS gp3", f"{int(P['ebs_gb'])} GB per instance x ${P['aws_ebs_gp3_gb_month']}/GB-month", f"${P['ebs_gb'] * P['aws_ebs_gp3_gb_month']:.2f}/month each"],
    ["Application load balancer", f"${P['aws_alb_hour']}/h + 2 public IPv4 at ${P['aws_ipv4_hour']}/h each", f"${(P['aws_alb_hour'] + 2 * P['aws_ipv4_hour']) * H_ON:.0f}/month per fleet"],
    ["ALB capacity units", f"audio is 115 MB per stream-hour, 1 GB/h per LCU, ${P['aws_alb_lcu_hour']}/LCU-h", f"${P['audio_bytes_per_hour'] / P['aws_alb_lcu_bytes_per_hour'] * P['aws_alb_lcu_hour']:.4f} per stream-hour"],
    ["Egress to the internet", f"about 1 kB/s of JSON back, ${P['aws_dto_gb']}/GB after 100 GB free", f"${P['stt_egress_bytes_per_hour'] / 1e9 * P['aws_dto_gb']:.4f} per stream-hour"],
    ["Audio in", "inbound data transfer", "free"],
    ["Logs and metrics", "assumption", f"${P['cloudwatch_month']:.0f}/month per fleet"],
    ["Transcript retention", "1 day, a few MB: S3 $0.023/GB-month", "under $0.01/month"],
    ["Operations", f"{P['ops_hours_base']:g} h/month + {P['ops_hours_per_instance']:g} h per instance at ${P['ops_rate']:.0f}/h", f"${ops_month(2):.0f}/month for a 2-instance fleet"],
])

# ---------------------------------------------------------------- Deepgram
T["deepgram"] = md(["Product (streaming unless noted)", "Pay as you go", "Growth", "Per audio hour (PAYG)"], [
    ["Nova-3 monolingual, per min", f"${P['dg_nova3_mono_stream_payg']}", f"${P['dg_nova3_mono_stream_growth']}", usd(P['dg_nova3_mono_stream_payg'] * 60, 3)],
    ["Nova-3 multilingual, per min", f"${P['dg_nova3_multi_stream_payg']}", f"${P['dg_nova3_multi_stream_growth']}", usd(P['dg_nova3_multi_stream_payg'] * 60, 3)],
    ["Flux English, per min", f"${P['dg_flux_en_stream_payg']}", f"${P['dg_flux_en_stream_growth']}", usd(P['dg_flux_en_stream_payg'] * 60, 3)],
    ["Nova-2, per hour (hourly price only, existing deployments)", f"${P['dg_nova2_stream_hour_payg']}", "about 12.5% lower", usd(P['dg_nova2_stream_hour_payg'], 3)],
    ["Nova-3 monolingual pre-recorded, per min", f"${P['dg_nova3_mono_pre_payg']}", f"${P['dg_nova3_mono_pre_growth']}", usd(P['dg_nova3_mono_pre_payg'] * 60, 3)],
    ["Nova-3 multilingual pre-recorded, per min", f"${P['dg_nova3_multi_pre_payg']}", f"${P['dg_nova3_multi_pre_growth']}", usd(P['dg_nova3_multi_pre_payg'] * 60, 3)],
    ["Whisper Large pre-recorded, per min", f"${P['dg_whisper_large_pre']}", f"${P['dg_whisper_large_pre']}", usd(P['dg_whisper_large_pre'] * 60, 3)],
    ["Keyterm prompting add-on, per min", f"+${P['dg_keyterm_min']}", "+$0.0011", usd(P['dg_keyterm_min'] * 60, 3)],
    ["Aura-2 TTS, per 1,000 chars", f"${P['dg_aura2_1k_payg']}", f"${P['dg_aura2_1k_growth']}", usd(P['dg_aura2_1k_payg'] * P['tts_chars_per_audio_hour'] / 1000, 2)],
    ["Aura-1 TTS, per 1,000 chars", f"${P['dg_aura1_1k_payg']}", "$0.0135", usd(P['dg_aura1_1k_payg'] * P['tts_chars_per_audio_hour'] / 1000, 2)],
])

# ---------------------------------------------------------------- batch / serverless
vcpus_l = P["lambda_mem_gb"] * 1024 / 1769
lam_eff = vcpus_l * vfac("c7i.4xlarge") * P["lambda_parallel_eff"]
lam_sec_per_audio_s = P["cpu_s_per_audio_s_batch_parakeet"] * P["overhead_os"] / lam_eff
lam_per_audio_min = 60 * lam_sec_per_audio_s * P["lambda_mem_gb"] * P["aws_lambda_gb_s"] + P["aws_lambda_req_million"] / 1e6
c = "c8g.4xlarge"
ec2_batch_hours_per_hour = vcpu(c) * vfac(c) * 0.9 / (P["cpu_s_per_audio_s_batch_parakeet"] * P["overhead_os"])
ec2_batch_min_od = price(c) / (ec2_batch_hours_per_hour * 60)
ec2_batch_min_spot = price(c, "spot") / (ec2_batch_hours_per_hour * 60)
cf_ref = P_STR["cf_container_ref_type"]
cf_cpu_s_batch = P["cpu_s_per_audio_s_batch_parakeet"] * P["overhead_os"] / vfac(cf_ref)  # vCPU-seconds per audio second
cf_batch_min = 60 * cf_cpu_s_batch * P["cf_container_vcpu_s"] + (60 * cf_cpu_s_batch / 4 * (P["cf_container_custom_gib"] * P["cf_container_gib_s"] + 20 * P["cf_container_disk_gb_s"]))
T["batch"] = md(["Option (pre-recorded audio)", "$ per audio minute", "$ per 1,000 audio minutes", "Status of the number"], [
    ["Deepgram Nova-3 PAYG", f"${P['dg_nova3_mono_pre_payg']}", f"${P['dg_nova3_mono_pre_payg'] * 1000:.2f}", "published"],
    ["Deepgram Nova-3 Growth", f"${P['dg_nova3_mono_pre_growth']}", f"${P['dg_nova3_mono_pre_growth'] * 1000:.2f}", "published"],
    ["Deepgram Whisper Large", f"${P['dg_whisper_large_pre']}", f"${P['dg_whisper_large_pre'] * 1000:.2f}", "published"],
    ["Amazon Transcribe batch", f"${P['aws_transcribe_batch_min']}", f"${P['aws_transcribe_batch_min'] * 1000:.2f}", "from AWS's own example; tiers not read"],
    ["Cloudflare Workers AI Whisper (large-v3-turbo)", f"${P['cf_wai_whisper_min']}", f"${P['cf_wai_whisper_min'] * 1000:.2f}", "published; audio leaves our machines"],
    ["Our service on Lambda, Parakeet, container image", f"${lam_per_audio_min:.5f}", f"${lam_per_audio_min * 1000:.2f}", "estimate from our CPU numbers; no cold-start or idle cost"],
    ["Our service on c8g.4xlarge on-demand, queue, 90% busy", f"${ec2_batch_min_od:.5f}", f"${ec2_batch_min_od * 1000:.2f}", "estimate"],
    ["Our service on a Cloudflare container (4 vCPU / 8 GiB, scale-to-zero, queue)", f"${cf_batch_min:.5f}", f"${cf_batch_min * 1000:.2f}", "estimate; amd64 only, vCPU speed not stated, needs the proof"],
    ["Same on spot", f"${ec2_batch_min_spot:.5f}", f"${ec2_batch_min_spot * 1000:.2f}", "estimate; spot price is third party"],
])

# streaming on serverless
msg_h = 36000 + 14400  # 100 ms audio chunks in, replies out
apigw = msg_h / 1e6 * P["aws_apigw_ws_msg_million"] + 60 * P["aws_apigw_ws_conn_min_million"] / 1e6
lam_inv = 36000 / 1e6 * P["aws_lambda_req_million"]
cpu_s_h = P["cpu_s_per_audio_s_parakeet"] * P["overhead_os"] * 3600
lam_compute = cpu_s_h / vfac("c7i.4xlarge") * 1.727 * P["aws_lambda_gb_s"]
lam_stream_total = apigw + lam_inv + lam_compute
fg_x86 = 16 * P["aws_fargate_vcpu_hour_x86"] + 32 * P["aws_fargate_gb_hour_x86"]
fg_arm = 16 * P["aws_fargate_vcpu_hour_arm"] + 32 * P["aws_fargate_gb_hour_arm"]
fg_x86_streams = 16 * vfac("c7i.4xlarge") * UTIL / (ROUTES["parakeet"] * P["overhead_os"])
fg_arm_streams = 16 * vfac("c7g.4xlarge") * UTIL / (ROUTES["parakeet"] * P["overhead_os"])
ar_h = 4 * P["aws_apprunner_vcpu_hour"] + 12 * P["aws_apprunner_gb_hour"]
ar_streams = 4 * vfac("c7i.4xlarge") * UTIL / (ROUTES["parakeet"] * P["overhead_os"])
# Cloudflare Containers bill CPU on active use, memory and disk on what is provisioned (pricing page, 2026-11-13)
cf_ref = P_STR["cf_container_ref_type"]
cf_gib = P["cf_container_custom_gib"]
cf_cpu_s_stream = 1 / measured(cf_ref, "measured_parakeet_streams_per_vcpu")   # vCPU-seconds per audio second at the measured knee (c7a-like vCPU)
cf_prov_h = cf_gib * P["cf_container_gib_s"] * 3600 + 20 * P["cf_container_disk_gb_s"] * 3600  # memory + disk, per container-hour
cf_streams = P["cf_streams_per_container"]
cf_h = cf_prov_h + cf_streams * cf_cpu_s_stream * 3600 * P["cf_container_vcpu_s"]            # one container-hour with its streams all busy
ec2_ref = price("c7i.4xlarge") / streams("c7i.4xlarge")
T["serverless_stream"] = md(["Platform (live streaming)", "Hourly cost of one unit", "Streams per unit", "$ per stream-hour at 100% of capacity", "Fit for live STT"], [
    ["EC2 c7i.4xlarge on-demand (reference)", usd4(price("c7i.4xlarge")), f"{streams('c7i.4xlarge'):.1f}", usd4(ec2_ref), "yes, tested design"],
    ["ECS on EC2", "same as EC2", "same", usd4(ec2_ref), "yes; the same box, with autoscaling and rolling deploys"],
    ["Fargate x86, 16 vCPU / 32 GB", usd4(fg_x86), f"{fg_x86_streams:.1f} (assumes c7i-like vCPU)", usd4(fg_x86 / fg_x86_streams), "yes; WebSockets through an ALB; no instance to patch"],
    ["Fargate Arm, 16 vCPU / 32 GB", usd4(fg_arm), f"{fg_arm_streams:.1f} (assumes Graviton3-like)", usd4(fg_arm / fg_arm_streams), "yes, same"],
    ["App Runner, 4 vCPU / 12 GB (largest)", usd4(ar_h), f"{ar_streams:.1f}", usd4(ar_h / ar_streams), "poor: small, and WebSocket support was not verified"],
    ["API Gateway WebSocket + Lambda (one invocation per audio chunk)", "per use", "1 per Lambda", usd4(lam_stream_total) + f" (gateway {usd4(apigw)}, invokes {usd4(lam_inv)}, compute {usd4(lam_compute)})", "no: decoder state cannot live between invocations; costs about 2x EC2"],
    ["Cloudflare Containers, custom 4 vCPU / 8 GiB (CPU billed on active use)", usd4(cf_h), f"{cf_streams:.0f} (c7a-like vCPU, not measured; 1 if c7i-like)", usd4(cf_h / cf_streams), "possible; 4 vCPU is the ceiling per instance; priced as 4 vCPU / 8 GiB custom; not measured on Cloudflare"],
])

# ---------------------------------------------------------------- TTS
rows = []
for t in ["c7a.4xlarge", "c8a.4xlarge", "c8g.4xlarge", "c7i.4xlarge"]:
    sp = tts_speakers(t)
    for u in (0.1, 0.3, 0.6, 0.9):
        pass
    rows.append([f"{t} on-demand, {sp:.1f} speakers"] + [
        f"${(price(t) + fixed_per_instance_hour()) / (sp * u) / (P['tts_chars_per_audio_hour'] / 1000) + P['tts_egress_bytes_per_hour'] / 1e9 * P['aws_dto_gb'] / (P['tts_chars_per_audio_hour'] / 1000):.4f}"
        for u in UTILS])
rows.append(["Deepgram Aura-2 PAYG (any utilisation)"] + [f"${P['dg_aura2_1k_payg']:.4f}"] * 4)
rows.append(["Deepgram Aura-2 Growth"] + [f"${P['dg_aura2_1k_growth']:.4f}"] * 4)
rows.append(["Deepgram Aura-1 PAYG"] + [f"${P['dg_aura1_1k_payg']:.4f}"] * 4)
rows.append(["Amazon Polly neural"] + [f"${P['aws_polly_neural_million_chars'] / 1000:.4f}"] * 4)
rows.append(["Cloudflare Workers AI MeloTTS ($0.0002 per audio minute)"] + [f"${P['cf_wai_melotts_min'] * 60 / (P['tts_chars_per_audio_hour'] / 1000):.4f}"] * 4)
T["tts"] = md(["Per 1,000 characters (our Kokoro includes PCM egress)"] + [f"{int(u * 100)}% busy" for u in UTILS], rows)

# ---------------------------------------------------------------- own hardware
pop_cap = P["streams_measured_pop_os_1_parakeet"]
mac_cap = P["streams_cap_mac_mini_m4"]
pop_amort = P["own_pop_os_1_price"] * P["own_pop_os_1_share"] / P["own_pop_os_1_life_months"]
pop_power = P["own_pop_os_1_watts"] / 1000 * H_ON * P["own_kwh"]
mac_amort = P["own_mac_mini_m4_price"] / P["own_mac_mini_life_months"]
mac_power = P["own_mac_mini_watts"] / 1000 * H_ON * P["own_kwh"]
rows = []
for name, cap, am, pw in [("i9-14900K desktop (half the machine)", pop_cap, pop_amort, pop_power), ("Mac mini M4", mac_cap, mac_amort, mac_power)]:
    rows.append([name, f"{cap:g} (measured)", usd(am), usd(pw), usd(am + pw), usd(pw)] +
                [usd4((am + pw) / (H_ON * cap * u)) for u in UTILS])
T["own"] = md(["Machine", "Streams", "Amortised/month", "Power/month", "Total/month", "Power only (already owned)"] +
              [f"$/stream-h at {int(u * 100)}%" for u in UTILS], rows)

# ---------------------------------------------------------------- sensitivity
VOLUMES = [10_000, 100_000, 1_000_000, 10_000_000]


def peak(M, window=H_BIZ):
    return P["peak_to_avg"] * M / 60 / window


def aws_month(fam, mode, M, hours, ha=True, ops=True, sizes=None, window=H_BIZ):
    best = None
    pk = peak(M, window)
    for t in INST:
        if not t.startswith(fam + ".") or (sizes and t.split(".")[1] not in sizes):
            continue
        n = max(math.ceil(pk / math.floor(streams(t))) if streams(t) >= 1 else 99, P["min_instances_ha"] if ha else 1)
        fleet_fixed = (P["aws_alb_hour"] + 2 * P["aws_ipv4_hour"]) * H_ON + P["cloudwatch_month"]
        cost = (n * price(t, mode) * hours + n * P["ebs_gb"] * P["aws_ebs_gp3_gb_month"] + fleet_fixed
                + (M / 60) * var_per_stream_hour() + (ops_month(n) if ops else 0))
        if best is None or cost < best[0]:
            best = (cost, t, n)
    return best[0], best[1], int(best[2])


def dg_month(M, tier):
    if tier == "payg":
        return M * P["dg_nova3_mono_stream_payg"], P["dg_conc_stt_payg"]
    return max(M * P["dg_nova3_mono_stream_growth"], P["dg_growth_commit_year"] / 12), P["dg_conc_stt_growth"]


def home_month(M, kind, owned, window=H_BIZ):
    cap, am, pw = (pop_cap, pop_amort, pop_power) if kind == "pop" else (mac_cap, mac_amort, mac_power)
    n = math.ceil(peak(M, window) / cap)
    return n * (pw if owned else am + pw), n


def sens_rows(ops, window=H_BIZ, options=None):
    rows = []
    options = options or [("c7a", "od", H_ON), ("c8a", "od", H_ON), ("c8a", "sp1y", H_ON), ("c8a", "od", H_BIZ)]
    for M in VOLUMES:
        pk = peak(M, window)
        row = [f"{M:,}", f"{pk:.1f}" if pk < 10 else f"{pk:.0f}"]
        for tier in ("payg", "growth"):
            cost, lim = dg_month(M, tier)
            row.append(usd(cost) + (" (over concurrency limit)" if pk > lim else ""))
        row.append(usd(M * P["cf_wai_nova3_ws_min"]))
        for fam, mode, hrs in options:
            c, t, n = aws_month(fam, mode, M, hrs, ops=ops, window=window)
            row.append(f"{usd(c)} ({n}x {t.split('.')[1]})")
        c, n = home_month(M, "pop", False, window)
        row.append(f"{usd(c)} ({n}x)")
        c, n = home_month(M, "mac", False, window)
        row.append(f"{usd(c)} ({n}x)")
        rows.append(row)
    return rows


H = ["Minutes/month", "Peak streams", "Deepgram PAYG", "Deepgram Growth", "Workers AI Nova-3 WS", "AWS c7a on-demand always-on",
     "AWS c8a on-demand always-on", "AWS c8a 1-yr SP always-on", "AWS c8a on-demand business-hours", "i9 desktop class (amortised)", "Mac mini M4 (amortised)"]
T["sens_ops"] = md(H, sens_rows(True))
T["sens_noops"] = md(H, sens_rows(False))
H247 = H[:]; H247[8] = "AWS c8a 3-yr SP always-on"
T["sens_247"] = md(H247, sens_rows(True, H_ON, [("c7a", "od", H_ON), ("c8a", "od", H_ON), ("c8a", "sp1y", H_ON), ("c8a", "sp3y", H_ON)]))


def breakeven(fam, mode, hours, ops, tier, window):
    for k in range(0, 4000):
        M = 1000 * (10 ** (k / 400))
        if M > 3e7: break
        if aws_month(fam, mode, M, hours, ops=ops, window=window)[0] < dg_month(M, tier)[0]:
            return M
    return None


def be(b): return f"{b / 1000:,.0f}k" if b else "never (under 30M)"


rows = []
for fam, mode, hrs, window, label in [
        ("c8a", "od", H_BIZ, H_BIZ, "traffic in business hours, c8a on-demand, scheduled on only 220 h"),
        ("c8a", "sp1y", H_ON, H_BIZ, "traffic in business hours, c8a 1-yr SP, always-on"),
        ("c8a", "od", H_ON, H_BIZ, "traffic in business hours, c8a on-demand, always-on"),
        ("c7a", "od", H_ON, H_ON, "traffic round the clock, c7a on-demand"),
        ("c8a", "od", H_ON, H_ON, "traffic round the clock, c8a on-demand"),
        ("c8a", "sp1y", H_ON, H_ON, "traffic round the clock, c8a 1-yr SP"),
        ("c8a", "sp3y", H_ON, H_ON, "traffic round the clock, c8a 3-yr SP"),
        ("c8g", "od", H_ON, H_ON, "traffic round the clock, c8g (Graviton4) on-demand"),
        ("c8g", "sp1y", H_ON, H_ON, "traffic round the clock, c8g 1-yr SP"),
        ("c8g", "sp3y", H_ON, H_ON, "traffic round the clock, c8g 3-yr SP"),
        ("c7i", "od", H_ON, H_ON, "traffic round the clock, c7i (Intel) on-demand")]:
    rows.append([label] + [be(breakeven(fam, mode, hrs, ops, tier, window)) for ops in (True, False) for tier in ("payg", "growth")])
T["breakeven"] = md(["Self-host on AWS (2 instances minimum for HA); first monthly volume where it is cheaper", "vs PAYG, with ops", "vs Growth, with ops", "vs PAYG, infra only", "vs Growth, infra only"], rows)


# ---------------------------------------------------------------- cloudflare containers: monthly model for live streams
def cf_always(M, window):
    """always-warm: n containers all month, sized for the peak (at least 2), CPU billed only for the audio actually decoded"""
    n = int(max(math.ceil(peak(M, window) / cf_streams), P["min_instances_ha"]))
    sec = H_ON * 3600
    mem = max(0, n * cf_gib * sec - P["cf_container_incl_gib_h"] * 3600) * P["cf_container_gib_s"]
    disk = max(0, n * 20 * sec - P["cf_container_incl_disk_gb_h"] * 3600) * P["cf_container_disk_gb_s"]
    cpu = max(0, M * 60 * cf_cpu_s_stream - P["cf_container_incl_vcpu_min"] * 60) * P["cf_container_vcpu_s"]
    do = max(0, (n + 1) * 0.125 * sec - P["cf_do_incl_gb_s"]) * P["cf_do_gb_s_million"] / 1e6   # one Durable Object per container plus a router, 128 MB, awake all month
    return P["cf_workers_paid_month"] + mem + disk + cpu + do, n


def cf_zero(M, window):
    """scale-to-zero: a container is billed while it has streams (packed at the fill factor) plus the inactivity tail after each wake-up"""
    stream_h = M / 60
    wakes = M / P["cf_session_min"] * P["cf_wake_fraction"]
    c_h = stream_h / (cf_streams * P["cf_fill"]) + wakes * P["cf_sleep_after_min"] / 60
    c_h = max(c_h, 0.0)
    sec = c_h * 3600
    mem = max(0, sec * cf_gib - P["cf_container_incl_gib_h"] * 3600) * P["cf_container_gib_s"]
    disk = max(0, sec * 20 - P["cf_container_incl_disk_gb_h"] * 3600) * P["cf_container_disk_gb_s"]
    cpu = max(0, M * 60 * cf_cpu_s_stream - P["cf_container_incl_vcpu_min"] * 60) * P["cf_container_vcpu_s"]
    do = max(0, sec * 0.125 * 2 - P["cf_do_incl_gb_s"]) * P["cf_do_gb_s_million"] / 1e6  # the container's Durable Object plus a router while awake
    return P["cf_workers_paid_month"] + mem + disk + cpu + do, int(math.ceil(peak(M, window) / cf_streams))


def cf_rows(window, hrs_aws):
    rows = []
    for M in VOLUMES:
        pk = peak(M, window)
        row = [f"{M:,}", f"{pk:.1f}" if pk < 10 else f"{pk:.0f}"]
        c, lim = dg_month(M, "payg")
        row.append(usd(c) + (" (over concurrency limit)" if pk > lim else ""))
        row.append(usd(M * P["cf_wai_nova3_ws_min"]))
        c, n = cf_always(M, window); row.append(f"{usd(c)} ({n}x)")
        c, n = cf_zero(M, window); row.append(f"{usd(c)} (up to {n}x)")
        for fam, mode in (("c8g", "od"), ("c8g", "sp1y")):
            c, t, n = aws_month(fam, mode, M, hrs_aws, ops=False, window=window)
            row.append(f"{usd(c)} ({n}x {t.split('.')[1]})")
        c, n = home_month(M, "pop", False, window)
        row.append(f"{usd(c)} ({n}x)")
        rows.append(row)
    return rows


HCF = ["Minutes/month", "Peak streams", "Deepgram PAYG", "Workers AI Nova-3 WS", "Cloudflare Containers always-warm", "Cloudflare Containers scale-to-zero",
       "EC2 c8g on-demand", "EC2 c8g 1-yr SP", "i9 desktop class (amortised)"]
T["cf_sens_247"] = md(HCF, cf_rows(H_ON, H_ON))
T["cf_sens_biz"] = md(HCF, cf_rows(H_BIZ, H_ON))
cf_stream_hour_cpu = cf_cpu_s_stream * 3600 * P["cf_container_vcpu_s"]
cf_idle_month = cf_always(0, H_ON)[0]
cf_one_month = P["cf_workers_paid_month"] + cf_gib * H_ON * 3600 * P["cf_container_gib_s"]

# ---------------------------------------------------------------- base plus burst (hybrid) model
import random as _random
HYP = P["hy_hour_peak"]
B_UNIT = "c8g.xlarge"                       # base capacity is bought in 4 vCPU units, measured 1.167 streams per vCPU
B_STREAMS = streams(B_UNIT)                  # about 4 streams per unit after the planning derate
B_OD = price(B_UNIT)
B_FIXED = P["ebs_gb"] * P["aws_ebs_gp3_gb_month"]   # no ALB: Cloudflare Tunnel and Load Balancing in front (the $5 is added once below)
SPOT_H = float(INST["c8g.4xlarge"]["spot_use1_vantage"]) / 4   # per xlarge, scaled linearly from the 4xlarge
OWN_UNIT_STREAMS, OWN_UNIT_COST = pop_cap, pop_amort + pop_power


def profile(kind):
    """hourly mean concurrency weights for one 730 hour month (30 days of 24 h; weekdays 1-5 of each week for business)"""
    w = []
    for day in range(30):
        weekday = day % 7 < 5
        for h in range(24):
            if kind == "business":
                v = [0.4, 0.8, 1, 1, 0.7, 0.9, 1, 1, 0.8, 0.4][h - 8] if (weekday and 8 <= h < 18) else 0.03
            elif kind == "roundclock":
                v = 0.65 + 0.35 * math.sin((h - 9) / 24 * 2 * math.pi)
            else:   # spiky: business shape plus a campaign of 3 hours at 4x on four days
                v = [0.4, 0.8, 1, 1, 0.7, 0.9, 1, 1, 0.8, 0.4][h - 8] if (weekday and 8 <= h < 18) else 0.03
                if day in (3, 10, 17, 24) and 13 <= h < 16: v = 4.0
            w.append(v)
    w += [0.03] * (730 - len(w))
    return w


def series(M, kind):
    w = profile(kind); tot = sum(w)
    return [x * (M / 60) / tot for x in w]          # mean concurrent streams per hour; sums to M/60 stream-hours


def hybrid(M, kind, burst, base_units, own=False):
    mu = series(M, kind)
    cap_s = (OWN_UNIT_STREAMS if own else B_STREAMS) * base_units          # streams the base carries at the planning load
    usable = cap_s / HYP                                                    # mean concurrency the base can take while covering in-hour peaks
    thr = usable * P["hy_base_threshold"] / 1.0
    excess_h = sum(max(0.0, m - usable) for m in mu)                        # stream-hours that go to the burst tier
    edges = sum(1 for i in range(1, len(mu)) if mu[i] * HYP > cap_s * P["hy_base_threshold"] >= mu[i - 1] * HYP)  # warm-ups started
    peak_x = max(0.0, max(mu) * HYP - cap_s)                                # peak streams over base
    base = base_units * (OWN_UNIT_COST if own else B_OD * H_ON + B_FIXED) + P["cf_lb_month"]   # front door: Tunnel plus Load Balancing, $5 a month
    if excess_h <= 0 and edges == 0:
        return base, 0.0
    if burst == "deepgram":
        extra = excess_h * 60 * P["dg_nova3_mono_stream_payg"]
    elif burst == "cloudflare":
        k = math.ceil(peak_x / cf_streams) if peak_x > 0 else 0
        run = excess_h / (cf_streams * P["hy_burst_fill"]) * cf_prov_h + excess_h * 3600 * cf_cpu_s_stream * P["cf_container_vcpu_s"]
        warm = edges * k * (P["hy_warm_lead_cf_min"] + P["hy_drain_min"]) / 60 * cf_prov_h
        extra = run + warm + P["cf_workers_paid_month"]
    else:   # EC2 spot Auto Scaling group of c8g.xlarge
        k = math.ceil(peak_x / B_STREAMS) if peak_x > 0 else 0
        run = excess_h / (B_STREAMS * P["hy_burst_fill"]) * SPOT_H
        warm = edges * k * (P["hy_warm_lead_ec2_min"] + P["hy_drain_min"]) / 60 * SPOT_H
        extra = run + warm
    return base, extra


def best_hybrid(M, kind, burst, own=False):
    best = None
    per = OWN_UNIT_STREAMS if own else B_STREAMS
    u0 = max(2, math.ceil(P["hy_min_base_share"] * max(series(M, kind)) * HYP / per)) if burst != "deepgram" else 2   # serverless and spot tiers: the base carries at least this share of the peak
    for u in range(u0, 4000):
        b, e = hybrid(M, kind, burst, u, own)
        if best is None or b + e < best[0]:
            best = (b + e, u, e)
        if per * u / HYP > max(series(M, kind)) * 1.02: break
    return best


def peak_fleet(M, kind):
    pk = max(series(M, kind)) * HYP
    u = max(2, math.ceil(pk / B_STREAMS))
    return u * (B_OD * H_ON + B_FIXED) + P["cf_lb_month"], u


def hybrid_rows():
    rows = []
    for kind, label in (("business", "business hours"), ("roundclock", "round the clock"), ("spiky", "business hours plus 4 campaign days")):
        for M in (100_000, 1_000_000, 10_000_000):
            pk = max(series(M, kind)) * HYP
            dg = M * P["dg_nova3_mono_stream_payg"]
            pf, pu = peak_fleet(M, kind)
            row = [label, f"{M:,}", f"{pk:.0f}", usd(dg), f"{usd(pf)} ({pu}x)"]
            for burst in ("deepgram", "cloudflare", "spot"):
                c, u, e = best_hybrid(M, kind, burst)
                row.append(f"{usd(c)} (base {u}x, burst {100 * e / c:.0f}%)")
            c, u, e = best_hybrid(M, kind, "deepgram", own=True)
            row.append(f"{usd(c)} (own base {u}x)")
            rows.append(row)
    return rows


T["hybrid"] = md(["Traffic", "Minutes/month", "Peak streams", "All on Deepgram PAYG", "EC2 c8g sized for the peak, always on", "Base + Deepgram overflow", "Base + Cloudflare containers burst",
                  "Base + EC2 spot burst", "Own machines base + Deepgram overflow"], hybrid_rows())


def hybrid_breakeven(kind, burst):
    for k in range(0, 3000):
        M = 5000 * (10 ** (k / 500))
        if M > 3e7: return None
        if best_hybrid(M, kind, burst)[0] < M * P["dg_nova3_mono_stream_payg"]: return M
    return None


T["hybrid_be"] = md(["Traffic", "Base + Deepgram overflow beats all-Deepgram from", "Base + Cloudflare burst from", "Base + EC2 spot burst from", "Peak-sized always-on EC2 from"],
                    [[lbl] + [be(hybrid_breakeven(k, b)) for b in ("deepgram", "cloudflare", "spot")] +
                     [be(next((5000 * 10 ** (i / 500) for i in range(3000) if peak_fleet(5000 * 10 ** (i / 500), k)[0] < 5000 * 10 ** (i / 500) * P["dg_nova3_mono_stream_payg"]), None))]
                     for k, lbl in (("business", "business hours"), ("roundclock", "round the clock"), ("spiky", "business hours plus campaign days"))])


# ---------------------------------------------------------------- Cloudflare curves and break-evens for the R&D page charts
def cf_options(M, kind):
    """monthly cost of each live-streaming option at M minutes (infrastructure only), kind = roundclock | business"""
    window = H_ON if kind == "roundclock" else H_BIZ
    dg, lim = dg_month(M, "payg")
    return {
        "deepgram": dg, "workers_ai_nova3_ws": M * P["cf_wai_nova3_ws_min"],
        "cf_always_warm": cf_always(M, window)[0], "cf_scale_to_zero": cf_zero(M, window)[0],
        "ec2_c8g_on_demand": aws_month("c8g", "od", M, H_ON, ops=False, window=window)[0],
        "ec2_c8g_1yr_plan": aws_month("c8g", "sp1y", M, H_ON, ops=False, window=window)[0],
        "own_i9_desktops": home_month(M, "pop", False, window)[0],
    }, int(peak(M, window) > lim)


def first_cheaper(kind, a, b):
    """first monthly volume at which option a costs less than option b (and stays so at the next point), or None"""
    prev = None
    for k in range(0, 400):
        M = 2000 * (10 ** (k / 40))
        if M > 3.1e7: return None
        o, _ = cf_options(M, kind)
        if o[a] < o[b]:
            return round(M, -2)
    return None


def write_cf_csvs():
    kinds = ("roundclock", "business")
    cols = ["deepgram", "workers_ai_nova3_ws", "cf_always_warm", "cf_scale_to_zero", "ec2_c8g_on_demand", "ec2_c8g_1yr_plan", "own_i9_desktops"]
    with open(os.path.join(HERE, "cloudflare_cost_curve.csv"), "w", newline="") as f:
        f.write("# Monthly cost against monthly audio minutes for live streaming, infrastructure only (no operations hours), US dollars. Generated by costs.py from costs.csv and instances.csv: do not edit by hand.\n"
                "# status: modelled (theory with stated assumptions); the Cloudflare columns assume a capacity that was not measured there, the EC2 columns use measured streams per vCPU and list prices; Deepgram and Workers AI are published prices read 2026-12-04 and 2026-12-05.\n"
                "# traffic: roundclock = the same load all day; business = weekdays 10 hours. deepgram_over_limit = 1 where the peak exceeds Deepgram pay-as-you-go's 150 concurrent streams.\n")
        f.write("traffic,minutes," + ",".join(cols) + ",deepgram_over_limit\n")
        for kind in kinds:
            for k in range(0, 41):
                M = 5000 * (10 ** (k / 12))
                if M > 3.1e7: break
                o, over = cf_options(M, kind)
                f.write(f"{kind},{round(M)}," + ",".join(f"{o[c]:.2f}" for c in cols) + f",{over}\n")
    pairs = [("cf_scale_to_zero", "deepgram", "Cloudflare containers (scale to zero) cheaper than Deepgram"),
             ("cf_always_warm", "deepgram", "Cloudflare containers (always warm) cheaper than Deepgram"),
             ("ec2_c8g_on_demand", "deepgram", "EC2 Graviton4 on-demand cheaper than Deepgram"),
             ("ec2_c8g_1yr_plan", "deepgram", "EC2 Graviton4 1-year plan cheaper than Deepgram"),
             ("own_i9_desktops", "deepgram", "Own desktops cheaper than Deepgram"),
             ("ec2_c8g_on_demand", "cf_scale_to_zero", "EC2 Graviton4 on-demand cheaper than Cloudflare scale-to-zero"),
             ("ec2_c8g_on_demand", "cf_always_warm", "EC2 Graviton4 on-demand cheaper than always-warm containers")]
    with open(os.path.join(HERE, "cloudflare_breakevens.csv"), "w", newline="") as f:
        f.write("# Break-even points: the first monthly volume (audio minutes) at which the first option costs less than the second, on a log grid of 40 points a decade from 2,000 minutes. Generated by costs.py: do not edit by hand. status: modelled.\n")
        f.write("traffic,option,cheaper_than,minutes_per_month,status\n")
        for kind in kinds:
            for a, b, label in pairs:
                m = first_cheaper(kind, a, b)
                f.write(f"{kind},{label.split(' cheaper')[0]},{b},{int(m) if m else 'never under 31M'},modelled\n")

# ---------------------------------------------------------------- cloudflare workers ai
T["cf_wai"] = md(["Model", "Price", "Per audio hour / per 1,000 chars", "Notes"], [
    ["@cf/openai/whisper, whisper-large-v3-turbo (STT)", "$0.0005 per audio minute", usd(P["cf_wai_whisper_min"] * 60, 3), "page does not state streaming; treat as batch/chunked"],
    ["@cf/deepgram/nova-3 (STT, REST)", "$0.0052 per audio minute", usd(P["cf_wai_nova3_min"] * 60, 3), "Deepgram direct pre-recorded PAYG is $0.0043"],
    ["@cf/deepgram/nova-3 (STT, WebSocket)", "$0.0092 per audio minute", usd(P["cf_wai_nova3_ws_min"] * 60, 3), "Deepgram direct streaming PAYG is $0.0048: nearly 2x"],
    ["@cf/deepgram/flux (STT, WebSocket)", "$0.0077 per audio minute", usd(P["cf_wai_flux_ws_min"] * 60, 3), "Deepgram direct $0.0065"],
    ["@cf/deepgram/aura-2-en, aura-2-es (TTS)", "$0.030 per 1,000 chars", usd(P["cf_wai_aura2_1k"] * P["tts_chars_per_audio_hour"] / 1000, 2), "same as Deepgram direct"],
    ["@cf/deepgram/aura-1 (TTS)", "$0.015 per 1,000 chars", usd(0.015 * P["tts_chars_per_audio_hour"] / 1000, 2), "same as Deepgram direct"],
    ["@cf/myshell-ai/melotts (TTS)", "$0.0002 per audio minute", usd(P["cf_wai_melotts_min"] * 60, 3), "about $0.0002 per 1,000 chars; the model page lists it as Deprecated 11/20/2026 (read 2026-12-05)"],
])

# ---------------------------------------------------------------- charts
def charts():
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt
    import numpy as np
    pal = ["#0072B2", "#E69F00", "#009E73", "#D55E00", "#CC79A7", "#56B4E9", "#000000", "#999999"]
    plt.rcParams.update({"font.size": 10, "axes.spines.top": False, "axes.spines.right": False, "axes.grid": True,
                         "grid.alpha": .25, "figure.dpi": 130})
    os.makedirs(IMG, exist_ok=True)

    # 1 streams per instance and $/stream-hour
    ts = ["c6i.4xlarge", "c7i.4xlarge", "m7i.4xlarge", "c8i.4xlarge", "c7a.4xlarge", "c8a.4xlarge", "c7g.4xlarge", "c8g.4xlarge"]
    fig, ax = plt.subplots(1, 2, figsize=(11, 4))
    ax[0].barh(ts, [streams(t) for t in ts], color=pal[0])
    for i, t in enumerate(ts): ax[0].text(streams(t) + .1, i, f"{streams(t):.1f}", va="center")
    ax[0].set_xlabel(f"full English channels per 16-vCPU instance at {int(UTIL * 100)}% CPU")
    ax[0].set_title("Capacity (Parakeet route, discounted from i9)")
    w = .27
    y = np.arange(len(ts))
    for k, (m, lab) in enumerate([("od", "on-demand"), ("sp1y", "1-yr SP"), ("sp3y", "3-yr SP")]):
        ax[1].barh(y + (k - 1) * w, [price(t, m) / streams(t) for t in ts], w, label=lab, color=pal[k])
    ax[1].axvline(P["dg_nova3_mono_stream_payg"] * 60, color=pal[3], ls="--")
    ax[1].text(P["dg_nova3_mono_stream_payg"] * 60, len(ts) - .4, " Deepgram PAYG\n $0.288/h", color=pal[3], va="top", ha="right")
    ax[1].set_yticks(y); ax[1].set_yticklabels(ts); ax[1].set_xlabel("$ per stream-hour with every channel busy (infra only)")
    ax[1].legend(loc="lower right"); ax[1].set_title("Cost per channel-hour at 100% of capacity")
    fig.tight_layout(); fig.savefig(os.path.join(IMG, "costs-capacity.png")); plt.close(fig)

    # 2 cost per 1000 min vs utilisation
    u = np.linspace(.05, 1, 80)
    fig, ax = plt.subplots(figsize=(7.5, 4.6))
    for k, (t, m, lab) in enumerate([("c7a.4xlarge", "od", "c7a.4xlarge on-demand"), ("c8a.4xlarge", "od", "c8a.4xlarge on-demand"),
                                     ("c8a.4xlarge", "sp1y", "c8a.4xlarge 1-yr SP"), ("c8g.4xlarge", "od", "c8g.4xlarge on-demand"),
                                     ("c8g.4xlarge", "sp3y", "c8g.4xlarge 3-yr SP"), ("c7i.4xlarge", "od", "c7i.4xlarge on-demand")]):
        ax.plot(u * 100, [per_stream_hour(t, m, x) / 60 * 1000 for x in u], label=lab, color=pal[k])
    ax.axhline(dg_pay, color=pal[3], ls="--", label="Deepgram Nova-3 PAYG"); ax.axhline(dg_gr, color=pal[4], ls=":", label="Deepgram Nova-3 Growth")
    ax.set_ylim(0, 6); ax.set_xlabel("% of channel capacity busy while the instance runs"); ax.set_ylabel("$ per 1,000 audio minutes")
    ax.set_title("Self-hosted vs Deepgram, streaming STT (infra incl. load balancer, no ops)")
    ax.legend(); fig.tight_layout(); fig.savefig(os.path.join(IMG, "costs-utilisation.png")); plt.close(fig)

    # 3 monthly cost vs minutes
    Ms = np.logspace(3, 7.3, 60)
    fig, ax = plt.subplots(figsize=(8, 5))
    ax.plot(Ms, [dg_month(m, "payg")[0] for m in Ms], label="Deepgram PAYG", color=pal[3])
    ax.plot(Ms, [dg_month(m, "growth")[0] for m in Ms], label="Deepgram Growth", color=pal[4], ls="--")
    ax.plot(Ms, [m * P["cf_wai_nova3_ws_min"] for m in Ms], label="Workers AI Nova-3 WS", color=pal[7], ls=":")
    for k, (fam, mode, hrs, lab) in enumerate([("c7a", "od", H_ON, "AWS c7a on-demand, always-on, with ops"),
                                              ("c8a", "sp1y", H_ON, "AWS c8a 1-yr SP, always-on, with ops"),
                                              ("c8a", "od", H_BIZ, "AWS c8a business hours, with ops")]):
        ax.plot(Ms, [aws_month(fam, mode, m, hrs)[0] for m in Ms], label=lab, color=pal[k])
    ax.plot(Ms, [aws_month("c8a", "sp1y", m, H_ON, ops=False)[0] for m in Ms], label="AWS c8a 1-yr SP, infra only", color=pal[2], ls="--")
    ax.plot(Ms, [home_month(m, "pop", False)[0] for m in Ms], label="i9 desktop class, amortised", color=pal[5])
    ax.set_xscale("log"); ax.set_yscale("log"); ax.set_xlabel("audio minutes per month (streaming, business-hours traffic)")
    ax.set_ylabel("USD per month"); ax.set_title("Monthly cost: where self-hosting wins")
    ax.legend(fontsize=8); fig.tight_layout(); fig.savefig(os.path.join(IMG, "costs-monthly.png")); plt.close(fig)


def inject(text, tables):
    for k, v in tables.items():
        pat = re.compile(rf"(<!-- BEGIN:{k} -->\n).*?(\n?<!-- END:{k} -->)", re.S)
        if not pat.search(text):
            print(f"warning: no marker for {k} in COSTS.md", file=sys.stderr)
            continue
        text = pat.sub(lambda m: m.group(1) + v + "\n<!-- END:" + k + " -->", text)
    return text


if __name__ == "__main__":
    write_cf_csvs()
    if os.path.exists(DOC):
        txt = open(DOC).read()
        open(DOC, "w").write(inject(txt, T))
    else:
        for k, v in T.items():
            print(f"## {k}\n{v}\n")
    if "--no-charts" not in sys.argv:
        try:
            charts()
        except ImportError:
            print("matplotlib missing: charts skipped", file=sys.stderr)
    # key numbers for the prose
    print("cf: cpu-s per audio-s", round(cf_cpu_s_stream, 3), "| cpu $/stream-hour", round(cf_stream_hour_cpu, 4), "| provisioned $/container-hour", round(cf_prov_h, 4),
          "| container-hour full", round(cf_h, 4), "| $/stream-hour", round(cf_h / cf_streams, 4), "| batch $/1000 min", round(cf_batch_min * 1000, 3), "| 2 containers idle month", round(cf_idle_month, 2),
          "| streams c7a-like", round(streams(cf_ref) / vcpu(cf_ref) * 4, 2), "c7i-like", round(streams("c7i.xlarge"), 2))
    print("lambda $/audio-min", round(lam_per_audio_min, 5), "| ec2 batch od", round(ec2_batch_min_od, 5), "spot", round(ec2_batch_min_spot, 5),
          "| apigw+lambda stream-hour", round(lam_stream_total, 3), "| var/stream-h", round(var_per_stream_hour(), 5))
