"""Chapter 3 model: Alvarez 2027 affordability dispersion, simultaneous reserve,
rent-versus-buy breakeven appreciation, and user cost of owning.

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

from __future__ import annotations

from pathlib import Path

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


def monthly_pi_factor(rate: float, years: int = 30) -> float:
    r = rate / 12.0
    n = years * 12
    return r * (1.0 + r) ** n / ((1.0 + r) ** n - 1.0)


def affordability_ceilings(
    durable_gross: float = 200_000.0,
    rsu_gross: float = 45_000.0,
    financial_assets: float = 447_000.0,
    rent_monthly: float = 3_000.0,
    rate: float = 0.070,
    down_pct: float = 0.20,
    prop_tax: float = 0.011,
    insurance: float = 0.0035,
    maintenance: float = 0.010,
    eff_tax: float = 0.25,
) -> list[tuple[str, str, float]]:
    total_gross = durable_gross + rsu_gross
    pi_rate = (1.0 - down_pct) * monthly_pi_factor(rate)
    piti_rate = pi_rate + (prop_tax + insurance) / 12.0
    full_rate = piti_rate + maintenance / 12.0
    net_base_mo = durable_gross * (1.0 - eff_tax) / 12.0

    return [
        (
            "Lender 45% DTI, all pay credited",
            "Total pay",
            (0.45 * total_gross / 12.0) / piti_rate,
        ),
        (
            "Lender 45% DTI, base salary only",
            "Durable pay",
            (0.45 * durable_gross / 12.0) / piti_rate,
        ),
        (
            "Full housing cost at 28% gross pay",
            "Total pay",
            (0.28 * total_gross / 12.0) / full_rate,
        ),
        ("Price at 20x annual rent", "Local rent", 20.0 * 12.0 * rent_monthly),
        (
            "Mortgage at 2x gross pay",
            "Total pay",
            (2.0 * total_gross) / (1.0 - down_pct),
        ),
        (
            "Full housing at 30% net base pay",
            "Durable pay",
            (0.30 * net_base_mo) / full_rate,
        ),
        ("House at 100% of financial assets", "Net worth", financial_assets),
    ]


def simultaneous_reserve_prices(
    available_cash: float = 180_000.0,
    non_housing_ess: float = 2_580.0,
    rent_monthly: float = 3_000.0,
    reserve_months: int = 6,
    down_pct: float = 0.20,
    buy_close: float = 0.02,
    rate: float = 0.070,
    prop_tax: float = 0.011,
    insurance: float = 0.0035,
    maintenance: float = 0.010,
) -> dict[str, tuple[float, float]]:
    cash_frac = down_pct + buy_close
    full_rate = (1.0 - down_pct) * monthly_pi_factor(rate) + (
        prop_tax + insurance + maintenance
    ) / 12.0
    no_res_price = available_cash / cash_frac
    rent_res = reserve_months * (rent_monthly + non_housing_ess)
    rent_res_price = (available_cash - rent_res) / cash_frac
    post_price = (available_cash - reserve_months * non_housing_ess) / (
        cash_frac + reserve_months * full_rate
    )
    post_res = reserve_months * (non_housing_ess + full_rate * post_price)
    return {
        "no_reserve": (0.0, no_res_price),
        "renting_reserve": (rent_res, rent_res_price),
        "post_purchase_reserve": (post_res, post_price),
    }


def simulate_rent_vs_buy(
    price: float = 600_000.0,
    rent0: float = 3_000.0,
    down_pct: float = 0.20,
    rate: float = 0.070,
    buy_close: float = 0.02,
    sell_close: float = 0.065,
    prop_tax: float = 0.011,
    insurance: float = 0.0035,
    maintenance: float = 0.010,
    rent_growth: float = 0.03,
    home_appr: float = 0.035,
    inv_ret: float = 0.06,
    years: int = 15,
    sec121_exclusion: float = 500_000.0,
) -> tuple[float, float]:
    loan = price * (1.0 - down_pct)
    r_m = rate / 12.0
    pi = loan * monthly_pi_factor(rate)
    r_inv_m = (1.0 + inv_ret) ** (1.0 / 12.0) - 1.0
    r_home_m = (1.0 + home_appr) ** (1.0 / 12.0) - 1.0
    r_rent_m = (1.0 + rent_growth) ** (1.0 / 12.0) - 1.0

    renter = price * (down_pct + buy_close)
    owner_side = 0.0
    bal = loan
    home_val = price
    rent = rent0

    for _ in range(years * 12):
        renter *= 1.0 + r_inv_m
        owner_side *= 1.0 + r_inv_m
        interest = bal * r_m
        principal = min(bal, pi - interest)
        bal -= principal
        owner_cost = pi + home_val * (prop_tax + insurance + maintenance) / 12.0
        diff = owner_cost - rent
        if diff > 0:
            renter += diff
        else:
            owner_side += -diff
        home_val *= 1.0 + r_home_m
        rent *= 1.0 + r_rent_m

    sale_net = home_val * (1.0 - sell_close)
    gain = max(0.0, sale_net - price * (1.0 + buy_close))
    cap_tax = max(0.0, gain - sec121_exclusion) * 0.15
    owner_nw = (sale_net - bal - cap_tax) + owner_side
    return owner_nw, renter


def breakeven_appreciation(years: int, inv_ret: float, **kw) -> float:
    lo, hi = -0.05, 0.15
    for _ in range(70):
        mid = (lo + hi) / 2.0
        o, r = simulate_rent_vs_buy(home_appr=mid, inv_ret=inv_ret, years=years, **kw)
        if o < r:
            lo = mid
        else:
            hi = mid
    return (lo + hi) / 2.0


def build_report() -> str:
    lines = ["# Chapter 3 model: Alvarez 2027 housing & rent-versus-buy", ""]
    lines.append("## Affordability ceilings ($200k base / $245k total, 7.0% 30-yr)")
    lines.append("| Rule | Keyed to | Ceiling |")
    lines.append("|:---|:---|---:|")
    for name, key, val in affordability_ceilings():
        lines.append(f"| {name} | {key} | ${val:,.0f} |")
    lines.append("")
    lines.append("## Breakeven appreciation ($600k house vs $3,000/mo rent, 7.0% loan)")
    lines.append("| Hold | 5% renter | 6% renter | 7% renter | 8% renter |")
    lines.append("|:---|---:|---:|---:|---:|")
    for y in (5, 10, 15, 20):
        vals = [
            f"{100 * breakeven_appreciation(y, r):.2f}%"
            for r in (0.05, 0.06, 0.07, 0.08)
        ]
        lines.append(f"| {y} yrs | " + " | ".join(vals) + " |")
    lines.append("")
    return "\n".join(lines)


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


if __name__ == "__main__":
    main()
