"""Third part: sales capacity, quotas and pipeline, on a synthetic software company (DESIGN-capacity.md).

Every input comes from protocol-capacity.json, declared before this code existed. Two calculations of the same model:

- `expected`: the bottom-up capacity plan, exact in expectation. Each territory is a Markov chain (not yet open,
  waiting for its first hire, empty after a departure, staffed at tenure month k); opportunities, wins, deal values and
  the chance a deal closes inside the plan year follow from the state probabilities.
- `simulate`: plan-years drawn from the same mechanics. Each territory slot has its own random stream and every month
  draws a fixed set of numbers from it, so scenarios that change an input reuse the same draws (common random numbers).

Writes results/capacity-results.json and results/capacity-years.csv, and prints one VERDICT line.

    .venv/bin/python -I revfc/capacity.py [--out <folder under the study>]
"""
from __future__ import annotations

import csv
import hashlib
import json
import math
import sys
from pathlib import Path

import numpy as np
from scipy import special, stats

ROOT = Path(__file__).resolve().parents[1]
PROTOCOL = ROOT / "protocol-capacity.json"
SLOTS = 16          # won deals a territory can close from one month's opportunities; more is counted as overflow
Z95 = 1.959963984540054
STEPS = ("quota_capacity", "attainment", "start_and_lag", "ramp", "attrition_vacancy", "pipeline_timing")


def load_protocol(path: Path = PROTOCOL) -> dict:
    return json.loads(path.read_text(encoding="utf-8"))


def rnd(x, n=6):
    if isinstance(x, (float, np.floating)):
        return round(float(x), n)
    if isinstance(x, (np.integer,)):
        return int(x)
    if isinstance(x, dict):
        return {k: rnd(v, n) for k, v in x.items()}
    if isinstance(x, (list, tuple)):
        return [rnd(v, n) for v in x]
    return x


# ------------------------------------------------------------------ inputs

def params(proto: dict, **over) -> dict:
    """Per-segment parameters for one scenario: the protocol's base inputs with `over` replacing any of them."""
    b = dict(proto["base"])
    for k, v in over.items():
        if k not in b:
            raise KeyError(k)
        b[k] = v
    h = 1.0 - (1.0 - b["annual_attrition"]) ** (1.0 / 12.0)
    out = {"shared": b, "seg": {}}
    for s in proto["segment_order"]:
        g = proto["segments"][s]
        R = g["ramp_months"] * b["ramp_scale"]
        K = max(1, math.ceil(R + 0.5))
        ramp = np.array([1.0] + [min(1.0, (k - 0.5) / R) if R > 0 else 1.0 for k in range(1, K + 1)])
        ramp[0] = 0.0                                   # index 0 is unused (states are tenure 1..K)
        ramp[K] = 1.0
        win = min(1.0, g["win_rate"] * b["win_rate_scale"])
        deal = g["deal_mean_usd"] * b["deal_mean_scale"]
        lam = b["attainment"] * g["quota_usd"] / (12.0 * win * deal)
        cyc = max(1.0, g["cycle_mean_months"] * b["cycle_scale"])
        out["seg"][s] = {"quota": float(g["quota_usd"]), "K": K, "R": R, "ramp": ramp, "win": win, "deal": deal,
                         "sigma": b["deal_size_sigma"], "lam_in": b["inbound_share"] * lam,
                         "lam_rep": (1.0 - b["inbound_share"]) * lam, "cycle_extra": cyc - 1.0, "h": h,
                         "fill": 1.0 / b["time_to_fill_months"], "lag_q": b["hiring_lag_months"] / (1.0 + b["hiring_lag_months"]),
                         "cover": b["vacancy_cover"], "ote": float(g["ote_usd"])}
    return out


def cycle_pmf(extra: float, upto: int) -> np.ndarray:
    """P(cycle = j months) for j = 0..upto; the cycle is 1 + Poisson(extra), so index 0 is 0."""
    p = np.zeros(upto + 1)
    p[1:] = stats.poisson.pmf(np.arange(0, upto), extra)
    return p


