"""Property tests for all 7 reproducible book models."""

from __future__ import annotations

import sys
from dataclasses import replace
from pathlib import Path

import numpy as np
import pytest

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

import concentration as conc  # noqa: E402
import couple  # noqa: E402
import funded_ratio_rerun as frr  # noqa: E402
import hold_hurdle as hh  # noqa: E402
import housing_2027 as h27  # noqa: E402
import ss_pv  # noqa: E402
import tips_ldi  # noqa: E402

P = 20_000


def hurdle(gamma=2, **kw):
    kw.setdefault("paths", P)
    return conc.break_even_alpha(conc.simulate(**kw), gamma)


# ---------------------------------------------------------------- Ch 15 concentration


def test_hurdle_vanishes_with_many_stocks():
    assert hurdle(n=500, paths=2_000) < 0.002
    assert hurdle(n=500, paths=2_000, gamma=3) < 0.003


def test_hurdle_zero_without_residual_risk():
    d = conc.simulate(sigma=0.16, sigma_m=0.16, paths=P)
    assert np.allclose(d.w_conc, d.w_index)
    for g in (1, 2, 3):
        assert abs(conc.break_even_alpha(d, g)) < 1e-12


@pytest.mark.parametrize("gamma", [1, 2, 3])
def test_hurdle_increasing_in_residual_correlation(gamma):
    h = [hurdle(gamma, rho_eps=r) for r in (0.0, 0.1, 0.2)]
    assert h[0] < h[1] < h[2]


@pytest.mark.parametrize("gamma", [1, 2, 3])
def test_hurdle_increasing_in_stock_volatility(gamma):
    h = [hurdle(gamma, sigma=s) for s in (0.30, 0.40, 0.50)]
    assert h[0] < h[1] < h[2]


def test_hurdle_increasing_in_risk_aversion():
    d = conc.simulate(paths=P)
    h = [conc.break_even_alpha(d, g) for g in (1, 2, 3)]
    assert 0 < h[0] < h[1] < h[2]


def test_hurdle_decreasing_in_number_of_stocks():
    h = [hurdle(n=n) for n in (1, 5, 10, 30)]
    assert h[0] > h[1] > h[2] > h[3]


def test_buy_and_hold_hurdle_at_least_closed_form():
    for g in (2, 3):
        assert hurdle(g) > conc.closed_form(g)


def test_shortcut_matches_year_by_year_simulation():
    fast = conc.break_even_alpha(conc.simulate(paths=200_000, seed=3), 2)
    slow = conc.break_even_alpha(conc.simulate_annual(paths=20_000, seed=4), 2)
    assert abs(fast - slow) < 0.003


def test_stock_volatility_calibration():
    d = conc.simulate_annual(n=1, years=1, paths=400_000, seed=5)
    assert abs(d.w_conc.std() - conc.BASE["sigma"]) < 0.003
    assert abs(d.w_index.std() - conc.BASE["sigma_m"]) < 0.002
    assert abs(d.w_conc.mean() - 1 - conc.BASE["mu"]) < 0.003


# ---------------------------------------------------------------- Ch 4 hold_hurdle


@pytest.mark.parametrize("case", ["liquidate", "step_up"])
def test_hold_hurdle_increasing_in_weight_sigma_gamma(case):
    ws = [hh.hold_hurdle(w, 2, case=case) for w in (0.1, 0.25, 0.5, 1.0)]
    assert all(a < b for a, b in zip(ws, ws[1:]))
    ss = [hh.hold_hurdle(0.25, 2, case=case, sigma=s) for s in (0.25, 0.33, 0.40)]
    assert all(a < b for a, b in zip(ss, ss[1:]))
    gs = [hh.hold_hurdle(0.25, g, case=case) for g in (1, 2, 3)]
    assert all(a < b for a, b in zip(gs, gs[1:]))


@pytest.mark.parametrize("case", ["liquidate", "step_up"])
def test_deferral_increasing_in_gain_and_tax(case):
    g = [hh.deferral_benefit(gain_share=x, case=case) for x in (0.1, 0.3, 0.55, 0.8)]
    assert all(a < b for a, b in zip(g, g[1:]))
    t = [hh.deferral_benefit(tax=x, case=case) for x in (0.10, 0.15, 0.20, 0.238)]
    assert all(a < b for a, b in zip(t, t[1:]))


