"""
策略优化快捷函数。

为常用策略提供一键优化入口。
"""

import pandas as pd

from backtest.vectorbt.engine import VectorBTEngine
from optimizer.engine import OptunaEngine
from optimizer.result import OptimizationResult, WalkForwardResult
from optimizer.space import (
    sma_cross_space,
    rsi_revert_space,
    momentum_breakout_space,
    factor_cross_space,
)

_DEFAULT_TRIALS = 100


def optimize_sma_cross(
    price_df: pd.DataFrame,
    factor_df: pd.DataFrame | None = None,
    bt_engine: VectorBTEngine | None = None,
    n_trials: int = _DEFAULT_TRIALS,
    metric: str = "sharpe",
) -> OptimizationResult:
    """均线交叉策略参数寻优。"""
    from backtest.strategies.sma_cross import SMACrossStrategy
    return OptunaEngine(bt_engine).optimize(
        SMACrossStrategy, sma_cross_space, price_df, factor_df, metric, n_trials,
    )


def optimize_rsi_revert(
    price_df: pd.DataFrame,
    factor_df: pd.DataFrame | None = None,
    bt_engine: VectorBTEngine | None = None,
    n_trials: int = _DEFAULT_TRIALS,
    metric: str = "sharpe",
) -> OptimizationResult:
    """RSI 反转策略参数寻优。"""
    from backtest.strategies.rsi_mean_revert import RSIMeanRevertStrategy
    return OptunaEngine(bt_engine).optimize(
        RSIMeanRevertStrategy, rsi_revert_space, price_df, factor_df, metric, n_trials,
    )


def optimize_momentum_breakout(
    price_df: pd.DataFrame,
    factor_df: pd.DataFrame | None = None,
    bt_engine: VectorBTEngine | None = None,
    n_trials: int = _DEFAULT_TRIALS,
    metric: str = "sharpe",
) -> OptimizationResult:
    """动量突破策略参数寻优。"""
    from backtest.strategies.momentum_breakout import MomentumBreakoutStrategy
    return OptunaEngine(bt_engine).optimize(
        MomentumBreakoutStrategy, momentum_breakout_space, price_df, factor_df, metric, n_trials,
    )


def optimize_factor_cross(
    price_df: pd.DataFrame,
    factor_column: str,
    factor_df: pd.DataFrame | None = None,
    bt_engine: VectorBTEngine | None = None,
    n_trials: int = _DEFAULT_TRIALS,
    metric: str = "sharpe",
) -> OptimizationResult:
    """因子阈值交叉策略参数寻优。

    参数:
        factor_column: 因子列名（如 'momentum_20'）
        其余同 optimize_* 系列。
    """
    from backtest.strategies.factor_cross import FactorCrossStrategy

    class _FCS(FactorCrossStrategy):
        def __init__(self, buy_threshold=0, sell_threshold=None):
            super().__init__(factor_column, buy_threshold, sell_threshold)

    return OptunaEngine(bt_engine).optimize(
        _FCS, factor_cross_space, price_df, factor_df, metric, n_trials,
    )
