"""回测绩效报告：与项目回测口径对齐（交易数/收益/PF/胜率/最大回撤）。"""
from __future__ import annotations

from collections import Counter

import pandas as pd

from .engine import BacktestEngine


def summarize(engine: BacktestEngine) -> dict:
    ctx = engine.ctx
    trades = ctx.trade_log
    n = len(trades)
    total_pnl = sum(t.pnl_quote for t in trades)
    wins = [t for t in trades if t.pnl_quote > 0]
    losses = [t for t in trades if t.pnl_quote <= 0]
    gross_win = sum(t.pnl_quote for t in wins)
    gross_loss = abs(sum(t.pnl_quote for t in losses))
    pf = gross_win / gross_loss if gross_loss > 0 else float("inf")

    ret_pct = (ctx.free_wallet - ctx.start_wallet) / ctx.start_wallet * 100

    max_dd = 0.0
    if engine.equity_curve:
        eq = pd.Series([e for _, e in engine.equity_curve])
        dd = (eq - eq.cummax()) / eq.cummax()
        max_dd = float(dd.min() * 100)

    by_close = Counter(t.close_type.value for t in trades)
    return {
        "trades": n,
        "return_pct": round(ret_pct, 2),
        "profit_factor": round(pf, 2),
        "winrate_pct": round(len(wins) / n * 100, 1) if n else 0.0,
        "max_drawdown_pct": round(max_dd, 2),
        "total_fees": round(sum(t.fees_quote for t in trades), 2),
        "final_wallet": round(ctx.free_wallet, 2),
        "by_close_type": dict(by_close),
    }


def print_report(engine: BacktestEngine, title: str = "") -> dict:
    s = summarize(engine)
    print(f"\n{'='*56}\n回测报告 {title}\n{'='*56}")
    print(f"交易数      : {s['trades']}")
    print(f"总收益      : {s['return_pct']:+.2f}%  (钱包 {s['final_wallet']})")
    print(f"盈亏比 PF   : {s['profit_factor']}")
    print(f"胜率        : {s['winrate_pct']}%")
    print(f"最大回撤    : {s['max_drawdown_pct']:.2f}%")
    print(f"总手续费    : {s['total_fees']}")
    print(f"平仓原因分布: {s['by_close_type']}")
    return s