def test_no_gain_no_deferral():
    for case in ("liquidate", "step_up"):
        assert abs(hh.deferral_benefit(gain_share=0.0, case=case)) < 1e-12


@pytest.mark.parametrize("case", ["liquidate", "step_up"])
def test_tiny_position_hurdle_is_minus_deferral(case):
    for g in (1, 2, 3):
        h = hh.hold_hurdle(1e-9, g, case=case)
        assert abs(h + hh.deferral_benefit(case=case)) < 1e-9


def test_paycheck_exposure_raises_hurdle():
    for w in (0.1, 0.5):
        assert hh.hold_hurdle(w, 2, phi=0.2) > hh.hold_hurdle(w, 2, phi=0.0)
        assert hh.hold_hurdle(w, 2, phi=0.2, h=1.0) > hh.hold_hurdle(
            w, 2, phi=0.0, h=1.0
        )


def test_total_wealth_human_capital_dilutes_volatility_cost():
    assert hh.volatility_cost(0.25, 2, phi=0.2, h=1.0) == pytest.approx(
        0.5 * hh.volatility_cost(0.25, 2, phi=0.2, h=0.0)
    )
    assert hh.volatility_cost(0.25, 2, phi=0.2, h=2.0) == pytest.approx(
        hh.volatility_cost(0.25, 2, phi=0.2, h=0.0) / 3.0
    )


def test_step_up_deferral_shrinks_over_longer_horizons():
    d10 = hh.deferral_benefit(years=10, case="step_up")
    d30 = hh.deferral_benefit(years=30, case="step_up")
    d40 = hh.deferral_benefit(years=40, case="step_up")
    assert d10 > d30 > d40 > 0


def test_deferral_benefit_solves_its_definition():
    for case in ("liquidate", "step_up"):
        d = hh.deferral_benefit(case=case)
        hold, _ = hh.after_tax_values(r=hh.BASE["r"] - d, case=case)
        _, sell = hh.after_tax_values(case=case)
        if case == "step_up":
            hold = (1 + hh.BASE["r"] - d) ** hh.BASE["years"]
        assert abs(hold - sell) < 1e-9


def test_gamma_one_full_weight_is_half_variance_gap():
    assert abs(hh.volatility_cost(1.0, 1) - 0.5 * (0.33**2 - 0.16**2)) < 1e-12


# ---------------------------------------------------------------- Ch 3 housing_2027


def test_housing_ceilings_order_and_spread():
    rows = h27.affordability_ceilings()
    vals = [v for _, _, v in rows]
    assert vals[0] > vals[-1] * 3.0
    res = h27.simultaneous_reserve_prices()
    assert (
        res["no_reserve"][1]
        > res["renting_reserve"][1]
        > res["post_purchase_reserve"][1]
    )


def test_housing_longer_hold_lowers_breakeven_appreciation():
    b5 = h27.breakeven_appreciation(5, 0.06)
    b15 = h27.breakeven_appreciation(15, 0.06)
    assert b5 > b15 > 0.02


# ---------------------------------------------------------------- Ch 6 & 27 tips_ldi


def test_tips_bootstrap_monotonic_dfs_and_30y_price():
    dfs = tips_ldi.bootstrap_semiannual_dfs()
    assert all(dfs[k] > dfs[k + 1] > 0 for k in range(1, 60))
    p30 = tips_ldi.ladder_price_30y_monthly()
    assert p30 == pytest.approx(19.74, abs=0.02)
    ldi = tips_ldi.ldi_retiree_summary()
    assert ldi["pv_net"] == pytest.approx(1_030_000, abs=15_000)
    assert ldi["duration"] == pytest.approx(12.4, abs=0.2)


# ---------------------------------------------------------------- Ch 26 ss_pv


