#!/usr/bin/env python3
"""Sizing and monthly cost model for 50 simultaneous voice-agent calls, 08:00 to 23:00 every day.

    python3 docs/data/solution50.py

Writes docs/data/solution50_*.csv (the site's charts and docs/SOLUTION-50-CALLS.md read them). Nothing is edited by
hand: change an input below (every price carries its source and date), re-run, commit the CSVs.

Capacity inputs are our measurements (docs/COSTS.md sections 1b and 1c, docs/data/ec2_concurrency.csv, ec2_tts.csv);
prices were read on 2026-12-05 (AWS Pricing API and Savings Plans offering rates, us-east-1, Linux, shared tenancy,
Compute Savings Plan No Upfront; Spot price history, mean of 30 days over five zones; Deepgram, Fish Audio and the
other TTS vendors from their own pages). Everything else (the load profile, speaking share, interruption rate,
cache hit rate) is a stated assumption and is labelled so in the output."""
import csv, math, os

HERE = os.path.dirname(os.path.abspath(__file__))
DAYS = 365 / 12                       # days per month
HOURS_ALWAYS = 730.0                  # AWS billing month
WINDOW = list(range(8, 23))           # 08:00 to 23:00, 15 hours
PEAK = 50

# ---------------------------------------------------------------- prices, us-east-1, read 2026-12-05
# type: (vCPU, on-demand $/h, 1-yr Compute SP no upfront, 3-yr Compute SP no upfront, spot mean 30 d)
PRICES = {
    "c8g.4xlarge":  (16, 0.63808, 0.45744, 0.30892, 0.3176),
    "c8g.8xlarge":  (32, 1.27616, 0.91488, 0.61784, 0.5484),
    "c8g.12xlarge": (48, 1.91424, 1.37231, 0.92676, 0.8997),
    "c8g.16xlarge": (64, 2.55232, 1.82975, 1.23568, 0.9277),
    "c7a.4xlarge":  (16, 0.82112, 0.59338, 0.39646, 0.3073),
    "c7a.8xlarge":  (32, 1.64224, 1.18677, 0.79291, 0.6324),
}
PRICES["c8g.4xlarge+voices"] = PRICES["c8g.4xlarge"]      # the same instance running speech to text AND two 4-thread voices (6 fast + 2 final + 8 voice vCPUs)
# load balancer and the fixed items (costs.csv, read 2026-12-04 / 2026-12-05)
LB_FIXED = 0.0225 * HOURS_ALWAYS + 2 * 0.005 * HOURS_ALWAYS     # ALB hour + two public IPv4
LCU_PER_STREAM_HOUR = 0.115 * 0.008                             # 115 MB per stream-hour, 1 GB/h per LCU, $0.008 per LCU-h
NAT = 0.045 * HOURS_ALWAYS                                      # one NAT gateway (assumption: AWS list price; bootstrap and metrics only)
LOGS = 10.0                                                     # costs.csv assumption
EBS_MONTH = 4.0                                                 # 50 GB gp3 at $0.08, per instance-month
OPS = 500.0                                                     # costs.csv assumption (operations, $100/h), reported separately
FIXED = LB_FIXED + NAT + LOGS

# ---------------------------------------------------------------- capacity, measured
STT_PLAN_PER_VCPU = 0.85              # planned live streams per instance vCPU (0.85 x the measured knee of 1.0 on all 16 vCPUs of a c8g.4xlarge)
CAP = {t: STT_PLAN_PER_VCPU * PRICES[t][0] for t in PRICES}
CAP["c8g.4xlarge"] = 13.6             # measured (COSTS.md 1c): knee 16, 0.85 derate
CAP["c7a.4xlarge"] = 11.3             # measured c7a: 0.83 per service vCPU at the knee, 0.85 derate, as in the cost tables
CAP["c7a.8xlarge"] = 22.6
CAP["c8g.4xlarge+voices"] = 6.8       # measured mixed run (ec2_mixed_c8g4xl.csv): 8 calls at the knee, p90 final lag 1.7 to 1.85 s, 0.85 derate
BASIS = {"c8g.4xlarge": "measured", "c7a.4xlarge": "measured", "c7a.8xlarge": "modelled (2 x c7a.4xlarge)"}
KNEE = {"c8g.4xlarge": 16.0, "c8g.8xlarge": 28.0}        # measured knees (8xlarge: on 24 of 32 vCPUs)
BUFFER = 0.10                          # assumption: headroom over the hourly peak for within-hour variation
MIN_INSTANCES = 2                      # assumption: two zones
SPOT_BASE_OD = 2                       # on-demand floor in the spot group
SPOT_FALLBACK = 0.10                   # assumption: share of spot hours served on-demand when spot capacity is short
INTERRUPT_MONTHLY = 0.10               # assumption: share of spot instances interrupted per month (Spot Advisor band 5 to 10%, not queryable)
CALL_MIN = 5.0                         # assumption: average call length, minutes
LAUNCH_HOURS = 0.25                    # assumption: 10 min of warm-up before the load and 5 min of lag when scaling in, per launch

