"""Real fat-tail drawdown of the honest book at constant leverage, and the ex-ante leverage ceiling
(K(D*)) — anchored to a REAL drawdown with a stress buffer, never to a smooth modeled curve."""
from __future__ import annotations


def max_drawdown_at_leverage(book_series: dict[int, float], leverage: float) -> float:
    """Worst peak-to-trough drawdown (NEGATIVE) of the book run at constant daily leverage. Returns -1.0
    (wipeout) if any levered day would take equity to zero or below."""
    peak, trough, v = 1.0, 0.0, 1.0
    for d in sorted(book_series):
        step = 1.0 + leverage * book_series[d]
        if step <= 0.0:
            return -1.0
        v *= step
        peak = max(peak, v)
        trough = min(trough, v / peak - 1.0)
    return trough


def leverage_ceiling(book_series: dict[int, float], *, dd_limit: float = -0.35,
                     stress: float = 2.0, grid: tuple[float, ...] = (1.0, 1.25, 1.5, 1.75, 2.0)) -> float:
    """Largest grid leverage whose STRESSED (× `stress`) real drawdown still respects `dd_limit`. Ex-ante
    K(D*): the honest ceiling with a stress buffer, not the smooth-curve fantasy. 0.0 if even 1× fails.
    An empty / no-drawdown book has no REAL drawdown to anchor to -> 0.0 (never max grid leverage)."""
    if not book_series:
        return 0.0
    ok = [L for L in grid if stress * max_drawdown_at_leverage(book_series, L) >= dd_limit]
    return max(ok) if ok else 0.0
