"""
优化结果数据结构。
"""

from dataclasses import dataclass, field

import pandas as pd

from backtest.report import BacktestReport


@dataclass
class OptimizationResult:
    """单次参数优化结果。"""

    best_params: dict = field(default_factory=dict)
    best_value: float = 0.0
    metric: str = "sharpe"

    best_report: BacktestReport | None = None
    trials_df: pd.DataFrame = field(default_factory=pd.DataFrame)
    param_importance: dict = field(default_factory=dict)

    def summary(self) -> str:
        lines = [
            f"最优参数: {self.best_params}",
            f"最优目标 ({self.metric}): {self.best_value:.4f}",
        ]
        if self.best_report is not None:
            lines.append(f"回测: {self.best_report.summary()}")
        return "\n".join(lines)


@dataclass
class WalkForwardResult:
    """滚动窗口优化结果。"""

    windows: list[dict] = field(default_factory=list)
    consolidated_report: BacktestReport | None = None
    param_stability: pd.DataFrame = field(default_factory=pd.DataFrame)

    def summary(self) -> str:
        n = len(self.windows)
        lines = [f"Walk-Forward: {n} 个窗口"]
        for w in self.windows:
            lines.append(
                f"  {w['train_start']}~{w['train_end']}"
                f" → {w['test_start']}~{w['test_end']}"
                f" | 参数={w.get('best_params', {})}"
                f" | 收益={w.get('test_return', 0):.1f}%"
            )
        if self.consolidated_report is not None:
            lines.append(f"整体: {self.consolidated_report.summary()}")
        if not self.param_stability.empty:
            stds = self.param_stability.std()
            lines.append(f"参数稳定性(std): {dict(stds.round(2))}")
        return "\n".join(lines)
