"""
================================================================================
Strategy **D040** — ``s040``  (VIX9D / VIX ratio — near-term fear clock)
================================================================================
**Idea:** If ``vix9d_close / vix_close > 1.14``, near index vol is **rich** vs 30d proxy; buy straddle.
**Entry:** ratio holds, both series finite on panel, ``contracts>=80``.
**Exit:** Long straddle **11** DTE, hold **3**.
================================================================================
"""

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": "D040", "theme": "vix_term_proxy", "title": "VIX9D/VIX elevated long straddle"}

HOLD_SESSIONS = 3
TRADE_KIND = "sl"
TRADE_PARAMS = (11,)


def wants_entry(i: int, row: pd.Series, ch: OptionChain, spy: float, ctx: ResearchContext) -> bool:
    v9 = row.get("vix9d_close")
    vx = row.get("vix_close")
    if v9 is None or vx is None or pd.isna(v9) or pd.isna(vx):
        return False
    f9, fx = float(v9), float(vx)
    if not math.isfinite(f9) or not math.isfinite(fx) or fx <= 0:
        return False
    if f9 / fx <= 1.14:
        return False
    if ctx.chain_contracts(i) < 80 or not ch.contracts:
        return False
    _ = spy
    return True
