"""Fourth part: patient-flow demand and supply, on a synthetic specialty therapy (DESIGN-patientflow.md).

Every input comes from protocol-patientflow.json, declared before this code existed. The world (a patient funnel,
persistence on therapy, a channel holding stock, a supply limit) runs to month 24, which is all the planner sees. At
month 24 two forecasts of shipments for months 25 to 48 are made: a straight-line trend of shipments, and a patient-flow
forecast reconciled to shipments through planned channel inventory. Their gap is split into six pieces that sum to it.

Writes results/patientflow-results.json, results/patientflow-months.csv and results/patientflow-worlds.csv, and
prints one VERDICT line.

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

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

import numpy as np

ROOT = Path(__file__).resolve().parents[1]
PROTOCOL = ROOT / "protocol-patientflow.json"
PIECES = ("inventory_history", "trend_fit", "new_starts", "discontinuations", "planned_inventory", "supply_ahead")
PATIENT = ("trend_fit", "new_starts", "discontinuations")
Z95 = 1.959963984540054


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


def rnd(x, n=6):
    if isinstance(x, np.ndarray):
        return rnd(x.tolist(), n)
    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


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)


# ------------------------------------------------------------------ the funnel

def hazard(age: int, early: float, late: float, early_months: int) -> float:
    return early if age < early_months else late


def survival(n: int, early: float, late: float, early_months: int) -> np.ndarray:
    """P(a): the share of a start cohort still on therapy a months after its start month (P(0) = 1)."""
    p = np.ones(n + 1)
    for a in range(1, n + 1):
        p[a] = p[a - 1] * (1.0 - hazard(a - 1, early, late, early_months))
    return p


def funnel(w: dict, months: int, referral_scale: float = 1.0, midpoint: float | None = None,
           early: float | None = None, late: float | None = None, rng: np.random.Generator | None = None) -> dict:
    """Starts and patients on therapy by start cohort, months 1..`months`. Expected values without `rng`; every flow
    drawn (Poisson incidence, binomial and multinomial exits, binomial survival) with it."""
    mid = w["adoption_midpoint_month"] if midpoint is None else midpoint
    he = w["early_discontinuation"] if early is None else early
    hl = w["late_discontinuation"] if late is None else late
    U, E, ref_prev = float(w["identified_at_launch"]), float(w["diagnosed_untreated_at_launch"]), 0.0
    cohorts = np.zeros(months + 1)        # on therapy now, by start month (index 1..months)
    ages = np.zeros(months + 1, dtype=np.int64)
    N = np.zeros(months + 1)
    A = np.zeros(months + 1)
    Q = np.zeros(months + 1)
    for t in range(1, months + 1):
        before = cohorts[1:t].sum()
        for c in range(1, t):             # 1. survival of every earlier cohort
            h = hazard(int(ages[c]), he, hl, w["early_months"])
            cohorts[c] = rng.binomial(int(cohorts[c]), 1.0 - h) if rng is not None else cohorts[c] * (1.0 - h)
            ages[c] += 1
        Q[t] = before - cohorts[1:t].sum()
        starts = rng.binomial(int(ref_prev), w["start_share"]) if rng is not None else w["start_share"] * ref_prev
        r = w["referral_rate_max"] * referral_scale / (1.0 + math.exp(-(t - mid) / w["adoption_scale_months"]))
        if rng is not None:               # 3. and 4. the identified and diagnosed pools
            dx, lu, _ = rng.multinomial(int(U), [w["diagnosis_rate"], w["identified_lost_rate"],
                                                 1.0 - w["diagnosis_rate"] - w["identified_lost_rate"]])
            ref, le, _ = rng.multinomial(int(E), [r, w["diagnosed_lost_rate"], 1.0 - r - w["diagnosed_lost_rate"]])
            U = U - dx - lu + rng.poisson(w["incidence_per_month"])
        else:
            dx, lu = U * w["diagnosis_rate"], U * w["identified_lost_rate"]
            ref, le = E * r, E * w["diagnosed_lost_rate"]
            U = U - dx - lu + w["incidence_per_month"]
        E = E - ref - le + dx
        ref_prev = ref
        cohorts[t] = starts
        N[t] = starts
        A[t] = cohorts[1:t + 1].sum()
    return {"N": N, "A": A, "Q": Q, "cohorts_at_end": cohorts.copy()}


def channel(w: dict, D: np.ndarray, months: int) -> dict:
    """Shipments, inventory and dispensed units, months 1..`months`, from demand D (index 1..)."""
    S, I, disp, unmet = np.zeros(months + 1), np.zeros(months + 1), np.zeros(months + 1), 0.0
    inv = 0.0
    for t in range(1, months + 1):
        L = w["launch_fill_units_per_month"] if t <= w["launch_fill_months"] else 0.0
        target = w["weeks_on_hand"] / WEEKS * max(D[t], L)
        s = max(0.0, D[t] + target - inv)
        if t in w["supply_cap_months"]:
            s = min(s, w["supply_cap_units"])
        avail = inv + s
        d = min(D[t], avail)
        unmet += D[t] - d
        inv = avail - d
        S[t], I[t], disp[t] = s, inv, d
    return {"S": S, "I": I, "D": disp, "unmet": unmet}


WEEKS = 4.345


def world(proto: dict, over: dict | None = None, rng: np.random.Generator | None = None) -> dict:
    """What the planner sees at the origin: months 1..origin of shipments, inventory, dispensed units, starts,
    patients on therapy and discontinuations, plus patients on therapy by start month at the origin."""
    w = dict(proto["world"])
    w.update(over or {})
    T = proto["origin_month"]
    f = funnel(w, T, rng=rng)
    D = w["units_per_patient_month"] * f["A"]
    ch = channel(w, D, T)
    return {"N": f["N"], "A": f["A"], "Q": f["Q"], "cohorts": f["cohorts_at_end"], "S": ch["S"], "I": ch["I"],
            "D": ch["D"], "demand": D, "unmet": ch["unmet"], "w": w}


# ------------------------------------------------------------------ the two forecasts and the bridge

def ols_line(y: np.ndarray, first: int, last: int) -> tuple[float, float]:
    x = np.arange(first, last + 1, dtype=float)
    v = y[first:last + 1]
    b = float(((x - x.mean()) * (v - v.mean())).sum() / ((x - x.mean()) ** 2).sum())
    return float(v.mean() - b * x.mean()), b


def forecast(proto: dict, h: dict, plan_over: dict | None = None, method_over: dict | None = None) -> dict:
    """Both forecasts for months origin+1..months, the gap, its six pieces and the divergence summary."""
    T, M = proto["origin_month"], proto["months"]
    w = proto["world"]
    an = dict(proto["plan"]["analogue"])
    pl = {"destock_share": proto["plan"]["destock_share"], "destock_start_month": proto["plan"]["destock_months"][0],
          "supply_cap_ahead_units": proto["plan"]["supply_cap_ahead_units"]}
    mt = {"trend_window_months": proto["trend"]["window_months"],
          "divergence_threshold_pct": proto["divergence_threshold_pct"]}
    for k, v in (plan_over or {}).items():
        (an if k in an else pl)[k] = v
    mt.update(method_over or {})
    months = np.arange(T + 1, M + 1)
    # shipment trend, and the same trend on dispensed units
    lo = T - int(mt["trend_window_months"]) + 1
    a_s, b_s = ols_line(h["S"], lo, T)
    a_d, b_d = ols_line(h["D"], lo, T)
    S_tr = a_s + b_s * months
    D_tr = a_d + b_d * months
    # patient flow: analogue funnel, calibrated on the observed starts
    model = funnel(w, M, referral_scale=an["referral_rate_scale"], midpoint=an["adoption_midpoint_month"],
                   early=an["early_discontinuation"], late=an["late_discontinuation"])
    cal = proto["plan"]["calibration_months"]
    k = float(h["N"][cal].sum() / model["N"][cal].sum())
    N_pf = np.zeros(M + 1)
    N_pf[T + 1:] = k * model["N"][T + 1:]
    P = survival(M, an["early_discontinuation"], an["late_discontinuation"], w["early_months"])
    A_pf = np.zeros(M + 1)
    A_pf[T] = h["A"][T]
    for t in range(T + 1, M + 1):
        carried = sum(h["cohorts"][c] * P[t - c] / P[T - c] for c in range(1, T + 1))
        new = sum(N_pf[s] * P[t - s] for s in range(T + 1, t + 1))
        A_pf[t] = carried + new
    u = float(h["D"][T] / h["A"][T])
    D_pf = u * A_pf
    # planned channel inventory: weeks on hand cut to destock_share in three equal monthly steps
    W0 = h["w"]["weeks_on_hand"]
    m0 = int(pl["destock_start_month"])
    Wp = np.full(M + 1, W0)
    for j in range(1, 4):
        Wp[m0 + j - 1:] = W0 * (1.0 - (1.0 - pl["destock_share"]) * j / 3.0)
    I_plan = np.zeros(M + 1)
    I_plan[T] = h["I"][T]
    I_plan[T + 1:] = Wp[T + 1:] / WEEKS * D_pf[T + 1:]
    dI = np.zeros(M + 1)
    dI[T + 1:] = I_plan[T + 1:] - I_plan[T:M]
    raw = D_pf + dI
    S_pf = np.maximum(raw, 0.0)
    if pl["supply_cap_ahead_units"] is not None:
        S_pf = np.minimum(S_pf, pl["supply_cap_ahead_units"])
    # the bridge
    rr = proto["recent_rate_months"]
    Q_obs = h["Q"]
    Nbar, Qbar = float(h["N"][rr].mean()), float(Q_obs[rr].mean())
    Q_pf = np.zeros(M + 1)
    Q_pf[T + 1:] = A_pf[T:M] + N_pf[T + 1:] - A_pf[T + 1:]
    D_rr = h["D"][T] + u * (months - T) * (Nbar - Qbar)
    pieces = {
        "inventory_history": S_tr - D_tr,
        "trend_fit": D_tr - D_rr,
        "new_starts": u * np.cumsum(Nbar - N_pf[T + 1:]),
        "discontinuations": u * np.cumsum(Q_pf[T + 1:] - Qbar),
        "planned_inventory": -dI[T + 1:],
        "supply_ahead": raw[T + 1:] - S_pf[T + 1:],
    }
    gap = S_tr - S_pf[T + 1:]
    closure = float(np.max(np.abs(gap - sum(pieces.values()))))
    pct = 100.0 * gap / S_pf[T + 1:]
    lead = [max(PIECES, key=lambda p, i=i: (abs(pieces[p][i]), -PIECES.index(p))) for i in range(len(months))]
    thr = mt["divergence_threshold_pct"]
    div = [int(m) for m, v in zip(months, pct) if abs(v) > thr]
    first = None
    if div:
        i = int(div[0] - T - 1)
        first = {"month": div[0], "gap_units": float(gap[i]), "gap_pct": float(pct[i]), "piece": lead[i],
                 "pieces_units": {p: float(pieces[p][i]) for p in PIECES}}
    runs = []
    for m in div:
        i = m - T - 1
        if runs and runs[-1]["end"] == m - 1 and runs[-1]["piece"] == lead[i]:
            runs[-1]["end"] = m
        else:
            runs.append({"start": m, "end": m, "piece": lead[i]})
    # history check of persistence: the analogue survival applied to the observed starts
    hist = list(range(T - 11, T + 1))                  # months 13 to 24, as declared
    back = {t: u * sum(h["N"][s] * P[t - s] for s in range(1, t + 1)) for t in hist}
    back_pct = {t: 100.0 * (back[t] / h["D"][t] - 1.0) for t in hist}
    price = proto["plan"]["net_price_usd_per_unit"]
    return {
        "months": [int(m) for m in months], "S_trend": S_tr, "D_trend": D_tr, "S_pf": S_pf[T + 1:], "D_pf": D_pf[T + 1:],
        "A_pf": A_pf[T + 1:], "N_pf": N_pf[T + 1:], "Q_pf": Q_pf[T + 1:], "dI_plan": dI[T + 1:], "gap": gap, "gap_pct": pct,
        "pieces": pieces, "lead": lead, "closure": closure, "first": first, "divergent_months": div, "runs": runs,
        "calibration": k, "units_per_patient_month": u, "recent_starts": Nbar, "recent_discontinuations": Qbar,
        "trend": {"shipments": [a_s, b_s], "dispensed": [a_d, b_d], "window": [lo, T]},
        "history_check": {"gap_pct_at_origin": back_pct[T], "mean_abs_gap_pct": float(np.mean([abs(v) for v in back_pct.values()]))},
        "summed_gap_units": float(gap.sum()), "summed_gap_usd": float(gap.sum() * price),
        "gap_pct_last": float(pct[-1]), "gap_units_last": float(gap[-1]), "threshold_pct": thr,
    }


def summary(fc: dict) -> dict:
    """The part of a forecast the results keep for a sweep or a noisy world."""
    f = fc["first"]
    return {"first_month": f["month"] if f else None, "first_gap_pct": f["gap_pct"] if f else None,
            "first_gap_units": f["gap_units"] if f else None, "first_piece": f["piece"] if f else None,
            "gap_pct_last": fc["gap_pct_last"], "summed_gap_units": fc["summed_gap_units"],
            "summed_gap_usd": fc["summed_gap_usd"], "history_gap_pct_at_origin": fc["history_check"]["gap_pct_at_origin"],
            "history_mean_abs_gap_pct": fc["history_check"]["mean_abs_gap_pct"], "divergent_months": len(fc["divergent_months"]),
            "closure": fc["closure"]}


def run_sweep(proto: dict, key: str, value) -> dict:
    spec = proto["sweep"][key]
    if spec["kind"] == "world":
        return forecast(proto, world(proto, {key: value}))
    if spec["kind"] in ("analogue", "plan"):
        return forecast(proto, world(proto), plan_over={key: value})
    return forecast(proto, world(proto), method_over={key: value})


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()
    T, M = proto["origin_month"], proto["months"]
    h = world(proto)
    fc = forecast(proto, h)
    hist_identity = float(np.max(np.abs(h["S"][1:] - (h["I"][1:] - np.concatenate([[0.0], h["I"][1:-1]])) - h["D"][1:])))
    res = {"protocol_sha256": hashlib.sha256(PROTOCOL.read_bytes()).hexdigest(),
           "history": {"months": list(range(1, T + 1)), "starts": h["N"][1:], "on_therapy": h["A"][1:],
                       "discontinuations": h["Q"][1:], "dispensed": h["D"][1:], "shipments": h["S"][1:],
                       "inventory": h["I"][1:], "unmet_units": h["unmet"], "identity_max_abs_units": hist_identity,
                       "peak_starts_month": int(np.argmax(h["N"][1:]) + 1), "peak_starts": float(np.max(h["N"][1:]))},
           "base": {k: fc[k] for k in ("months", "first", "divergent_months", "runs", "lead", "calibration",
                                         "units_per_patient_month", "recent_starts", "recent_discontinuations", "trend",
                                         "history_check", "summed_gap_units", "summed_gap_usd", "gap_pct_last",
                                         "gap_units_last", "closure", "threshold_pct")},
           "series": {k: fc[k] for k in ("S_trend", "D_trend", "S_pf", "D_pf", "A_pf", "N_pf", "Q_pf", "dI_plan", "gap",
                                         "gap_pct")},
           "pieces": fc["pieces"]}
    # one at a time
    sw = {}
    worst = fc["closure"]
    for key, spec in proto["sweep"].items():
        row = {"kind": spec["kind"], "low": spec["low"], "high": spec["high"]}
        for end in ("low", "high"):
            f2 = run_sweep(proto, key, spec[end])
            worst = max(worst, f2["closure"])
            row[end] = summary(f2)
        sw[key] = row
    res["one_at_a_time"] = sw
    # noisy worlds
    nz = proto["noise"]
    rows, unmet_worlds = [], 0
    for i in range(nz["worlds"]):
        rng = np.random.default_rng(np.random.SeedSequence(entropy=nz["seed"], spawn_key=(i,)))
        hw = world(proto, rng=rng)
        unmet_worlds += int(hw["unmet"] > 0)
        f2 = forecast(proto, hw)
        worst = max(worst, f2["closure"])
        rows.append(dict(summary(f2), world=i))
    firsts = [r["first_month"] for r in rows if r["first_month"] is not None]
    sizes = [r["first_gap_pct"] for r in rows if r["first_month"] is not None]
    n = len(rows)
    by_piece = {}
    for p in PIECES:
        x = sum(1 for r in rows if r["first_piece"] == p)
        lo, hi = wilson(x, n)
        by_piece[p] = {"worlds": x, "share": x / n, "lo": lo, "hi": hi}
    month_counts = {str(m): firsts.count(m) for m in sorted(set(firsts))}
    res["noisy_worlds"] = {
        "worlds": n, "with_divergence": len(firsts), "worlds_with_unmet_demand": unmet_worlds, "by_piece": by_piece,
        "first_month": {"p10": float(np.percentile(firsts, 10)), "p25": float(np.percentile(firsts, 25)),
                        "median": float(np.median(firsts)), "p75": float(np.percentile(firsts, 75)),
                        "p90": float(np.percentile(firsts, 90)), "min": int(min(firsts)), "max": int(max(firsts)),
                        "counts": month_counts},
        "first_gap_pct": {"p10": float(np.percentile(sizes, 10)), "median": float(np.median(sizes)),
                          "p90": float(np.percentile(sizes, 90))},
        "gap_pct_last": {"p10": float(np.percentile([r["gap_pct_last"] for r in rows], 10)),
                         "median": float(np.median([r["gap_pct_last"] for r in rows])),
                         "p90": float(np.percentile([r["gap_pct_last"] for r in rows], 90))},
        "calibration_note": "planner at base, world noisy"}
    # predictions
    f = fc["first"]
    p1 = "supported" if (f and f["month"] < proto["plan"]["destock_months"][0] and f["piece"] in PATIENT) else "not supported"
    same = by_piece[f["piece"]] if f else {"share": 0.0, "lo": 0.0}
    p2 = ("supported" if same["share"] >= 0.8 and same["lo"] >= 0.75 else
          "direction only" if same["share"] >= 0.8 else "not supported")
    res["predictions"] = {"P1": {"result": p1, "first_month": f["month"] if f else None, "piece": f["piece"] if f else None},
                          "P2": {"result": p2, "share": same["share"], "lo": same["lo"]}}
    res["closure_max_abs_units"] = worst
    (out / "patientflow-results.json").write_text(json.dumps(rnd(res), indent=1, sort_keys=True) + "\n", encoding="utf-8")
    with (out / "patientflow-months.csv").open("w", newline="", encoding="utf-8") as fh:
        wr = csv.writer(fh, lineterminator="\n")
        wr.writerow(["month", "starts", "on_therapy", "dispensed", "shipments", "inventory", "shipment_trend",
                     "patient_flow_shipments", "gap_units", "gap_pct", "largest_piece"] + list(PIECES))
        for t in range(1, T + 1):
            wr.writerow([t, f"{h['N'][t]:.4f}", f"{h['A'][t]:.4f}", f"{h['D'][t]:.4f}", f"{h['S'][t]:.4f}",
                         f"{h['I'][t]:.4f}"] + [""] * (5 + len(PIECES)))
        for i, t in enumerate(fc["months"]):
            wr.writerow([t, f"{fc['N_pf'][i]:.4f}", f"{fc['A_pf'][i]:.4f}", f"{fc['D_pf'][i]:.4f}", "", "",
                         f"{fc['S_trend'][i]:.4f}", f"{fc['S_pf'][i]:.4f}", f"{fc['gap'][i]:.4f}", f"{fc['gap_pct'][i]:.4f}",
                         fc["lead"][i]] + [f"{fc['pieces'][p][i]:.4f}" for p in PIECES])
    with (out / "patientflow-worlds.csv").open("w", newline="", encoding="utf-8") as fh:
        wr = csv.writer(fh, lineterminator="\n")
        cols = ["world", "first_month", "first_gap_pct", "first_piece", "gap_pct_last", "summed_gap_units"]
        wr.writerow(cols)
        for r in rows:
            wr.writerow([r["world"], r["first_month"] if r["first_month"] is not None else "",
                         f"{r['first_gap_pct']:.4f}" if r["first_gap_pct"] is not None else "", r["first_piece"] or "",
                         f"{r['gap_pct_last']:.4f}", f"{r['summed_gap_units']:.2f}"])
    ok = worst < 1e-6 and h["unmet"] == 0 and hist_identity < 1e-6 and f is not None
    print(f"PATIENT FLOW VERDICT: {'PASS' if ok else 'FAIL'} (bridge closure {worst:.2e} units over the base case, "
          f"{2 * len(proto['sweep'])} sweeps and {n} worlds; history identity {hist_identity:.2e}; base unmet "
          f"{h['unmet']:.1f}; first divergence month {f['month'] if f else None}, {f['piece'] if f else None})")
    return 0 if ok else 1


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