"""Chapter 29: the modeled couple, pure-FIRE plan against the synthesis plan.

Deterministic and 2,000-path stochastic models, real (after-tax) dollars,
monthly steps. Uses the unified November 27, 2026 bootstrapped 30-year TIPS
price ($19.74 per $1/yr paid monthly in arrears, equivalent 3.05% flat real
yield).

Synthesis upgrades over Pure FIRE:
  1. Funds a dedicated $20,000/yr experiences-and-gifts earmark from younger
     spouse's age 50 through 64 ($300,000 total).
  2. Keeps the risky options layer untouched through the first 10 years of
     retirement (the sequence-risk danger zone).
  3. Starting in year 11 of retirement, dynamically releases 12%/yr of verified
     surplus above (PV of remaining discretionary spending at TIPS yield +
     $200,000 late-life/LTC contingency reserve).

Run:  python3 scripts/book-models/couple.py
Writes scripts/book-models/out/couple.md
"""

from __future__ import annotations

from dataclasses import dataclass, field, replace
from pathlib import Path

import numpy as np

OUT = Path(__file__).resolve().parent / "out"

# Unified Nov 27, 2026 bootstrapped 30-year monthly-in-arrears TIPS price
TIPS_PRICE_NOV_2026 = 19.74


@dataclass(frozen=True)
class Inputs:
    age_a: float = 45.0  # household clock (younger spouse)
    age_gap_b: float = 2.0  # spouse B is this many years older
    horizon_age_a: float = 95.0
    portfolio: float = 1_200_000.0
    savings: float = 50_000.0  # per year while working
    essential: float = 55_000.0  # per year in retirement
    discretionary: float = 25_000.0  # per year in retirement
    ss_a: float = 12_000.0  # per year, from A's claiming age
    ss_b: float = 15_000.0  # per year, from B's claiming age
    claim_age_a: float = 67.0
    claim_age_b: float = 67.0
    r_accum: float = 0.05  # real equity-heavy accumulation return
    r_retired: float = 0.04  # real 60/40 options/surplus return
    tips_price_30y: float = TIPS_PRICE_NOV_2026
    options_rate: float = 0.035
    experiences: float = 0.0  # per year (synthesis: 20,000)
    exp_start_age_a: float = 50.0
    exp_end_age_a: float = 65.0  # exclusive
    dynamic_release: bool = False  # synthesis: True
    release_delay_months: int = 120  # lock options layer for first 10 yrs
    release_rate: float = 0.12  # release 12%/yr of verified surplus
    ltc_reserve: float = 200_000.0  # preserved late-life/LTC buffer
    rule: str = "layered"  # or "multiple"
    multiple: float = 25.0


SYNTHESIS = {"experiences": 20_000.0, "dynamic_release": True}


@dataclass
class Result:
    inputs: Inputs
    retire_month: int
    ages: np.ndarray
    wealth: np.ndarray
    floor: np.ndarray
    earmark: np.ndarray
    risky: np.ndarray
    floor_at_retirement: float
    bridge_at_retirement: float
    options_at_retirement: float
    earmark_at_retirement: float
    tips_yield: float
    extra_surplus_released: float
    unfunded_essential: np.ndarray = field(repr=False)

    @property
    def retire_age(self) -> float:
        return float(self.ages[self.retire_month])

    def wealth_at(self, age_a: float) -> float:
        return float(self.wealth[int(round((age_a - self.inputs.age_a) * 12))])

    def floor_at(self, age_a: float) -> float:
        return float(self.floor[int(round((age_a - self.inputs.age_a) * 12))])


def annuity_price(y: float, years: float = 30.0) -> float:
    """Cost of $1/yr real income paid monthly in arrears for `years`."""
    if years <= 0:
        return 0.0
    v = (1.0 + y) ** (-1.0 / 12.0)
    n = int(round(years * 12))
    return float(sum(v**j for j in range(1, n + 1)) / 12.0)


def implied_tips_yield(
    price: float = TIPS_PRICE_NOV_2026, years: float = 30.0
) -> float:
    """Flat real yield at which a 30-year monthly stream costs `price` per $1/yr."""
    lo, hi = -0.05, 0.15
    for _ in range(200):
        mid = (lo + hi) / 2.0
        if annuity_price(mid, years) > price:
            lo = mid
        else:
            hi = mid
    return (lo + hi) / 2.0


def pv(flows_per_year: np.ndarray, start: int, y: float) -> float:
    """PV at boundary `start` of monthly flows from month `start` onward."""
    f = flows_per_year[start:] / 12.0
    v = (1.0 + y) ** (-np.arange(1, len(f) + 1) / 12.0)
    return float((f * v).sum())


def schedules(p: Inputs) -> dict[str, np.ndarray]:
    months = int(round((p.horizon_age_a - p.age_a) * 12))
    age = p.age_a + np.arange(months) / 12.0
    ss = np.where(age >= p.claim_age_a, p.ss_a, 0.0) + np.where(
        age + p.age_gap_b >= p.claim_age_b, p.ss_b, 0.0
    )
    need = np.maximum(p.essential - ss, 0.0)
    exp = np.where(
        (age >= p.exp_start_age_a) & (age < p.exp_end_age_a), p.experiences, 0.0
    )
    return {"age": age, "ss": ss, "need": need, "exp": exp, "months": months}