def test_ss_pv_delay_favored_by_longevity_and_lower_rates():
    be_m = ss_pv.crossover_rate(20.3)
    be_f = ss_pv.crossover_rate(23.1)
    be_cohort = ss_pv.crossover_rate(26.0)
    assert be_m < be_f < be_cohort
    assert ss_pv.crossover_rate(23.1, cut_year_offset=6) < be_f


# ---------------------------------------------------------------- Ch 27 funded_ratio_rerun


def test_funded_ratio_exact_pivot_at_one():
    _, grid = frr.run_grid(n_paths=2_000, seed=42)
    # At funded_ratio == 1.0, every partial floor (0, 25, 50, 75%) ties identically
    row1 = grid[1.00]
    assert row1[0] == pytest.approx(row1[1], abs=1e-9)
    assert row1[0] == pytest.approx(row1[2], abs=1e-9)
    assert row1[0] == pytest.approx(row1[3], abs=1e-9)
    assert row1[4] == 1.0
    # Below 1.0 flooring lowers all-or-nothing success; above 1.0 it raises it
    assert grid[0.80][0] > grid[0.80][2]
    assert grid[1.20][2] > grid[1.20][0]
    # Correlation matrix symmetric & PSD
    assert np.allclose(frr.CORR, frr.CORR.T)
    assert np.linalg.eigvalsh(frr.CORR).min() > 0


# ---------------------------------------------------------------- Ch 29 couple


@pytest.fixture(scope="module")
def plans():
    return couple.both()


def test_no_essential_spending_unfunded(plans):
    for res in plans:
        assert res.unfunded_essential.max() < 1e-6
        after = slice(res.retire_month, None)
        assert res.floor[after].min() > -1e-6
        assert res.risky[after].min() > 0
        assert res.earmark[after].min() > -1e-6


def test_pre_67_years_funded_from_portfolio(plans):
    for res in plans:
        p = res.inputs
        s = couple.schedules(p)
        g = (1 + res.tips_yield) ** (1 / 12)
        months_before_67 = 0
        for k in range(res.retire_month, len(s["age"])):
            if s["age"][k] >= 67:
                break
            paid = res.floor[k] * g - res.floor[k + 1]
            assert paid * 12 == pytest.approx(p.essential - s["ss"][k])
            assert res.floor[k + 1] > 0
            months_before_67 += 1
        assert months_before_67 > 12 * 15
        assert res.bridge_at_retirement > 0


def test_floor_cost_scales_linearly():
    p = couple.Inputs()
    y = couple.implied_tips_yield()
    base = couple.floor_cost(p, 60, y)
    doubled = couple.floor_cost(
        replace(p, essential=2 * p.essential, ss_a=2 * p.ss_a, ss_b=2 * p.ss_b), 60, y
    )
    assert doubled == pytest.approx(2 * base)


def test_tips_price_reproduced():
    y = couple.implied_tips_yield(couple.TIPS_PRICE_NOV_2026)
    assert couple.annuity_price(y) == pytest.approx(
        couple.TIPS_PRICE_NOV_2026, abs=1e-6
    )


def test_retirement_rule_binds(plans):
    for res in plans:
        p = res.inputs
        s = couple.schedules(p)
        y = res.tips_yield
        k = res.retire_month

        def need(m, s=s, y=y, p=p):
            return (
                couple.pv(s["need"], m, y)
                + p.discretionary / p.options_rate
                + couple.pv(s["exp"], m, y)
            )

        assert res.wealth[k] >= need(k)
        assert res.wealth[k - 1] < need(k - 1)


def test_synthesis_retires_later_spends_300k_and_releases_surplus(plans):
    fire, synth = plans
    assert synth.retire_month > fire.retire_month
    s = couple.schedules(synth.inputs)
    assert s["exp"].sum() / 12 == pytest.approx(300_000)
    assert synth.extra_surplus_released > 300_000
    assert synth.wealth_at(85) < fire.wealth_at(85)
    assert synth.wealth_at(95) >= synth.inputs.ltc_reserve


def test_stochastic_stress_preserves_essential_floor():
    st = couple.stochastic_stress(n_paths=200, seed=2027)
    assert st["fire"]["ess_funded"] == 1.0
    assert st["synth"]["ess_funded"] == 1.0
    assert st["synth"]["rel_p50"] > 0
