"""Map a gauntlet backtest report (evaluate_constructions output) into BacktestSummary DTOs for the
cockpit. Pure function — no I/O — so it's trivially testable; the CLI does the persistence. Mirrors the
forward_ingest seam (report -> DTOs -> repo.upsert)."""
from __future__ import annotations

from typing import Any

from fxhnt.application.forward_models import BacktestSummary

# Backtest constructions map to the three live equity-factor paper-track strategy ids.
_CONSTRUCTION_TO_SID = {"long": "eqfactor_long", "ls": "eqfactor_ls", "tilt": "eqfactor_tilt"}


def backtest_summaries_from_report(report: dict[str, Any]) -> list[BacktestSummary]:
    """Convert evaluate_constructions(...) output -> one BacktestSummary per construction.

    as_of = the last rebalance date in the run ("" if none). cagr/ann_vol/sharpe/max_drawdown come from
    each construction's `stats`; passed/dsr/is_sharpe/oos_sharpe/pvalue from its `verdict`.
    """
    rebals = report.get("rebalance_dates", [])
    as_of = rebals[-1] if rebals else ""
    out: list[BacktestSummary] = []
    for construction, block in report.get("constructions", {}).items():
        sid = _CONSTRUCTION_TO_SID.get(construction)
        if sid is None:
            continue
        stats = block["stats"]
        verdict = block["verdict"]
        out.append(BacktestSummary(
            strategy_id=sid,
            as_of=as_of,
            cagr=float(stats["cagr"]),
            ann_vol=float(stats["ann_vol"]),
            sharpe=float(stats["sharpe"]),
            max_drawdown=float(stats["max_drawdown"]),
            passed=bool(verdict["passed"]),
            dsr=float(verdict["dsr"]),
            is_sharpe=float(verdict["is_sharpe"]),
            oos_sharpe=float(verdict["oos_sharpe"]),
            pvalue=float(verdict["pvalue"]),
        ))
    return out
