"""
================================================================================
Strategy **D044** — ``s044``  (Price near **SMA50** band — short straddle)
================================================================================
**Idea:** ``abs(close/sma_50 - 1) <= 0.012`` means SPY is **close** to its 50d mean; paired with
``VIX in [15, 22]`` sell **32** DTE straddle.
**Entry:** band + VIX window + ``iv_atm(32)>rv21``, ``contracts>=80``.
**Exit:** Short straddle 32 DTE, hold **5**.
================================================================================
"""

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": "D044", "theme": "ma_pin", "title": "Near SMA50 band + mid VIX + VRP short straddle"}

HOLD_SESSIONS = 5
TRADE_KIND = "ss"
TRADE_PARAMS = (32,)


def wants_entry(i: int, row: pd.Series, ch: OptionChain, spy: float, ctx: ResearchContext) -> bool:
    s50 = row.get("sma_50")
    if s50 is None or pd.isna(s50) or float(s50) <= 0:
        return False
    z = abs(float(row["close"]) / float(s50) - 1.0)
    if z > 0.012:
        return False
    vx = ctx.vix(i)
    if not math.isfinite(vx) or vx < 15.0 or vx > 22.0:
        return False
    rv = float(row["rv21"]) if pd.notna(row.get("rv21")) else float("nan")
    if not math.isfinite(rv) or rv <= 0:
        return False
    iv = ctx.iv_atm_dte(i, 32)
    if iv is None or iv <= rv:
        return False
    if ctx.chain_contracts(i) < 80 or not ch.contracts:
        return False
    _ = spy
    return True
