"""
================================================================================
Strategy **D023** — ``s023``
================================================================================

Theme
-----
**Outside OPEX week + high VIX percentile + long convexity.**

Economic idea
-------------
This is the **calendar complement** of D022: require **not** expiry week to avoid pinning
dynamics, but **VIX percentile** over 252 sessions above **0.88** (historically elevated
fear) and buy a **14 DTE** straddle. Distinct from D010 (absolute VIX change) and D012
(level+VRP).

Entry
-----
1. ``is_op_exp_week`` is false.
2. ``vix_pct_rank_252 > 0.88``.
3. ``iv_atm(14)`` exists.
4. ``n_contracts[i] >= 80``.

Exit
----
Long straddle 14 DTE, hold **4** sessions.
================================================================================
"""

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": "D023", "theme": "calendar_opex", "title": "Non-OPEX week + very high VIX pct rank long straddle"}

HOLD_SESSIONS = 4
TRADE_KIND = "sl"
TRADE_PARAMS = (14,)


def wants_entry(i: int, row: pd.Series, ch: OptionChain, spy: float, ctx: ResearchContext) -> bool:
    fl = row.get("is_op_exp_week")
    if fl is None or pd.isna(fl) or bool(fl):
        return False
    pr = row.get("vix_pct_rank_252")
    if pr is None or pd.isna(pr) or float(pr) <= 0.88:
        return False
    if ctx.iv_atm_dte(i, 14) is None:
        return False
    if ctx.chain_contracts(i) < 80:
        return False
    if not ch.contracts:
        return False
    _ = spy
    return True
