"""
================================================================================
Strategy **D035** — ``s035``  (55-session close channel tightness)
================================================================================
**Idea:** ``(roll_high_55 - roll_low_55)/close`` measures **close-only** channel width; very
tight channels may precede breaks; here we **sell straddle** when tight and VIX moderate.
**Entry:** ratio ``< 0.035``, ``VIX in [14, 21]``, ``iv_atm(30)>rv21``, ``contracts>=80``.
**Exit:** Short straddle 30 DTE, 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": "D035", "theme": "price_channel", "title": "Tight 55d close channel + VRP short straddle"}

HOLD_SESSIONS = 6
TRADE_KIND = "ss"
TRADE_PARAMS = (30,)


def wants_entry(i: int, row: pd.Series, ch: OptionChain, spy: float, ctx: ResearchContext) -> bool:
    hi = row.get("roll_high_55")
    lo = row.get("roll_low_55")
    c = float(row["close"])
    if hi is None or lo is None or pd.isna(hi) or pd.isna(lo) or c <= 0:
        return False
    ratio = (float(hi) - float(lo)) / c
    if ratio >= 0.035:
        return False
    vx = ctx.vix(i)
    if not math.isfinite(vx) or vx < 14.0 or vx > 21.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, 30)
    if iv is None or iv <= rv:
        return False
    if ctx.chain_contracts(i) < 80 or not ch.contracts:
        return False
    _ = spy
    return True