def floor_cost(p: Inputs, start_month: int, y: float | None = None) -> float:
    y = implied_tips_yield(p.tips_price_30y) if y is None else y
    return pv(schedules(p)["need"], start_month, y)


def run(p: Inputs, annual_returns: np.ndarray | None = None) -> Result:
    s = schedules(p)
    months = s["months"]
    y = implied_tips_yield(p.tips_price_30y)
    g_acc = (1.0 + p.r_accum) ** (1.0 / 12.0)
    g_y = (1.0 + y) ** (1.0 / 12.0)
    options = p.discretionary / p.options_rate

    # Precompute remaining discretionary PV factors for fast dynamic release
    rem_disc_pv = np.zeros(months + 1)
    if p.dynamic_release and p.rule == "layered":
        v = (1.0 + y) ** (-1.0 / 12.0)
        disc_mo = p.discretionary / 12.0
        acc = 0.0
        for k in range(months - 1, -1, -1):
            acc = (acc + disc_mo) * v
            rem_disc_pv[k] = acc

    wealth = np.zeros(months + 1)
    floor = np.zeros(months + 1)
    earmark = np.zeros(months + 1)
    risky = np.zeros(months + 1)
    unfunded = np.zeros(months)

    w = p.portfolio
    retire = None
    f = e = r = 0.0
    fl0 = br0 = em0 = 0.0
    extra_released = 0.0

    for k in range(months + 1):
        if retire is None:
            if p.rule == "layered":
                fl = pv(s["need"], k, y) if k < months else 0.0
                em = pv(s["exp"], k, y) if k < months else 0.0
                ok = w >= fl + options + em
            else:
                fl = em = 0.0
                ok = w >= p.multiple * (p.essential + p.discretionary)
            if ok or k == months:
                retire = k
                if p.rule == "layered":
                    f, e, r = fl, em, w - fl - em
                    fl0, em0 = fl, em
                    pre67 = s["need"].copy()
                    pre67[s["age"] >= 67.0] = 0.0
                    br0 = pv(pre67, k, y)
                else:
                    f, e, r = 0.0, 0.0, w
        if retire is None:
            wealth[k] = w
            risky[k] = w
            if k < months:
                w = w * g_acc + (p.savings - s["exp"][k]) / 12.0
            continue
        wealth[k] = f + e + r
        floor[k], earmark[k], risky[k] = f, e, r
        if k == months:
            break

        yr_idx = (k - retire) // 12
        if annual_returns is None:
            g_ret = (1.0 + p.r_retired) ** (1.0 / 12.0)
        else:
            g_ret = (1.0 + float(annual_returns[yr_idx])) ** (1.0 / 12.0)

        if p.rule == "layered":
            f = f * g_y - s["need"][k] / 12.0
            e = e * g_y - s["exp"][k] / 12.0
            extra_mo = 0.0
            if p.dynamic_release and (k - retire) >= p.release_delay_months:
                req = rem_disc_pv[k] + p.ltc_reserve
                surplus = max(0.0, r - req)
                extra_mo = (p.release_rate * surplus) / 12.0
                extra_released += extra_mo
            r = (
                r * g_ret
                - p.discretionary / 12.0
                - extra_mo
                + max(s["ss"][k] - p.essential, 0.0) / 12.0
            )
            if r < 0.0:
                r = 0.0
            if f < -1e-6:
                unfunded[k] = -f
        else:
            spend = p.essential + p.discretionary + s["exp"][k] - s["ss"][k]
            r = r * g_ret - spend / 12.0
            if r < 0:
                unfunded[k] = -r
                r = 0.0

    return Result(
        inputs=p,
        retire_month=retire,
        ages=p.age_a + np.arange(months + 1) / 12.0,
        wealth=wealth,
        floor=floor,
        earmark=earmark,
        risky=risky,
        floor_at_retirement=fl0,
        bridge_at_retirement=br0,
        options_at_retirement=options if p.rule == "layered" else 0.0,
        earmark_at_retirement=em0,
        tips_yield=y,
        extra_surplus_released=extra_released,
        unfunded_essential=unfunded,
    )


def both(p: Inputs = Inputs()) -> tuple[Result, Result]:
    fire = run(replace(p, experiences=0.0, dynamic_release=False))
    synth = run(replace(p, **SYNTHESIS))
    return fire, synth