def stationary(sp: dict) -> np.ndarray:
    """Stationary distribution of an existing territory: index 0 empty, 1..K staffed at tenure k (K = ramped)."""
    K, h, f = sp["K"], sp["h"], sp["fill"]
    P = np.zeros((K + 1, K + 1))
    P[0, 0], P[0, 1] = 1.0 - f, f
    for k in range(1, K + 1):
        P[k, 0] += h
        P[k, min(k + 1, K)] += 1.0 - h
    A = np.vstack([P.T - np.eye(K + 1), np.ones(K + 1)])
    rhs = np.zeros(K + 2)
    rhs[-1] = 1.0
    return np.linalg.lstsq(A, rhs, rcond=None)[0]


# ------------------------------------------------------------------ plans

def top_down(proto: dict) -> dict:
    hc = {s: math.ceil(proto["target_usd"] * g["target_share"] / g["quota_usd"] - 1e-9)
          for s, g in proto["segments"].items()}
    return plan_from(proto, hc)


def plan_from(proto: dict, hc: dict) -> dict:
    """Headcount per segment -> territories: today's, then one per hire in the order hires are added."""
    order = proto["segment_order"]
    hires = []
    for s in order:
        hires += [s] * (hc[s] - proto["segments"][s]["current_reps"])
    return {"headcount": {s: hc[s] for s in order}, "hire_order": hires}


def hire_months(proto: dict, plan: dict) -> dict:
    """Planned start month of each segment's new territories, in segment order; the k-th hire of the year starts in
    hire_start_months[(k - 1) mod 3]."""
    months = proto["hire_start_months"]
    out = {s: [] for s in proto["segment_order"]}
    for k, s in enumerate(plan["hire_order"]):
        out[s].append(months[k % len(months)])
    return out


def quota_capacity(proto: dict, plan: dict) -> float:
    return float(sum(plan["headcount"][s] * proto["segments"][s]["quota_usd"] for s in proto["segment_order"]))


# ------------------------------------------------------------------ expectation (the bottom-up capacity plan)

