"""
================================================================================
Strategy **D017** — ``s017``
================================================================================

Theme
-----
**Contango in ATM IV (back > front) with short OTM strangle.**

Economic idea
-------------
When **40 DTE ATM IV** exceeds **10 DTE ATM IV** by at least **2 points**, longer-dated
variance is priced richer than near variance in **IV space** (not VIX futures). The
sleeve sells a **55 DTE** strangle (different tenor than other strangles) to harvest
term-slope carry while staying OTM.

Entry
-----
1. ``iv40 - iv10 >= 0.02``.
2. ``VIX <= 22``.
3. ``rv_ratio_5_21 < 1.0`` (5d realized vol not above 21d — no fresh vol regime spike).
4. ``n_contracts[i] >= 100``.

Exit
----
Short strangle 55 DTE, put **-0.22**, call **0.15**, hold **10**.
================================================================================
"""

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": "D017", "theme": "iv_term", "title": "ATM IV contango back>front short long-dated strangle"}

HOLD_SESSIONS = 10
TRADE_KIND = "sg"
TRADE_PARAMS = (55, -0.22, 0.15)


def wants_entry(i: int, row, ch: OptionChain, spy: float, ctx: ResearchContext) -> bool:
    a = ctx.iv_atm_dte(i, 40)
    b = ctx.iv_atm_dte(i, 10)
    if a is None or b is None:
        return False
    if a - b < 0.02:
        return False
    vx = ctx.vix(i)
    if not math.isfinite(vx) or vx > 22.0:
        return False
    rr = row.get("rv_ratio_5_21")
    if rr is None or pd.isna(rr) or float(rr) >= 1.0:
        return False
    if ctx.chain_contracts(i) < 100:
        return False
    if not ch.contracts:
        return False
    _ = spy
    return True
