"""Chapter 27 / Appendix A model: funded-ratio income-floor sweep (standalone).

Simulates a 65-year-old retiree over 30 full retirement years (ages 65 to 95,
retirement_age = 65, zero external Social Security so the funded ratio counts
every dollar backing spending) using a transparent 6-asset global 60/40
multivariate-normal return model (10,000 paths per cell, seed 42) and the
unified November 27, 2026 bootstrapped TIPS curve ($19.74 per $1/yr real ->
$1,974,000 for a full $100,000/yr 30-year floor).

Completely standalone (requires only NumPy) so it exports cleanly into the
public companion bundle without private application dependencies.

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

from __future__ import annotations

from pathlib import Path

import numpy as np
from tips_ldi import CURVE_DATE, ladder_price_30y_monthly

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

SEED = 42
N_PATHS = 10_000
YEARS = 30
ANNUAL_SPENDING = 100_000.0
INFLATION = 0.03
TAX_RATE = 0.00  # pre-tax apples-to-apples comparison (both floor & residual taxed identically in a traditional account)

ASSET_NAMES = ["US Eq", "Dev Eq", "EM Eq", "US Bond", "Dev Bond", "EM Bond"]
WEIGHTS = np.array([0.36, 0.18, 0.06, 0.24, 0.12, 0.04])
MEANS_NOMINAL = np.array([0.080, 0.075, 0.085, 0.050, 0.045, 0.060])
STDS = np.array([0.16, 0.18, 0.23, 0.07, 0.09, 0.12])

# Transparent 6x6 correlation matrix (reported directly in Appendix A)
CORR = np.array(
    [
        [1.00, 0.82, 0.72, 0.05, 0.10, 0.35],
        [0.82, 1.00, 0.78, 0.05, 0.20, 0.40],
        [0.72, 0.78, 1.00, 0.05, 0.15, 0.50],
        [0.05, 0.05, 0.05, 1.00, 0.65, 0.45],
        [0.10, 0.20, 0.15, 0.65, 1.00, 0.50],
        [0.35, 0.40, 0.50, 0.45, 0.50, 1.00],
    ]
)

FLOOR_LEVELS = (0.0, 0.25, 0.50, 0.75, 1.0)
RATIOS = (0.50, 0.60, 0.70, 0.80, 0.90, 1.00, 1.10, 1.20)


def portfolio_real_returns(n_paths: int = N_PATHS, seed: int = SEED) -> np.ndarray:
    """Draw annual rebalanced 60/40 real returns (shape: n_paths x YEARS)."""
    cov = np.outer(STDS, STDS) * CORR
    rng = np.random.default_rng(seed)
    draws = rng.multivariate_normal(MEANS_NOMINAL, cov, size=(n_paths, YEARS))
    port_nom = draws @ WEIGHTS
    return (1.0 + port_nom) / (1.0 + INFLATION) - 1.0


def simulate_success(
    funded_ratio: float,
    floor_pct: float,
    real_returns: np.ndarray,
    full_floor_cost: float,
    annual_spending: float = ANNUAL_SPENDING,
    tax_rate: float = TAX_RATE,
) -> float | None:
    """Return probability of paying unfloored real spending across all 30 years."""
    portfolio = full_floor_cost * funded_ratio
    cost = full_floor_cost * floor_pct
    if cost > portfolio + 1e-6:
        return None
    if floor_pct >= 1.0 - 1e-9:
        return 1.0

    bal = np.full(real_returns.shape[0], portfolio - cost, dtype=float)
    unfloored_net = annual_spending * (1.0 - floor_pct)
    gross_draw = unfloored_net / (1.0 - tax_rate)

    for yr in range(real_returns.shape[1]):
        bal -= gross_draw
        bal = np.where(bal > 0.0, bal * (1.0 + real_returns[:, yr]), 0.0)
    return float(np.mean(bal > 0.0))


def run_grid(
    n_paths: int = N_PATHS, seed: int = SEED
) -> tuple[float, dict[float, list[float | None]]]:
    full_cost = ladder_price_30y_monthly() * ANNUAL_SPENDING
    rets = portfolio_real_returns(n_paths=n_paths, seed=seed)
    grid: dict[float, list[float | None]] = {}
    for fr in RATIOS:
        grid[fr] = [simulate_success(fr, lvl, rets, full_cost) for lvl in FLOOR_LEVELS]
    return full_cost, grid


def build_report(n_paths: int = N_PATHS) -> str:
    full_cost, grid = run_grid(n_paths=n_paths)
    lines = [
        "# Chapter 27 funded-ratio floor sweep (standalone)",
        "",
        f"Curve date: {CURVE_DATE}; 30 full retirement years (ages 65–95); "
        f"full $100k/yr floor cost ${full_cost:,.0f}; {n_paths:,} paths, seed {SEED}; "
        f"effective tax rate {100 * TAX_RATE:.0f}% on residual portfolio withdrawals.",
        "",
        "| Funded ratio | No floor | 25% floor | 50% floor | 75% floor | 100% floor |",
        "|---:|---:|---:|---:|---:|---:|",
    ]
    for fr, vals in grid.items():
        cells = ["n/a" if v is None else f"{100 * v:.1f}" for v in vals]
        lines.append(f"| {fr:.2f} | " + " | ".join(cells) + " |")
    lines.append("")
    return "\n".join(lines)


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


if __name__ == "__main__":
    main()