# ---------------------------------------------------------------- load profiles (modelled)
A = [0.35, 0.65, 0.90, 1.00, 0.80, 0.70, 0.95, 1.00, 0.90, 0.70, 0.60, 0.50, 0.45, 0.35, 0.25]   # call-centre day: morning ramp, lunch dip, afternoon peak, evening tail
PROFILES = {
    "flat": [1.0] * 15,
    "diurnal_A": A,                                  # peak 50, average about 34
    "diurnal_B": [x * x for x in A],                 # peaky: peak 50, average about 26
}
def calls(profile, h): return PEAK * PROFILES[profile][h - 8]

# ---------------------------------------------------------------- Deepgram, Fish and the rest (read 2026-12-05)
DG_PAYG, DG_GROWTH, DG_GROWTH_MIN_YEAR = 0.0048, 0.0042, 4000.0      # Nova-3 monolingual streaming, per minute
CHARS_PER_AUDIO_MIN = 150 * 5.7                                       # costs.csv: 150 words per minute x 5.7 characters
SPEAK_SHARE = 0.40                                                    # assumption: the agent speaks 40% of the call
CACHE_HIT = 0.40                                                      # assumption: 40% of agent speech from cached or pre-synthesised audio
TTS_CLOUD = [   # name, $ per 1M characters (Fish: per 1M UTF-8 bytes; English ASCII, 1 byte per character), source note
    ("Fish Audio s3-pro", 15.0, "docs.fish.audio pricing-and-rate-limits, 2026-12-05"),
    ("Deepgram Aura-2 PAYG", 30.0, "deepgram.com/pricing, 2026-12-05"),
    ("Deepgram Aura-2 Growth", 27.0, "deepgram.com/pricing, 2026-12-05"),
    ("Deepgram Aura-1 PAYG", 15.0, "deepgram.com/pricing, 2026-12-05"),
    ("Amazon Polly neural", 16.0, "aws.amazon.com/polly/pricing, 2026-12-05"),
    ("Amazon Polly generative", 30.0, "aws.amazon.com/polly/pricing, 2026-12-05"),
    ("OpenAI tts-1", 15.0, "developers.openai.com pricing, 2026-12-05"),
    ("ElevenLabs Flash (as listed, $0.04 per 1,000 characters)", 40.0, "elevenlabs.io/pricing/api, 2026-12-05"),
]
FISH_SCALE_CONCURRENCY, FISH_SCALE_FEE = 50, 500.0                    # Fish: concurrent requests by plan: PAYG 5, Starter 10, Growth 15, Scale 50
TTS_VOICE_VCPU = {"c7a.4xlarge": 2, "c8g.4xlarge": 4}                 # measured: RTF 0.45 on 2 c7a cores, 0.35 on 4 c8g cores (ec2_tts.csv)


def binom_quantile(n, p, q):
    n = int(round(n)); acc = 0.0
    for k in range(n + 1):
        acc += math.comb(n, k) * p ** k * (1 - p) ** (n - k)
        if acc >= q: return k
    return n


def voices(c, share=SPEAK_SHARE, q=0.99):
    return binom_quantile(c, share, q) if c > 0 else 0


def need(profile, h, cap=13.6, floor=MIN_INSTANCES):
    c = calls(profile, h) if 8 <= h <= 22 else 0
    return max(floor, math.ceil(c * (1 + BUFFER) / cap)) if c > 0 else 0


def fleet(profile, cap=13.6, floor=MIN_INSTANCES):
    """instances per hour of the day (index 0..23): the hour's need; the ten minutes of warm-up before each scale-out and the
    five minutes of lag when scaling in are charged per launch (LAUNCH_HOURS)"""
    return [need(profile, h, cap, floor) for h in range(24)]


