"""
================================================================================
Strategy **D027** — ``s027``  (turn-of-month drift + short put)
================================================================================
**Idea:** First sessions of month sometimes coincide with inflows; sell OTM put with trend filter.
**Entry:** ``1 <= day_of_month <= 3``, ``close > sma_200``, ``VIX < 19``, ``contracts>=90``.
**Exit:** Short put 40 DTE delta **-0.20**, hold **12**.
================================================================================
"""

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": "D027", "theme": "calendar_flow", "title": "Month start + SPY>SMA200 + calm VIX short put"}

HOLD_SESSIONS = 12
TRADE_KIND = "put"
TRADE_PARAMS = (40, -0.20)


def wants_entry(i: int, row: pd.Series, ch: OptionChain, spy: float, ctx: ResearchContext) -> bool:
    dom = row.get("day_of_month")
    if dom is None or pd.isna(dom):
        return False
    d = int(dom)
    if d < 1 or d > 3:
        return False
    s200 = row.get("sma_200")
    if s200 is None or pd.isna(s200) or float(row["close"]) <= float(s200):
        return False
    vx = ctx.vix(i)
    if not math.isfinite(vx) or vx >= 19.0:
        return False
    if ctx.chain_contracts(i) < 90 or not ch.contracts:
        return False
    _ = spy
    return True
