import pytest
from src.portfolio.base import Portfolio, SleeveSpec
from scripts.analysis.report_families import build_everything
from scripts.analysis.combine_portfolio import port_returns, metrics, SPLIT


def _master9_specs():
    fade = [SleeveSpec(kind="single", name=f"{c}", sid=f"{c}_{a}", asset=a, cluster=f"{a}-rev")
            for a in ("BTC", "ETH") for c in ("MR01", "MR02", "MR07")]
    honest = [SleeveSpec(kind="single", name="DIP01", sid="DIP01_BTC", asset="BTC", cluster="BTC-rev"),
              SleeveSpec(kind="single", name="TR01", sid="TR01_basket", cluster="trend"),
              SleeveSpec(kind="single", name="ROT02", sid="ROT02_rot", cluster="rotation")]
    return fade + honest


def test_master9_backtest_matches_report():
    p = Portfolio(code="PORT03", label="Master", sleeves=_master9_specs(), weighting="equal")
    res = p.backtest()
    S, _, _, _ = build_everything()
    dr_ref = port_returns(S)
    ref_full, ref_oos = metrics(dr_ref), metrics(dr_ref, lo=SPLIT)
    assert res.full["sharpe"] == pytest.approx(ref_full["sharpe"], abs=1e-6)
    assert res.full["dd"] == pytest.approx(ref_full["dd"], abs=1e-6)
    assert res.oos["sharpe"] == pytest.approx(ref_oos["sharpe"], abs=1e-6)
