#!/usr/bin/env python3
"""Emit markdown of closed R2a/R2b trades for overlap-portfolio Theta backtest."""
from __future__ import annotations

from pathlib import Path

import pandas as pd

_REPO_ROOT = Path(__file__).resolve().parents[2]
import sys

if str(_REPO_ROOT) not in sys.path:
    sys.path.insert(0, str(_REPO_ROOT))

from RenTech.core.theta_chunks_loader import ThetaChunksLoader, theta_chunks_date_bounds
from RenTech.strategy_stack.vrp_backtester import (
    VRPBacktester,
    load_spy_vix_from_yfinance,
    normalize_spy_df,
    trading_days_intersecting_spy,
)
from RenTech.strategy_stack.vrp_strategy_config import (
    DEFAULT_STRATEGY_CONFIG_PATH,
    apply_strategy_params_to_vrp_backtester_module,
    load_strategy_config_file,
)

_THETA_DIR = _REPO_ROOT / "RenTech" / "data" / "theta_chunks"
_OUT_MD = _REPO_ROOT / "RenTech" / "data" / "logs" / "r2a_r2b_overlap_trade_log.md"


def main() -> None:
    theta_dir = _THETA_DIR
    out_md = _OUT_MD

    d0, d1 = theta_chunks_date_bounds(theta_dir)
    yf_start = (d0 - pd.Timedelta(days=400)).strftime("%Y-%m-%d")
    yf_end = (d1 + pd.Timedelta(days=14)).strftime("%Y-%m-%d")
    spy_wide = normalize_spy_df(load_spy_vix_from_yfinance(yf_start, yf_end))
    ld = ThetaChunksLoader(theta_dir, spy_df=spy_wide)
    days = trading_days_intersecting_spy(ld, spy_wide.index, d0, d1)
    days = [d for d in days if d >= pd.Timestamp("2016-01-04")]
    days = [d for d in days if d <= pd.Timestamp("2019-01-03")]
    if len(days) != 756:
        raise SystemExit(f"expected 756 trading days (VRP_TOGGLE_MATRIX window), got {len(days)}")

    cfg = load_strategy_config_file(DEFAULT_STRATEGY_CONFIG_PATH)
    apply_strategy_params_to_vrp_backtester_module(cfg.strategy_params)

    bt = VRPBacktester(
        ld,
        initial_capital=100_000.0,
        spy_df=spy_wide,
        vol_risk_scaling=False,
        r2_crossover_filters=False,
        dd_risk_scaling=False,
        sleeve_risk_fractions=dict(cfg.sleeve_risk_fractions),
        overlap_portfolio=True,
        overlap_slice_contracts=1,
    )
    bt.run_backtest(trading_days=days, show_progress=False)

    r2a = [t for t in bt.trade_log if t.regime == "diagonal"]
    r2b = [t for t in bt.trade_log if t.regime == "r2_spread"]

    def fmt_row(t) -> str:
        return (
            f"| {pd.Timestamp(t.entry_date).strftime('%Y-%m-%d')} | "
            f"{pd.Timestamp(t.exit_date).strftime('%Y-%m-%d')} | "
            f"{t.days_in_trade} | {t.qty} | {t.pnl_usd:.2f} | {t.exit_reason} | "
            f"{t.initial_net_premium:.2f} | {t.max_margin:.2f} |\n"
        )

    lines: list[str] = []
    lines.append("# R2a + R2b closed trades (overlap portfolio backtest)\n\n")
    lines.append(
        "**Setup (frozen reference):** `RenTech/strategy_stack/VRP_TOGGLE_MATRIX.md` and "
        "`VRP_TOGGLE_MATRIX.json` — this run matches the matrix window **756 sessions "
        "(2016-01-04 → 2019-01-03)**, **$100k** capital, `overlap_portfolio=ON`, "
        "`overlap_slice_contracts=1`, **vol scaling OFF**, **R2 crossover filters OFF**, "
        "**DD scaling OFF**, **macro OFF**, sleeve fractions from `sleeve_risk_fractions.json`.\n\n"
    )
    lines.append(
        "**Engine:** `VRPBacktester` · **R2a** = regime `diagonal` · **R2b** = regime `r2_spread` "
        "(separate exits per ticket).\n\n"
    )
    lines.append(
        f"**Summary:** R2a trades = {len(r2a)} | R2b trades = {len(r2b)} | "
        f"all regimes closed trades = {len(bt.trade_log)}\n"
    )

    for title, trades in (
        ("R2a (diagonal)", r2a),
        ("R2b (r2_spread)", r2b),
    ):
        lines.append(f"\n## {title} — {len(trades)} rows\n\n")
        lines.append(
            "| entry | exit | days | qty | pnl_usd | exit_reason | initial_net_premium | max_margin |\n"
        )
        lines.append(
            "|------:|-----:|-----:|----:|--------:|:------------|--------------------:|-----------:|\n"
        )
        for t in trades:
            lines.append(fmt_row(t))

    out_md.parent.mkdir(parents=True, exist_ok=True)
    out_md.write_text("".join(lines), encoding="utf-8")
    print(f"Wrote {out_md} ({len(r2a)} R2a + {len(r2b)} R2b rows)")


if __name__ == "__main__":
    main()
