"""Confronto di tutti i portafogli PORT01-06 (backtest in un solo processo).

all_sleeve_equities() è cache-ata: la build (fade+honest+pairs+tsm+shape) avviene una
volta sola, poi i 6 backtest la riusano. Stampa una tabella FULL/OOS e i pesi/rischio.
Run: uv run python scripts/portfolios/compare_all.py
"""
import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[2]
sys.path.insert(0, str(PROJECT_ROOT))

from scripts.portfolios._defs import PORTFOLIOS  # noqa: E402


def run():
    print("=" * 104)
    print("  CONFRONTO PORTAFOGLI PORT01-06 | netto fee, finestra comune 2021-2026, OOS = ultimo 30%")
    print("=" * 104)
    print(f"  {'code':<7s}{'label':<16s}{'n':>3s}{'pesi':>9s}"
          f"{'FULLret':>9s}{'CAGR':>6s}{'DD':>6s}{'Shrp':>6s}  |"
          f"{'OOSret':>8s}{'oDD':>6s}{'oShrp':>7s}")
    print("  " + "-" * 100)
    rows = []
    for code in ("PORT01", "PORT02", "PORT03", "PORT04", "PORT05", "PORT06"):
        p = PORTFOLIOS[code]
        r = p.backtest()
        cap = f"{p.weighting}" + (f"{int(p.caps['PAIRS']*100)}" if p.caps else "")
        print(f"  {p.code:<7s}{p.label:<16s}{len(p.sleeves):>3d}{cap:>9s}"
              f"{r.full['ret']:>+9.0f}{r.full['cagr']:>6.0f}{r.full['dd']:>6.1f}{r.full['sharpe']:>6.2f}  |"
              f"{r.oos['ret']:>+8.0f}{r.oos['dd']:>6.1f}{r.oos['sharpe']:>7.2f}")
        rows.append((code, r))

    # miglior per Sharpe OOS e per DD OOS
    best_sharpe = max(rows, key=lambda x: x[1].oos["sharpe"])
    best_dd = min(rows, key=lambda x: x[1].oos["dd"])
    print("  " + "-" * 100)
    print(f"  miglior Sharpe OOS: {best_sharpe[0]} ({best_sharpe[1].oos['sharpe']:.2f})   "
          f"miglior DD OOS: {best_dd[0]} ({best_dd[1].oos['dd']:.1f}%)")
    print("\n  PORT06 (default) — top contributi al rischio:")
    r6 = dict(rows)["PORT06"]
    top = sorted(r6.risk.items(), key=lambda x: -x[1])[:6]
    print("   " + "  ".join(f"{k}={v:.0f}%" for k, v in top))


if __name__ == "__main__":
    run()
