#!/usr/bin/env python3
"""
Diagnose R1 (weekly strangle) + Theta chunks: raw Parquet vs :class:`ThetaChunksLoader`.

Historical bug: ``get_chain_for_date`` filtered to **puts only** → zero calls in
``OptionChain`` → R1 could not open long-call legs. Fixed in ``theta_chunks_loader.py``
by including both **C** and **P**.
"""

from __future__ import annotations

import sys
from pathlib import Path

_REPO = Path(__file__).resolve().parents[2]
if str(_REPO) not in sys.path:
    sys.path.insert(0, str(_REPO))

import pandas as pd

from RenTech.core.theta_chunks_loader import ThetaChunksLoader

_DEFAULT_THETA = _REPO / "RenTech" / "data" / "theta_chunks"


def main() -> None:
    theta_dir = _DEFAULT_THETA

    sample_p = theta_dir / "spy_1545_2021_03.parquet"
    raw = pd.read_parquet(sample_p)
    r = raw["right"].astype(str).str.upper().str.strip().str[0]
    print("=" * 72)
    print("1) RAW PARQUET (sample month)")
    print(f"   {sample_p.name}: rows={len(raw)}  C≈{(r=='C').sum()}  P≈{(r=='P').sum()}")
    print()

    # Loader needs SPY close for strike filter + BS; use one real session from that file.
    qd = pd.to_datetime(raw["quote_datetime"], utc=True).dt.tz_convert("America/New_York")
    session_dates = pd.to_datetime(qd.dt.date).unique()
    test_day = pd.Timestamp(pd.Timestamp(session_dates[0]).date())

    # Synthetic spy row for that calendar day (price only affects strike band 0.5–1.1×)
    spy = pd.DataFrame(
        {
            "close": [450.0],
            "vix_close": [10.0],
            "sma_200": [400.0],
        },
        index=[test_day],
    )

    print("=" * 72)
    print(f"2) LOADER CHAIN for session {test_day.date()} (minimal spy_df for close={spy['close'].iloc[0]})")
    ld = ThetaChunksLoader(theta_dir, spy_df=spy)
    ch = ld.get_chain_for_date(test_day)
    nc = sum(1 for c in ch.contracts if c.option_type == "C")
    np_ = sum(1 for c in ch.contracts if c.option_type == "P")
    print(f"   contracts={len(ch.contracts)}  calls={nc}  puts={np_}")
    print()

    # Scan first 15 unique session dates in that month
    uniq = sorted({pd.Timestamp(x).normalize() for x in session_dates})[:15]
    calls_any = 0
    for d in uniq:
        spy2 = pd.DataFrame(
            {"close": [450.0], "vix_close": [10.0], "sma_200": [400.0]},
            index=[d],
        )
        ld2 = ThetaChunksLoader(theta_dir, spy_df=spy2)
        ch2 = ld2.get_chain_for_date(d)
        if any(c.option_type == "C" for c in ch2.contracts):
            calls_any += 1
    print("=" * 72)
    print(f"3) Of first {len(uniq)} session dates in sample month, days with ≥1 call in chain: {calls_any}")
    print()

    print("=" * 72)
    print("CONCLUSION")
    print("  • Parquet has large call and put counts.")
    print("  • After fix: loader chains include calls (needed for R1 weekly strangle).")
    print("  • Before fix: get_chain_for_date kept rup=='P' only → calls=0 always.")
    print("=" * 72)


if __name__ == "__main__":
    main()