def expected(proto: dict, prm: dict, plan: dict, step: str = "pipeline_timing") -> dict:
    """Expected bookings of the plan year with the plan bridge's steps switched on up to `step`, plus (at the last
    step) the expected pipeline figures. Order: attainment, start_and_lag, ramp, attrition_vacancy, pipeline_timing.

    Each seat is a vector over [waiting for its first hire, empty, staffed at tenure 1..K]; a seat not yet open is all
    zeros. Before start_and_lag every seat is staffed and ramped all year; before ramp every staffed seat produces at
    full rate; before attrition_vacancy nobody leaves (today's seats start at the stationary tenure mix, given staffed);
    before pipeline_timing a won deal counts in the month it is created."""
    on = STEPS.index(step)
    if on == 0:
        return {"total": quota_capacity(proto, plan)}
    lag_on, ramp_on, attr_on, timing_on = on >= 2, on >= 3, on >= 4, on >= 5
    Y, B = proto["plan_year_months"], proto["burn_in_months"]
    months = list(range(1 - B, Y + 1)) if timing_on else list(range(1, Y + 1))
    starts = hire_months(proto, plan)
    shares = proto["quarter_target_shares"]
    q_first = [1 + 3 * i for i in range(len(shares))]
    by_seg, created, needed = {}, 0.0, 0.0
    open_q = [0.0] * len(shares)
    for s in proto["segment_order"]:
        sp = prm["seg"][s]
        K = sp["K"]
        ramp = sp["ramp"] if ramp_on else np.ones(K + 1)
        h = sp["h"] if attr_on else 0.0
        pi = stationary(sp)
        if attr_on:
            init = pi
        elif ramp_on:
            init = np.concatenate([[0.0], pi[1:] / pi[1:].sum()])
        else:
            init = np.zeros(K + 1)
            init[K] = 1.0
        pmf = cycle_pmf(sp["cycle_extra"], Y + B + 2)
        seats = [None] * proto["segments"][s]["current_reps"] + starts[s]
        book = 0.0
        for m0 in seats:
            v = np.zeros(K + 2)
            if m0 is None:
                v[1:] = init
            elif not lag_on:
                v[K + 1] = 1.0
            for m in months:
                if m0 is not None and lag_on and m == m0:
                    v[:] = 0.0
                    v[0], v[2] = sp["lag_q"], 1.0 - sp["lag_q"]
                staffed_out = float((v[2:] * ramp[1:]).sum())
                staffed = float(v[2:].sum())
                empty = float(v[0] + v[1])
                is_open = staffed + empty
                won_value = sp["deal"] * sp["win"] * (sp["lam_rep"] * staffed_out
                                                      + sp["lam_in"] * (staffed + sp["cover"] * empty))
                if timing_on:
                    hi = Y - m                        # longest cycle that still closes inside the plan year
                    pin = float(pmf[max(1 - m, 0): hi + 1].sum()) if hi >= 1 else 0.0
                    book += won_value * pin
                    opp_value = sp["deal"] * (sp["lam_rep"] * staffed_out + sp["lam_in"] * is_open)
                    if 1 <= m <= Y:
                        created += opp_value
                    for i, a in enumerate(q_first):
                        if m < a:                     # created before the quarter starts and still open at its start
                            open_q[i] += opp_value * float(pmf[a - m:].sum())
                else:
                    book += won_value
                nv = np.zeros_like(v)
                nv[0] = v[0] * sp["lag_q"]
                nv[2] += v[0] * (1.0 - sp["lag_q"])
                nv[1] = v[1] * (1.0 - sp["fill"])
                nv[2] += v[1] * sp["fill"]
                for k in range(1, K + 1):
                    nv[1] += v[k + 1] * h
                    nv[min(k + 1, K) + 1] += v[k + 1] * (1.0 - h)
                v = nv
        by_seg[s] = book
        needed += proto["target_usd"] * proto["segments"][s]["target_share"] / sp["win"]
    out = {"total": float(sum(by_seg.values())), "by_segment": by_seg}
    if timing_on:
        out["pipeline"] = {"created_in_year_usd": created, "needed_usd": needed,
                           "open_at_quarter_start_usd": open_q,
                           "coverage_at_quarter_start": [o / (proto["target_usd"] * sh) for o, sh in zip(open_q, shares)]}
    return out


def bridge(proto: dict, prm: dict, plan: dict) -> dict:
    vals = {st: expected(proto, prm, plan, st)["total"] for st in STEPS}
    pieces = {STEPS[i]: vals[STEPS[i]] - vals[STEPS[i - 1]] for i in range(1, len(STEPS))}
    closure = vals["quota_capacity"] + sum(pieces.values()) - vals["pipeline_timing"]
    return {"steps": vals, "pieces": pieces, "closure_usd": closure}


# ------------------------------------------------------------------ simulation

def _cdf_table(lams: np.ndarray, n: int) -> np.ndarray:
    """Poisson CDF at 0..n-1 for each rate, for inverse-CDF draws from one uniform each."""
    return stats.poisson.cdf(np.arange(n)[None, :], lams[:, None])


