"""
================================================================================
Strategy **D031** — ``s031``  (price “pinned” near long MA — short risk reversal)
================================================================================
**Idea:** When SPY is within **0.6%** of ``SMA200``, trend traders may disagree; skew trades can
dominate. Short RR with **different** deltas than D007/D018.
**Entry:** ``abs(close/sma_200 - 1) <= 0.006``, ``skew(30,-0.18,0.12)>0.04``, ``contracts>=90``.
**Exit:** Short RR 30 DTE **-0.18 / 0.10**, hold **6**.
================================================================================
"""

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": "D031", "theme": "ma_pin", "title": "Near SMA200 + steep skew short RR"}

HOLD_SESSIONS = 6
TRADE_KIND = "rr"
TRADE_PARAMS = (30, -0.18, 0.10)


def wants_entry(i: int, row: pd.Series, ch: OptionChain, spy: float, ctx: ResearchContext) -> bool:
    s200 = row.get("sma_200")
    if s200 is None or pd.isna(s200) or float(s200) <= 0:
        return False
    z = abs(float(row["close"]) / float(s200) - 1.0)
    if z > 0.006:
        return False
    sk = ctx.skew_iv_diff(i, 30, -0.18, 0.12)
    if sk is None or sk <= 0.04:
        return False
    if ctx.chain_contracts(i) < 90 or not ch.contracts:
        return False
    _ = spy
    return True
