#!/usr/bin/env python3
"""
Run the **multi-sleeve** merge from a JSON sleeve table (see ``portfolio_merge_engine.py``).

Example::

    cd /Users/robzingale/trading_bot && .venv/bin/python RenTech/strategy_stack/run_multi_sleeve_portfolio.py \\
      --config RenTech/strategy_stack/config/portfolio_sleeves_default.json \\
      --out-prefix RenTech/data/logs/multi_sleeve_default
"""
from __future__ import annotations

import argparse
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))

from RenTech.strategy_stack.portfolio_merge_engine import run_from_config


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    ap.add_argument(
        "--config",
        type=Path,
        default=_REPO / "RenTech/strategy_stack/config/portfolio_sleeves_default.json",
        help="JSON sleeve definition (see repo example).",
    )
    ap.add_argument(
        "--out-prefix",
        type=Path,
        default=_REPO / "RenTech/data/logs/multi_sleeve_default",
        help="Prefix for *_equity_daily.csv, *_ALL_SLEEVES_trade_log.csv, *_manifest.txt",
    )
    ap.add_argument("--total-capital", type=float, default=None, help="Override account.total_capital_usd")
    ap.add_argument("--no-trades", action="store_true", help="Skip combined trade log CSV")
    ap.add_argument("--no-manifest", action="store_true", help="Skip manifest")
    ap.add_argument("-q", "--quiet", action="store_true", help="Less stdout")
    args = ap.parse_args()

    cfg = args.config.expanduser().resolve()
    if not cfg.is_file():
        raise SystemExit(f"Config not found: {cfg}")

    prefix = args.out_prefix.expanduser().resolve()
    prefix.parent.mkdir(parents=True, exist_ok=True)
    eq = prefix.parent / f"{prefix.name}_equity_daily.csv"
    tr = None if args.no_trades else prefix.parent / f"{prefix.name}_ALL_SLEEVES_trade_log.csv"
    mf = None if args.no_manifest else prefix.parent / f"{prefix.name}_manifest.txt"

    print(f"Config: {cfg}", flush=True)
    run_from_config(
        cfg,
        repo_root=_REPO,
        total_capital_override=args.total_capital,
        out_equity_csv=eq,
        out_trade_log_csv=tr,
        out_manifest=mf,
        print_metrics=not args.quiet,
    )


if __name__ == "__main__":
    main()