def inst_hours_day(n):
    launches = sum(max(0, n[h] - n[h - 1]) for h in range(24))
    return sum(n) + launches * LAUNCH_HOURS, launches


def stream_hours(profile): return sum(calls(profile, h) for h in WINDOW)
def minutes_month(profile): return stream_hours(profile) * 60 * DAYS


def overhead(inst_hours_month, profile, ops=False):
    ebs = EBS_MONTH * inst_hours_month / HOURS_ALWAYS
    lcu = stream_hours(profile) * DAYS * LCU_PER_STREAM_HOUR
    return FIXED + ebs + lcu + (OPS if ops else 0)


def spend(profile, kind, t="c8g.4xlarge"):
    """monthly instance cost + overhead for a way of buying the same fleet. kind:
    'sp3_247', 'sp1_247', 'od_247' (flat fleet sized for the peak, always on), 'od_sched' (the peak fleet, scheduled on 08-23),
    'od_asg' (follows load), 'spot_asg' (2 on-demand + spot, follows load), 'plan_base_asg' (best k on a 3-yr plan, rest on-demand)"""
    vcpu, od, sp1, sp3, spot = PRICES[t]
    cap = CAP[t]
    peak_n = need("flat", 12, cap)
    if kind in ("sp3_247", "sp1_247", "od_247"):
        rate = {"sp3_247": sp3, "sp1_247": sp1, "od_247": od}[kind]
        ih = peak_n * HOURS_ALWAYS
        return peak_n * rate * HOURS_ALWAYS + overhead(ih, profile), peak_n
    if kind == "od_sched":
        ih = peak_n * (len(WINDOW) + LAUNCH_HOURS) * DAYS
        return ih * od + overhead(ih, profile), peak_n
    n = fleet(profile, cap)
    ihd, _ = inst_hours_day(n)
    ih = ihd * DAYS
    if kind == "od_asg":
        return ih * od + overhead(ih, profile), max(n)
    if kind == "spot_asg":
        base = sum(min(x, SPOT_BASE_OD) for x in n) * DAYS + (SPOT_BASE_OD * 0)   # on-demand floor hours
        launch_extra = (ihd - sum(n)) * DAYS
        od_hours = base + launch_extra * min(1.0, SPOT_BASE_OD / max(1, max(n)))
        spot_hours = ih - od_hours
        cost = od_hours * od + spot_hours * ((1 - SPOT_FALLBACK) * spot + SPOT_FALLBACK * od)
        return cost + overhead(ih, profile), max(n)
    if kind == "plan_base_asg":
        best = None
        for k in range(0, max(n) + 1):
            covered = sum(min(x, k) for x in n) * DAYS
            rest = ih - covered
            cost = k * sp3 * HOURS_ALWAYS + max(0.0, rest) * od
            if best is None or cost < best[0]: best = (cost, k)
        return best[0] + overhead(ih, profile), best[1]
    raise ValueError(kind)


def write(name, rows, fields):
    with open(os.path.join(HERE, name), "w", newline="") as f:
        w = csv.DictWriter(f, fieldnames=fields)
        w.writeheader()
        for r in rows: w.writerow(r)