def stochastic_stress(
    p: Inputs = Inputs(),
    n_paths: int = 2_000,
    sigma: float = 0.10,
    seed: int = 2027,
) -> dict[str, dict[str, float]]:
    """Run paired Monte Carlo sequences on the 60/40 options layer."""
    rng = np.random.default_rng(seed)
    mu_log = float(np.log(1.0 + p.r_retired))
    p_fire = replace(p, experiences=0.0, dynamic_release=False)
    p_synth = replace(p, **SYNTHESIS)

    w85_f, w85_s, rel_s = [], [], []
    depl_f = depl_s = ess_fail_f = ess_fail_s = 0
    for _ in range(n_paths):
        rets = np.exp(rng.normal(mu_log, sigma, size=55)) - 1.0
        rf = run(p_fire, annual_returns=rets)
        rs = run(p_synth, annual_returns=rets)
        w85_f.append(rf.wealth_at(85))
        w85_s.append(rs.wealth_at(85))
        rel_s.append(rs.extra_surplus_released)
        if rf.risky[rf.retire_month :].min() <= 1.0:
            depl_f += 1
        if rs.risky[rs.retire_month :].min() <= 1.0:
            depl_s += 1
        if rf.unfunded_essential.max() > 1e-6:
            ess_fail_f += 1
        if rs.unfunded_essential.max() > 1e-6:
            ess_fail_s += 1

    return {
        "fire": {
            "w85_p10": float(np.percentile(w85_f, 10)),
            "w85_p50": float(np.percentile(w85_f, 50)),
            "w85_p90": float(np.percentile(w85_f, 90)),
            "disc_depl": depl_f / n_paths,
            "ess_funded": 1.0 - ess_fail_f / n_paths,
        },
        "synth": {
            "w85_p10": float(np.percentile(w85_s, 10)),
            "w85_p50": float(np.percentile(w85_s, 50)),
            "w85_p90": float(np.percentile(w85_s, 90)),
            "rel_p10": float(np.percentile(rel_s, 10)),
            "rel_p50": float(np.percentile(rel_s, 50)),
            "rel_p90": float(np.percentile(rel_s, 90)),
            "disc_depl": depl_s / n_paths,
            "ess_funded": 1.0 - ess_fail_s / n_paths,
        },
    }


def fmt_age(a: float) -> str:
    years = int(a + 1e-9)
    months = int(round((a - years) * 12))
    if months == 12:
        years, months = years + 1, 0
    return f"{years} y {months} m"


def k(x: float) -> str:
    return f"${x / 1000:,.0f}k"


def build_report() -> str:
    p = Inputs()
    fire, synth = both(p)
    st = stochastic_stress(p)
    lines = [
        "# Chapter 29 model: the modeled couple (dynamic surplus release)",
        "",
        "Generated by `scripts/book-models/couple.py`. Unified November 27, 2026 "
        f"TIPS price (${p.tips_price_30y:.2f} per $1/yr, equivalent {100 * fire.tips_yield:.2f}% real).",
        "",
        "| Metric | Pure FIRE | Synthesis plan |",
        "|:---|---:|---:|",
        f"| Retires at (A's age) | {fmt_age(fire.retire_age)} | {fmt_age(synth.retire_age)} |",
        f"| Portfolio at retirement | {k(fire.wealth[fire.retire_month])} | {k(synth.wealth[synth.retire_month])} |",
        f"| Floor cost (pre-67 bridge) | {k(fire.floor_at_retirement)} ({k(fire.bridge_at_retirement)}) | {k(synth.floor_at_retirement)} ({k(synth.bridge_at_retirement)}) |",
        f"| Options layer | {k(fire.options_at_retirement)} | {k(synth.options_at_retirement)} |",
        f"| Experiences earmark | $0k | {k(synth.earmark_at_retirement)} |",
        f"| Post-decade verified surplus released | $0k | {k(synth.extra_surplus_released)} |",
        f"| Wealth at 67 | {k(fire.wealth_at(67))} | {k(synth.wealth_at(67))} |",
        f"| Wealth at 85 (floor owed {k(fire.floor_at(85))}) | {k(fire.wealth_at(85))} | {k(synth.wealth_at(85))} |",
        f"| Wealth at 95 | {k(fire.wealth_at(95))} | {k(synth.wealth_at(95))} |",
        "",
        "## Stochastic stress check (2,000 paths, 4% real median, 10% vol, seed 2027)",
        "",
        f"- Pure FIRE W@85: p10 {k(st['fire']['w85_p10'])}, p50 {k(st['fire']['w85_p50'])}, p90 {k(st['fire']['w85_p90'])}, disc trim {100 * st['fire']['disc_depl']:.1f}%",
        f"- Synthesis W@85: p10 {k(st['synth']['w85_p10'])}, p50 {k(st['synth']['w85_p50'])}, p90 {k(st['synth']['w85_p90'])}, disc trim {100 * st['synth']['disc_depl']:.1f}%",
        f"- Synthesis extra released: p10 {k(st['synth']['rel_p10'])}, p50 {k(st['synth']['rel_p50'])}, p90 {k(st['synth']['rel_p90'])}",
        "",
    ]
    return "\n".join(lines)


def main() -> None:
    OUT.mkdir(exist_ok=True)
    report = build_report()
    (OUT / "couple.md").write_text(report)
    print(report)


if __name__ == "__main__":
    main()
