"""
================================================================================
Strategy **D009** — ``s009``
================================================================================

Theme
-----
**Bearish MA stack + mid VIX (bear call), distinct band from D001.**

Economic idea
-------------
``SMA20 < SMA50 < SMA200`` identifies a **nested downtrend** configuration on closes. D001
used a **single** death-cross event; this sleeve fires whenever the nested stack holds and
VIX is in **15–26** (tighter than D001’s upper bound). Trade: bear call vertical with a
**wider** wing than D001 to reflect slower bleed preference.

Entry
-----
1. ``sma_20 < sma_50 < sma_200`` (all finite).
2. ``15 <= VIX <= 26``.
3. ``n_contracts[i] >= 80``.

Exit
----
Bear call ``vtc``: 30 DTE, short call delta **0.24**, wing **10** points, hold **9**.
================================================================================
"""

from __future__ import annotations

import math

import pandas as pd

from RenTech.core.options_data_loader import OptionChain
from RenTech.strategy_stack.diverse_theta_strategies_v1.context import ResearchContext

META = {"sid": "D009", "theme": "bear_stack", "title": "SMA20<SMA50<SMA200 + mid VIX bear call wider wing"}

HOLD_SESSIONS = 9
TRADE_KIND = "vtc"
TRADE_PARAMS = (30, 0.24, 10.0)


def wants_entry(i: int, row: pd.Series, ch: OptionChain, spy: float, ctx: ResearchContext) -> bool:
    s20 = row.get("sma_20")
    s50 = row.get("sma_50")
    s200 = row.get("sma_200")
    if any(x is None or pd.isna(x) for x in (s20, s50, s200)):
        return False
    a, b, c = float(s20), float(s50), float(s200)
    if not (a < b < c):
        return False
    vx = ctx.vix(i)
    if not math.isfinite(vx) or vx < 15.0 or vx > 26.0:
        return False
    if ctx.chain_contracts(i) < 80:
        return False
    if not ch.contracts:
        return False
    _ = spy
    return True