def main():
    # ---- prices
    rows = []
    for t, (v, od, sp1, sp3, spot) in PRICES.items():
        rows.append(dict(instance=t, vcpu=v, on_demand_usd_h=od, sp1y_no_upfront_usd_h=sp1, sp3y_no_upfront_usd_h=sp3,
                         spot_mean_30d_usd_h=spot, sp3y_vs_od=round(sp3 / od, 3), spot_vs_od=round(spot / od, 3),
                         source="AWS Pricing API, Savings Plans offering rates and EC2 spot price history, us-east-1, Linux", date_read="2026-12-05"))
    write("solution50_prices.csv", rows, list(rows[0]))

    # ---- sizing of the STT fleet for 50 calls
    mixes = [("5 x c8g.4xlarge", {"c8g.4xlarge": 5}), ("4 x c8g.4xlarge", {"c8g.4xlarge": 4}), ("2 x c8g.8xlarge", {"c8g.8xlarge": 2}),
             ("3 x c8g.8xlarge", {"c8g.8xlarge": 3}), ("1 x c8g.12xlarge + 1 x c8g.4xlarge", {"c8g.12xlarge": 1, "c8g.4xlarge": 1}),
             ("1 x c8g.16xlarge", {"c8g.16xlarge": 1}), ("2 x c8g.16xlarge", {"c8g.16xlarge": 2}),
             ("5 x c7a.4xlarge (AMD)", {"c7a.4xlarge": 5}), ("6 x c7a.4xlarge (AMD)", {"c7a.4xlarge": 6}), ("3 x c7a.8xlarge (AMD)", {"c7a.8xlarge": 3})]
    srows = []
    for name, mix in mixes:
        planned = sum(CAP[t] * n for t, n in mix.items())
        vc = sum(PRICES[t][0] * n for t, n in mix.items())
        odh = sum(PRICES[t][1] * n for t, n in mix.items())
        sp3 = sum(PRICES[t][3] * n for t, n in mix.items())
        biggest = max(CAP[t] for t in mix)
        survive = planned - biggest
        basis = "measured" if all(t in ("c8g.4xlarge", "c7a.4xlarge") for t in mix) else "modelled (0.85 per vCPU; 8xlarge also measured on 24 of 32 vCPUs: knee 28, plan 24)"
        srows.append(dict(mix=name, vcpu=vc, planned_streams=round(planned, 1), load_at_peak_pct=round(100 * PEAK / planned),
                          streams_if_largest_instance_lost=round(survive, 1), survives_peak_after_loss="yes" if survive >= PEAK else "no",
                          od_usd_h=round(odh, 3), sp3y_usd_h=round(sp3, 3), od_usd_month_247=round(odh * HOURS_ALWAYS), basis=basis))
    for n in (8, 9):
        t = "c8g.4xlarge+voices"
        planned = CAP[t] * n
        srows.append(dict(mix=f"{n} x c8g.4xlarge, speech + voices", vcpu=16 * n, planned_streams=round(planned, 1), load_at_peak_pct=round(100 * PEAK / planned),
                          streams_if_largest_instance_lost=round(planned - CAP[t], 1), survives_peak_after_loss="yes" if planned - CAP[t] >= PEAK else "no",
                          od_usd_h=round(PRICES[t][1] * n, 3), sp3y_usd_h=round(PRICES[t][3] * n, 3), od_usd_month_247=round(PRICES[t][1] * n * HOURS_ALWAYS),
                          basis="measured (calls with their voices, 2026-12-05)"))
    write("solution50_sizing.csv", srows, list(srows[0]))

    # ---- profiles and fleet per hour
    prow = []
    nA, nB, nF = fleet("diurnal_A"), fleet("diurnal_B"), fleet("flat")
    for h in range(7, 24):
        c = lambda p: calls(p, h) if 8 <= h <= 22 else 0
        prow.append(dict(hour=h, calls_flat=c("flat"), calls_diurnal_A=round(c("diurnal_A"), 1), calls_diurnal_B=round(c("diurnal_B"), 1),
                         instances_flat=nF[h], instances_diurnal_A=nA[h], instances_diurnal_B=nB[h],
                         voices_p99_flat=voices(c("flat")), voices_p99_diurnal_A=voices(round(c("diurnal_A"))), voices_p99_diurnal_B=voices(round(c("diurnal_B"))),
                         voices_mean_flat=round(c("flat") * SPEAK_SHARE, 1)))
    write("solution50_profile.csv", prow, list(prow[0]))

    # ---- monthly cost, STT only, per way of buying, per profile
    strategies = [("od_247", "24/7 on-demand"), ("sp1_247", "24/7, 1-year plan"), ("sp3_247", "24/7, 3-year plan"), ("od_sched", "Scheduled on-demand 08-23"),
                  ("od_asg", "Follows load, on-demand"), ("plan_base_asg", "Plan base + on-demand burst"), ("spot_asg", "2 on-demand + spot, follows load")]
    mrows = []
    for prof in PROFILES:
        mins = minutes_month(prof)
        for key, label in strategies:
            usd, units = spend(prof, key)
            if key == "od_sched" and prof != "flat":
                pass
            mrows.append(dict(profile=prof, strategy=key, label=label, monthly_usd=round(usd), per_1000_min=round(usd / mins * 1000, 3),
                              minutes_month=round(mins), units=units, with_ops_usd=round(usd + OPS), note="infrastructure incl. load balancer, NAT, logs, disks; ops excluded"))
        for key, label in (("od_sched", "Speech + voices on c8g, scheduled on-demand"), ("od_asg", "Speech + voices on c8g, follows load, on-demand"), ("spot_asg", "Speech + voices on c8g, 2 on-demand + spot")):
            usd, units = spend(prof, key, "c8g.4xlarge+voices")
            mrows.append(dict(profile=prof, strategy="mixed_" + key, label=label, monthly_usd=round(usd), per_1000_min=round(usd / mins * 1000, 3), minutes_month=round(mins), units=units,
                              with_ops_usd=round(usd + OPS), note="measured layout: 6 fast + 2 final + two 4-thread voices on 16 vCPUs, 6.8 calls planned per instance"))
        # hybrid: 3 instances + Deepgram overflow
        cap3 = 3 * CAP["c8g.4xlarge"]
        spill = sum(max(0.0, calls(prof, h) - cap3) for h in WINDOW) * 60 * DAYS
        n3 = [3 if 7 <= h <= 22 else 0 for h in range(24)]
        ih = inst_hours_day(n3)[0] * DAYS
        usd = ih * PRICES["c8g.4xlarge"][1] + overhead(ih, prof) + spill * DG_PAYG
        mrows.append(dict(profile=prof, strategy="hybrid3", label="3 instances + Deepgram overflow", monthly_usd=round(usd), per_1000_min=round(usd / mins * 1000, 3),
                          minutes_month=round(mins), units=3, with_ops_usd=round(usd + OPS), note=f"{round(spill):,} overflow minutes a month to Deepgram PAYG"))
        dg = mins * DG_PAYG
        dgg = max(mins * DG_GROWTH, DG_GROWTH_MIN_YEAR / 12)
        mrows.append(dict(profile=prof, strategy="deepgram_payg", label="Deepgram Nova-3 PAYG", monthly_usd=round(dg), per_1000_min=round(DG_PAYG * 1000, 3), minutes_month=round(mins), units=0, with_ops_usd=round(dg), note="$0.0048 per minute"))
        mrows.append(dict(profile=prof, strategy="deepgram_growth", label="Deepgram Nova-3 Growth", monthly_usd=round(dgg), per_1000_min=round(dgg / mins * 1000, 3), minutes_month=round(mins), units=0, with_ops_usd=round(dgg), note="$0.0042 per minute; $4,000 a year prepaid minimum"))
        # own hardware
        for label, cap_m, price, watts, key in (("Mac mini M4, 4 streams each (measured cap)", 4, 599, 12, "mac4"), ("Mac mini M4, 12 streams each (modelled)", 12, 599, 12, "mac12"), ("i9 workstation, 8 streams each (half the machine)", 8, None, None, "pop")):
            n = math.ceil(PEAK * 1.1 / cap_m)
            if key == "pop": per = 48.2
            else: per = price / 48 + watts / 1000 * 730 * 0.15
            usd = n * per
            mrows.append(dict(profile=prof, strategy=key, label=label, monthly_usd=round(usd), per_1000_min=round(usd / mins * 1000, 3), minutes_month=round(mins), units=n,
                              with_ops_usd=round(usd + OPS), note="amortised over 48 months plus power at $0.15/kWh; no failover; one site"))
    write("solution50_monthly.csv", mrows, list(mrows[0]))

    # ---- spot interruptions
    spot_inst = sum(max(0, x - SPOT_BASE_OD) for x in nA) * DAYS / HOURS_ALWAYS   # average spot instances (hours/730)
    events = spot_inst * INTERRUPT_MONTHLY * (HOURS_ALWAYS / HOURS_ALWAYS)
    per_inst_calls = 34 / 3.5
    affected = events * per_inst_calls * math.exp(-2 / CALL_MIN)
    total_calls = minutes_month("diurnal_A") / CALL_MIN
    srow = dict(avg_spot_instances=round(spot_inst, 2), interrupt_rate_month=INTERRUPT_MONTHLY, events_month=round(events, 2),
                calls_per_instance=round(per_inst_calls, 1), call_minutes=CALL_MIN, share_still_live_after_2min=round(math.exp(-2 / CALL_MIN), 2),
                calls_cut_month_without_handoff=round(affected, 1), total_calls_month=round(total_calls), share_pct=round(100 * affected / total_calls, 4),
                note="modelled; with a drain on the rebalance signal and a client reconnect these calls resume after a short gap")
    write("solution50_spot.csv", [srow], list(srow))

    # ---- text to speech
    trows = []
    prof = "flat"
    mins = minutes_month(prof)
    vmean = PEAK * SPEAK_SHARE
    v99 = voices(PEAK)
    v99c = voices(PEAK, SPEAK_SHARE * (1 - CACHE_HIT))
    for t in ("c7a.4xlarge", "c8g.4xlarge"):
        per_inst = PRICES[t][0] // TTS_VOICE_VCPU[t]
        for cache, v in ((0.0, v99), (CACHE_HIT, v99c)):
            n = math.ceil(v / per_inst)
            pool_od = n * PRICES[t][1] * (len(WINDOW) + LAUNCH_HOURS) * DAYS
            pool_sp3 = n * PRICES[t][3] * HOURS_ALWAYS
            trows.append(dict(option=f"Kokoro on {t} ({TTS_VOICE_VCPU[t]} vCPU per voice)", cache_hit=cache, peak_voices_p99=v, instances=n, vcpu=n * PRICES[t][0],
                              monthly_usd_scheduled_od=round(pool_od), monthly_usd_3y_plan_247=round(pool_sp3),
                              per_call_minute=round(pool_od / mins, 5), concurrency_limit="your own pool", basis="capacity measured, mix modelled"))
    for name, per_m, src in TTS_CLOUD:
        for cache in (0.0, CACHE_HIT):
            per_audio_min = per_m / 1e6 * CHARS_PER_AUDIO_MIN
            per_call_min = per_audio_min * SPEAK_SHARE * (1 - cache)
            usd = per_call_min * mins
            lim = ("Scale plan: 50 concurrent, $500 a month (fee becomes credit)" if name.startswith("Fish") else
                   "45 streaming (PAYG), 60 (Growth)" if "Aura" in name else "not read")
            trows.append(dict(option=name, cache_hit=cache, peak_voices_p99=v99 if cache == 0 else v99c, instances=0, vcpu=0, monthly_usd_scheduled_od=round(usd),
                              monthly_usd_3y_plan_247="", per_call_minute=round(per_call_min, 5), concurrency_limit=lim, basis="sourced price, modelled volume"))
    write("solution50_tts.csv", trows, list(trows[0]))

    # ---- cost per call-minute, three shapes, for the recommended and the simple setup
    crow = []
    for prof in PROFILES:
        mins = minutes_month(prof)
        stt = {k: next(r for r in mrows if r["profile"] == prof and r["strategy"] == k)["monthly_usd"] for k in ("od_asg", "spot_asg", "plan_base_asg", "od_sched", "sp3_247")}
        # TTS pool follows load: voices p99 per hour, c7a.4xlarge, 8 voices each, on-demand, no plan
        def tts_pool(cache, key="od"):
            tot_h = 0.0; prev = 0
            for h in range(24):
                c = round(calls(prof, h)) if 8 <= h <= 22 else 0
                nxt = round(calls(prof, h + 1)) if 8 <= h + 1 <= 22 else 0
                v = voices(c, SPEAK_SHARE * (1 - cache)) if 8 <= h <= 22 else 0
                n = math.ceil(v / 8) if v else 0
                tot_h += n + max(0, n - prev) * LAUNCH_HOURS; prev = n
            ih = tot_h * DAYS
            p = PRICES["c7a.4xlarge"]
            return ih * (p[1] if key == "od" else (1 - SPOT_FALLBACK) * p[4] + SPOT_FALLBACK * p[1])
        for sk in ("od_asg", "spot_asg"):
            base = stt[sk]
            for cache in (0.0, CACHE_HIT):
                local = tts_pool(cache, "od" if sk == "od_asg" else "spot")
                fish = mins * SPEAK_SHARE * (1 - cache) * 15.0 / 1e6 * CHARS_PER_AUDIO_MIN
                aura2 = mins * SPEAK_SHARE * (1 - cache) * 30.0 / 1e6 * CHARS_PER_AUDIO_MIN
                mixed = next(r for r in mrows if r["profile"] == prof and r["strategy"] == "mixed_" + sk)["monthly_usd"]
                crow.append(dict(profile=prof, stt_fleet=sk, cache_hit=cache, minutes_month=round(mins),
                                 mixed_c8g_usd=mixed, mixed_c8g_per_min=round(mixed / mins, 5),
                                 stt_only_usd=round(base), stt_only_per_min=round(base / mins, 5),
                                 local_tts_usd=round(local), stt_local_tts_usd=round(base + local), stt_local_tts_per_min=round((base + local) / mins, 5),
                                 fish_tts_usd=round(fish), stt_fish_usd=round(base + fish), stt_fish_per_min=round((base + fish) / mins, 5),
                                 aura2_tts_usd=round(aura2), stt_aura2_usd=round(base + aura2), stt_aura2_per_min=round((base + aura2) / mins, 5),
                                 all_deepgram_usd=round(mins * DG_PAYG + aura2), all_deepgram_per_min=round(DG_PAYG + SPEAK_SHARE * (1 - cache) * CHARS_PER_AUDIO_MIN * 30.0 / 1e6, 5)))
    write("solution50_callmin.csv", crow, list(crow[0]))

    # ---- average concurrency below the peak: flat load P for 15 h a day, fleet sized for P
    arows = []
    for P in range(2, 61, 2):
        mins = P * 60 * len(WINDOW) * DAYS
        n = max(MIN_INSTANCES, math.ceil(P * (1 + BUFFER) / CAP["c8g.4xlarge"]))
        ih = n * (len(WINDOW) + LAUNCH_HOURS) * DAYS
        ov = FIXED + EBS_MONTH * ih / HOURS_ALWAYS + P * len(WINDOW) * DAYS * LCU_PER_STREAM_HOUR
        c = PRICES["c8g.4xlarge"]
        od = ih * c[1] + ov
        sp = (min(n, SPOT_BASE_OD) * c[1] + max(0, n - SPOT_BASE_OD) * ((1 - SPOT_FALLBACK) * c[4] + SPOT_FALLBACK * c[1])) * (len(WINDOW) + LAUNCH_HOURS) * DAYS + ov
        arows.append(dict(avg_calls=P, instances=n, minutes_month=round(mins), fleet_od_usd=round(od), fleet_spot_usd=round(sp), fleet_od_with_ops_usd=round(od + OPS),
                          deepgram_payg_usd=round(mins * DG_PAYG), deepgram_growth_usd=round(max(mins * DG_GROWTH, DG_GROWTH_MIN_YEAR / 12))))
    write("solution50_avgcurve.csv", arows, list(arows[0]))
    # break-evens (linear interpolation on the grid)
    def cross(a, b):
        for i in range(1, len(arows)):
            d0 = arows[i - 1][a] - arows[i - 1][b]; d1 = arows[i][a] - arows[i][b]
            if d0 > 0 >= d1 or d0 >= 0 > d1:
                x0, x1 = arows[i - 1]["avg_calls"], arows[i]["avg_calls"]
                return x0 + (x1 - x0) * d0 / (d0 - d1)
        return None
    be = []
    for a, lab in (("fleet_od_usd", "fleet on-demand"), ("fleet_spot_usd", "fleet with spot"), ("fleet_od_with_ops_usd", "fleet on-demand plus $500 operations")):
        for b, lb in (("deepgram_payg_usd", "Deepgram PAYG"), ("deepgram_growth_usd", "Deepgram Growth")):
            x = cross(a, b)
            be.append(dict(option=lab, against=lb, avg_calls=round(x, 1) if x else "", minutes_month=round(x * 60 * len(WINDOW) * DAYS) if x else ""))
    write("solution50_breakevens.csv", be, list(be[0]))
    # ---- a plan pays for 24 hours a day: cost per hour actually used, against hours of use per day (c8g.4xlarge)
    _, od, sp1, sp3, spot = PRICES["c8g.4xlarge"]
    prow2 = []
    for hrs in [x / 2 for x in range(4, 49)]:
        prow2.append(dict(hours_used_per_day=hrs, on_demand=round(od, 4), plan_1y=round(sp1 * 24 / hrs, 4), plan_3y=round(sp3 * 24 / hrs, 4),
                          spot_with_10pct_fallback=round((1 - SPOT_FALLBACK) * spot + SPOT_FALLBACK * od, 4)))
    write("solution50_plan_breakeven.csv", prow2, list(prow2[0]))
    write("solution50_plan_crossovers.csv", [dict(plan="1-year Compute Savings Plan, no upfront", hours_per_day=round(24 * sp1 / od, 1)),
                                            dict(plan="3-year Compute Savings Plan, no upfront", hours_per_day=round(24 * sp3 / od, 1))], ["plan", "hours_per_day"])


if __name__ == "__main__":
    main()