def simulate(proto: dict, prm: dict, plan: dict, years: int, seed: int, trace: int | None = None) -> dict:
    """Simulated plan-years: total and quarterly bookings per year, attainment of reps in seat and ramped all year,
    and (with `trace`) the month-by-month record of one year."""
    Y, B = proto["plan_year_months"], proto["burn_in_months"]
    months = list(range(1 - B, Y + 1))
    starts = hire_months(proto, plan)
    nq = len(proto["quarter_target_shares"])
    monthly = np.zeros((years, Y))
    att, overflow = [], 0
    tr = {"territories": []} if trace is not None else None
    for si, s in enumerate(proto["segment_order"]):
        sp = prm["seg"][s]
        K = sp["K"]
        ramp = sp["ramp"]
        pi_cdf = np.cumsum(stationary(sp))
        mu = math.log(sp["deal"]) - sp["sigma"] ** 2 / 2.0
        cyc_cdf = stats.poisson.cdf(np.arange(Y + B + 2), sp["cycle_extra"])
        # rates of won deals per month by state: 0 not open, 1 waiting, 2 empty, 3.. staffed at tenure 1..K
        rate = np.zeros(K + 3)
        rate[1] = rate[2] = sp["win"] * sp["lam_in"] * sp["cover"]
        rate[3:] = sp["win"] * (sp["lam_in"] + sp["lam_rep"] * ramp[1:])
        table = _cdf_table(rate, SLOTS + 1)
        n_today = proto["segments"][s]["current_reps"]
        slots = [None] * n_today + starts[s]
        for ti, m0 in enumerate(slots):
            rng = np.random.default_rng(np.random.SeedSequence(entropy=seed, spawn_key=(si, ti)))
            u0 = rng.random(years)
            if m0 is None:
                state = np.searchsorted(pi_cdf, u0, side="right")       # 0 empty, 1..K tenure
                state = np.where(state > K, K, state) + 2                  # shift: 2 empty, 3.. staffed
            else:
                state = np.zeros(years, dtype=np.int64)
            same = None
            book = np.zeros(years)
            rec = []
            for m in months:
                # a fixed block of uniforms per territory-month: state, count, then a cycle and a size per slot
                U = rng.random((years, 2 + 2 * SLOTS))
                us, uc = U[:, 0], U[:, 1]
                if m0 is not None and m == m0:
                    state = np.where(u0 < 1.0 - sp["lag_q"], 3, 1)       # its own draw, not the month's
                if m == 1:
                    same = state == K + 2
                won = (table[state] < uc[:, None]).sum(axis=1)
                overflow += int((won > SLOTS).sum())
                won = np.minimum(won, SLOTS)
                r_, c_ = np.nonzero(np.arange(SLOTS)[None, :] < won[:, None])     # the live slots only
                close = m + 1 + np.searchsorted(cyc_cdf, U[r_, 2 + c_], side="left")
                size = np.exp(mu + sp["sigma"] * special.ndtri(np.clip(U[r_, 2 + SLOTS + c_], 1e-12, 1.0 - 1e-12)))
                keep = (close >= 1) & (close <= Y)
                r_, close, size = r_[keep], close[keep], size[keep]
                yr_book = np.bincount(r_, weights=size, minlength=years)
                book += yr_book
                if len(r_):
                    monthly += np.bincount(r_ * Y + (close - 1), weights=size, minlength=years * Y).reshape(years, Y)
                if tr is not None:
                    rec.append((m, int(state[trace]), int(won[trace]), float(yr_book[trace])))
                # transition into the next month (the planned start month's own draw opens a new territory)
                if m0 is None or m >= m0:
                    nxt = state.copy()
                    wait = state == 1
                    nxt[wait & (us < 1.0 - sp["lag_q"])] = 3
                    emp = state == 2
                    nxt[emp & (us < sp["fill"])] = 3
                    stf = state >= 3
                    leave = stf & (us < sp["h"])
                    nxt[leave] = 2
                    nxt[stf & ~leave] = np.minimum(state[stf & ~leave] + 1, K + 2)
                    if same is not None and 1 <= m < Y:
                        same &= ~leave
                    state = nxt
            if m0 is None:
                att.append(book[same] / sp["quota"])
            if tr is not None:
                tr["territories"].append({"segment": s, "planned_start": m0, "K": K, "months": rec})
    attainment = np.concatenate(att) if att else np.zeros(0)
    quarter = monthly.reshape(years, nq, Y // nq).sum(axis=2)
    out = {"total": monthly.sum(axis=1), "quarter": quarter, "attainment": attainment, "overflow": overflow,
           "monthly": monthly}
    if tr is not None:
        out["trace"] = tr
    return out


def wilson(x: int, n: int) -> tuple[float, float]:
    if n == 0:
        return 0.0, 0.0
    z2 = Z95 ** 2
    c = (x + z2 / 2.0) / (n + z2)
    h = Z95 * math.sqrt(x * (n - x) / n + z2 / 4.0) / (n + z2)
    return max(0.0, c - h), min(1.0, c + h)


def summary(proto: dict, sim: dict, exp_total: float) -> dict:
    t = sim["total"]
    n = len(t)
    T = proto["target_usd"]
    met = int((t >= T).sum())
    lo, hi = wilson(met, n)
    qs = []
    for q, sh in enumerate(proto["quarter_target_shares"]):
        x = int((sim["quarter"][:, q] >= T * sh).sum())
        ql, qh = wilson(x, n)
        qs.append({"met": x, "share": x / n, "lo": ql, "hi": qh, "target_usd": T * sh,
                   "mean_usd": float(sim["quarter"][:, q].mean())})
    se = float(t.std(ddof=1) / math.sqrt(n))
    a = sim["attainment"]
    return {"years": n, "met": met, "met_share": met / n, "met_lo": lo, "met_hi": hi,
            "mean_usd": float(t.mean()), "mean_se_usd": se, "p10_usd": float(np.percentile(t, 10)),
            "p50_usd": float(np.percentile(t, 50)), "p90_usd": float(np.percentile(t, 90)),
            "mean_pct_of_target": 100.0 * float(t.mean()) / T, "p50_pct_of_target": 100.0 * float(np.percentile(t, 50)) / T,
            "expected_usd": exp_total, "self_test_z": (float(t.mean()) - exp_total) / se if se > 0 else 0.0,
            "quarters": qs, "overflow": sim["overflow"],
            "attainment": {"reps": int(len(a)), "at_or_above_quota_share": float((a >= 1.0).mean()) if len(a) else 0.0,
                           "p10": float(np.percentile(a, 10)) if len(a) else 0.0,
                           "p50": float(np.percentile(a, 50)) if len(a) else 0.0,
                           "p90": float(np.percentile(a, 90)) if len(a) else 0.0,
                           "mean": float(a.mean()) if len(a) else 0.0}}


# ------------------------------------------------------------------ sizing, sweeps

def size_plans(proto: dict, prm: dict, years: int, seed: int) -> tuple[dict, dict, list]:
    """Add one hire at a time (protocol rule) from the top-down headcount: the first plan whose expected bookings reach
    the target, and the first whose target is met in at least the declared share of simulated years."""
    T = proto["target_usd"]
    plan = top_down(proto)
    path, exp_plan = [], None
    for _ in range(60):
        e = expected(proto, prm, plan)
        sim = simulate(proto, prm, plan, years, seed)
        share = float((sim["total"] >= T).mean())
        path.append({"headcount": dict(plan["headcount"]), "expected_usd": e["total"], "met_share": share})
        if exp_plan is None and e["total"] >= T:
            exp_plan = {"headcount": dict(plan["headcount"]), "hire_order": list(plan["hire_order"])}
        if share >= proto["capacity_plan_met_share"]:
            return exp_plan, {"headcount": dict(plan["headcount"]), "hire_order": list(plan["hire_order"])}, path
        ratio = {s: e["by_segment"][s] / (T * proto["segments"][s]["target_share"]) for s in proto["segment_order"]}
        add = min(proto["segment_order"], key=lambda s: (ratio[s], proto["segment_order"].index(s)))
        hc = dict(plan["headcount"])
        hc[add] += 1
        plan = {"headcount": hc, "hire_order": list(plan["hire_order"]) + [add]}
    raise RuntimeError("no plan met the target in the declared share of years within 60 added hires")


def added_cost(proto: dict, base: dict, plan: dict) -> float:
    f = proto["loaded_cost_factor"]
    return float(sum((plan["headcount"][s] - base["headcount"][s]) * proto["segments"][s]["ote_usd"] * f
                     for s in proto["segment_order"]))


def team_cost(proto: dict, plan: dict) -> float:
    f = proto["loaded_cost_factor"]
    return float(sum(plan["headcount"][s] * proto["segments"][s]["ote_usd"] * f for s in proto["segment_order"]))


def worked_year(proto: dict, plan: dict, trace: dict, index: int, total: float, quarters: list) -> dict:
    """One simulated year, traced: when each hire arrived, who left and when, empty seat-months, and how much of the
    year's bookings came from deals created before it."""
    Y = proto["plan_year_months"]
    arrivals, departures, empty, pre, wins = [], [], 0, 0.0, 0
    for t in trace["territories"]:
        K = t["K"]
        rec = t["months"]
        for i, (m, st, won, val) in enumerate(rec):
            if m <= 0:
                pre += val
            else:
                wins += won
                if st in (1, 2):
                    empty += 1
            nxt = rec[i + 1][1] if i + 1 < len(rec) else None
            if t["planned_start"] is not None and st == 3 and (i == 0 or rec[i - 1][1] in (0, 1)) and m >= 1:
                arrivals.append({"segment": t["segment"], "planned": t["planned_start"], "arrived": m})
            if nxt == 2 and st >= 3 and 1 <= m < Y:
                departures.append({"segment": t["segment"], "month": m})
        del K
    return {"index": index, "total_usd": total, "quarters_usd": quarters,
            "quarter_targets_usd": [proto["target_usd"] * sh for sh in proto["quarter_target_shares"]],
            "arrivals": arrivals, "departures": departures, "empty_seat_months": empty,
            "from_pipeline_before_year_usd": pre, "deals_created_in_year_won": wins}


def main(argv: list[str]) -> int:
    out = ROOT / (argv[argv.index("--out") + 1] if "--out" in argv else "results")
    out.mkdir(parents=True, exist_ok=True)
    proto = load_protocol()
    simp = proto["simulation"]
    seed, n_main, n_sweep = simp["seed"], simp["years_main"], simp["years_sweep"]
    T = proto["target_usd"]
    base = params(proto)
    td = top_down(proto)
    exp_plan, plan80, path = size_plans(proto, base, n_main, seed)
    plans = {"top_down": td, "expected": exp_plan, "plan80": plan80}
    res = {"protocol_sha256": hashlib.sha256(PROTOCOL.read_bytes()).hexdigest(), "target_usd": T, "plans": {},
           "sizing_path": path}
    sims = {}
    for name, pl in plans.items():
        e = expected(proto, base, pl)
        sim = simulate(proto, base, pl, n_main, seed)
        sims[name] = sim
        res["plans"][name] = {"headcount": pl["headcount"], "hires": len(pl["hire_order"]),
                              "hire_months": hire_months(proto, pl), "quota_capacity_usd": quota_capacity(proto, pl),
                              "quota_capacity_pct_of_target": 100.0 * quota_capacity(proto, pl) / T,
                              "expected_usd": e["total"], "expected_by_segment_usd": e["by_segment"],
                              "expected_pct_of_target": 100.0 * e["total"] / T, "pipeline": e["pipeline"],
                              "team_cost_usd": team_cost(proto, pl), "added_cost_vs_top_down_usd": added_cost(proto, td, pl),
                              "sim": summary(proto, sim, e["total"])}
    br = bridge(proto, base, td)
    res["bridge_top_down"] = br
    res["gap_top_down"] = {"quota_capacity_minus_expected_usd": br["steps"]["quota_capacity"] - br["steps"]["pipeline_timing"],
                           "target_minus_expected_usd": T - br["steps"]["pipeline_timing"],
                           "shortfall_pct_of_target": 100.0 * (T - br["steps"]["pipeline_timing"]) / T}
    # one-at-a-time
    tor = {}
    for k, (lo, hi) in proto["ranges"].items():
        row = {"low": lo, "high": hi, "base": proto["base"][k]}
        for end, v in (("low", lo), ("high", hi)):
            p = params(proto, **{k: v})
            row[end + "_top_down_expected_pct"] = 100.0 * expected(proto, p, td)["total"] / T
            row[end + "_plan80_met_share"] = float((simulate(proto, p, plan80, n_sweep, seed)["total"] >= T).mean())
        row["swing_top_down_pct"] = abs(row["high_top_down_expected_pct"] - row["low_top_down_expected_pct"])
        row["flips_plan80"] = bool(min(row["low_plan80_met_share"], row["high_plan80_met_share"]) < 0.5)
        tor[k] = row
    res["one_at_a_time"] = tor
    res["plan80_met_share_sweep_size"] = float((simulate(proto, base, plan80, n_sweep, seed)["total"] >= T).mean())
    top2 = sorted(tor, key=lambda k: (-tor[k]["swing_top_down_pct"], list(proto["ranges"]).index(k)))[:2]
    pts = proto["two_way"]["points"]
    gx = [float(v) for v in np.linspace(*proto["ranges"][top2[0]], pts)]
    gy = [float(v) for v in np.linspace(*proto["ranges"][top2[1]], pts)]
    grid_td, grid_80 = [], []
    for y in gy:
        r_td, r_80 = [], []
        for x in gx:
            p = params(proto, **{top2[0]: x, top2[1]: y})
            r_td.append(100.0 * expected(proto, p, td)["total"] / T)
            r_80.append(float((simulate(proto, p, plan80, n_sweep, seed)["total"] >= T).mean()))
        grid_td.append(r_td)
        grid_80.append(r_80)
    res["two_way"] = {"x": top2[0], "y": top2[1], "x_values": gx, "y_values": gy,
                      "top_down_expected_pct": grid_td, "plan80_met_share": grid_80}
    # seeds
    res["seeds"] = {}
    for name in ("top_down", "plan80"):
        rows = []
        for sd in simp["extra_seeds"]:
            s2 = simulate(proto, base, plans[name], n_main, sd)
            rows.append({"seed": sd, "met_share": float((s2["total"] >= T).mean()), "mean_usd": float(s2["total"].mean())})
        res["seeds"][name] = rows
    # worked example: the top-down plan's simulated year at the median of bookings
    t = sims["top_down"]["total"]
    med = int(np.argsort(t, kind="stable")[len(t) // 2])
    tr = simulate(proto, base, td, n_main, seed, trace=med)
    res["worked_year"] = worked_year(proto, td, tr["trace"], med, float(t[med]),
                                     [float(v) for v in sims["top_down"]["quarter"][med]])
    # predictions
    s_td = res["plans"]["top_down"]["sim"]
    p1 = ("supported" if s_td["met_hi"] < 0.10 else "direction only" if s_td["met_share"] < 0.10 else "not supported")
    timing = sum(br["pieces"][k] for k in ("start_and_lag", "ramp", "attrition_vacancy", "pipeline_timing"))
    p2 = "supported" if abs(timing) > abs(br["pieces"]["attainment"]) else "not supported"
    res["predictions"] = {"P1": {"result": p1, "met_share": s_td["met_share"], "upper": s_td["met_hi"]},
                          "P2": {"result": p2, "timing_pieces_usd": timing, "attainment_piece_usd": br["pieces"]["attainment"]}}
    (out / "capacity-results.json").write_text(json.dumps(rnd(res), indent=1, sort_keys=True) + "\n", encoding="utf-8")
    with (out / "capacity-years.csv").open("w", newline="", encoding="utf-8") as fh:
        w = csv.writer(fh, lineterminator="\n")
        w.writerow(["year", "plan", "bookings_usd", "q1_usd", "q2_usd", "q3_usd", "q4_usd"])
        for name in plans:
            sim = sims[name]
            for i in range(n_main):
                w.writerow([i, name, f"{sim['total'][i]:.2f}"] + [f"{v:.2f}" for v in sim["quarter"][i]])
    worst_z = max(abs(res["plans"][n]["sim"]["self_test_z"]) for n in plans)
    over = sum(res["plans"][n]["sim"]["overflow"] for n in plans)
    ok = abs(br["closure_usd"]) < 1e-6 and over == 0 and worst_z < 4.0
    print(f"CAPACITY VERDICT: {'PASS' if ok else 'FAIL'} (bridge closure, by construction, {br['closure_usd']:.2e} USD, overflow {over}, "
          f"largest self-test z {worst_z:.2f}, top-down met {s_td['met_share']:.4f}, "
          f"80% plan headcount {sum(plan80['headcount'].values())})")
    return 0 if ok else 1


if __name__ == "__main__":
    sys.exit(main(sys.argv))
