"""Chapter 26 model: Social Security claiming present values at ages 62, 67, and 70.

Evaluates statutory reduction/credit schedules (FRA 67: 0.70 at 62, 1.00 at 67,
1.24 at 70) under Gompertz-calibrated SSA period vs cohort/higher-earner
mortality, pre-tax vs after-tax November 27, 2026 20-year TIPS real yields
(3.05% pre-tax vs ~2.2% after-tax), and the post-2032 78%-payable haircut.

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

from __future__ import annotations

from pathlib import Path

import numpy as np

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

CLAIM_FACTOR = {62: 0.70, 67: 1.00, 70: 1.24}


def survival_curve(e62: float, max_age: int = 105) -> np.ndarray:
    """Smooth Gompertz survival S(age) from age 62 calibrated to exact life expectancy e62."""
    ages = np.arange(62, max_age + 1)
    b = 0.088  # standard U.S. adult mortality slope

    def le(a: float) -> float:
        q = 1.0 - np.exp(-a * np.exp(b * (ages - 62)))
        s = np.ones(len(ages))
        for i in range(1, len(ages)):
            s[i] = s[i - 1] * (1.0 - q[i - 1])
        return float(s[1:].sum() + 0.5)

    lo, hi = 1e-5, 0.2
    for _ in range(80):
        mid = (lo + hi) / 2.0
        if le(mid) > e62:
            lo = mid
        else:
            hi = mid
    a = (lo + hi) / 2.0
    q = 1.0 - np.exp(-a * np.exp(b * (ages - 62)))
    s = np.ones(len(ages))
    for i in range(1, len(ages)):
        s[i] = s[i - 1] * (1.0 - q[i - 1])
    return s


def pv_at_62(
    claim_age: int,
    real_rate: float,
    e62: float,
    cut_year_offset: int | None = None,
    cut_share: float = 0.78,
) -> float:
    """Expected present value at age 62 per $1 of annual FRA (PIA) benefit."""
    s = survival_curve(e62)
    factor = CLAIM_FACTOR[claim_age]
    total = 0.0
    for idx in range(len(s)):
        age = 62 + idx
        if age < claim_age:
            continue
        mult = (
            cut_share
            if (cut_year_offset is not None and idx >= cut_year_offset)
            else 1.0
        )
        total += s[idx] * factor * mult / ((1.0 + real_rate) ** idx)
    return float(total)


def crossover_rate(e62: float, cut_year_offset: int | None = None) -> float:
    """Real discount rate at which claiming at 70 ties claiming at 62."""
    lo, hi = -0.05, 0.10
    for _ in range(80):
        mid = (lo + hi) / 2.0
        if pv_at_62(70, mid, e62, cut_year_offset) > pv_at_62(
            62, mid, e62, cut_year_offset
        ):
            lo = mid
        else:
            hi = mid
    return (lo + hi) / 2.0


def build_report() -> str:
    # SSA 2023 period LE at 62: men 20.3 yrs (age 82.3), women 23.1 yrs (age 85.1)
    # Cohort / higher-earner LE at 62: men ~23.5 yrs (85.5), women ~26.0 yrs (88.0)
    profiles = [
        ("Male, SSA period mortality (e62 = 20.3y)", 20.3),
        ("Female, SSA period mortality (e62 = 23.1y)", 23.1),
        ("Male, cohort / higher-earner (e62 = 23.5y)", 23.5),
        ("Female, cohort / higher-earner (e62 = 26.0y)", 26.0),
    ]
    lines = [
        "# Chapter 26 model: Social Security claiming present values (Nov 27, 2026 curve)",
        "",
        "20-yr Treasury par real yield = 3.05% pre-tax (~2.2% after-tax at 24% federal bracket).",
        "",
        "| Profile | Break-even real rate (70 vs 62) | 78% cut from yr 6 (2032) | PV @ 2.2% after-tax (62 / 70) |",
        "|:---|---:|---:|:---|",
    ]
    for label, e62 in profiles:
        be = crossover_rate(e62)
        be_cut = crossover_rate(e62, cut_year_offset=6)
        pv62 = pv_at_62(62, 0.022, e62)
        pv70 = pv_at_62(70, 0.022, e62)
        lines.append(
            f"| {label} | {100 * be:.2f}% | {100 * be_cut:.2f}% | {pv62:.2f} / {pv70:.2f} |"
        )
    lines.append("")
    return "\n".join(lines)


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


if __name__ == "__main__":
    main()
