# %% md
# # TabM 回归训练流程
#
# 使用 TabM (Tabular MLP with Ensembles) 模型进行回归训练。
# TabM 通过内置集成机制（ensemble_size=32）实现高效的多模型集成。
# %% md
# ## 1. 导入依赖
# %%
import os

from src.factors import FactorEngine
from src.training import (
    FactorManager,
    DataPipeline,
    TabMRegressionTask,
    NullFiller,
    Winsorizer,
    StandardScaler,
    CrossSectionalStandardScaler,
)
from src.training.core.trainer_v2 import Trainer
from src.training.components.filters import STFilter
from src.experiment.common import (
    SELECTED_FACTORS,
    FACTOR_DEFINITIONS,
    LABEL_NAME,
    LABEL_FACTOR,
    TRAIN_START,
    TRAIN_END,
    VAL_START,
    VAL_END,
    TEST_START,
    TEST_END,
    stock_pool_filter,
    STOCK_FILTER_REQUIRED_COLUMNS,
    OUTPUT_DIR,
    SAVE_PREDICTIONS,
    SAVE_MODEL,
    get_model_save_path,
    save_model_with_factors,
    TOP_N,
    TRAIN_SKIP_DAYS, STOCK_POOL_SIZE,
)

# 训练类型标识
TRAINING_TYPE = "tabm_regression"

# %% md
# ## 2. 训练特定配置
# %%
# Label 配置（从 common.py 统一导入）
# LABEL_NAME 和 LABEL_FACTOR 已在 common.py 中绑定，只需从 common 导入

# 排除的因子列表（与 LightGBM 回归保持一致）
EXCLUDED_FACTORS = [

]

# TabM 模型参数配置（来自用户提供的示例代码）
MODEL_PARAMS = {
    # ==================== MLP 结构 ====================
    "n_blocks": 3,  # MLP 层数
    "d_block": 256,  # 每层神经元数
    "dropout": 0.5,  # Dropout 率
    # ==================== 集成机制 ====================
    "ensemble_size": 32,  # 内置集成大小（模拟 32 个模型集成）
    # ==================== 训练参数 ====================
    "batch_size": STOCK_POOL_SIZE * 5,  # 批次大小
    "learning_rate": 1e-3,  # 学习率
    "weight_decay": 1e-5,  # 权重衰减
    "epochs": 100,  # 训练轮数
    # ==================== 早停 ====================
    "early_stopping_patience": 30,  # 早停耐心值
}

# 日期范围配置
date_range = {
    "train": (TRAIN_START, TRAIN_END),
    "val": (VAL_START, VAL_END),
    "test": (TEST_START, TEST_END),
}

# 输出配置
output_config = {
    "output_dir": OUTPUT_DIR,
    "output_filename": "tabm_regression_output.csv",
    "save_predictions": SAVE_PREDICTIONS,
    "save_model": SAVE_MODEL,
    "model_save_path": get_model_save_path(TRAINING_TYPE),
    "top_n": TOP_N,
}


def main():
    """主函数"""
    print("\n" + "=" * 80)
    print("TabM 回归模型训练")
    print("=" * 80)

    # 1. 创建 FactorEngine
    print("\n[1] 创建 FactorEngine")
    engine = FactorEngine()

    # 2. 创建 FactorManager
    print("\n[2] 创建 FactorManager")
    factor_manager = FactorManager(
        selected_factors=SELECTED_FACTORS,
        factor_definitions=FACTOR_DEFINITIONS,
        label_factor=LABEL_FACTOR,
        excluded_factors=EXCLUDED_FACTORS,
    )

    # 3. 创建 DataPipeline
    # 【关键】TabM 需要标准化输入，使用 StandardScaler
    # 处理顺序：NullFiller -> Winsorizer -> StandardScaler
    print("\n[3] 创建 DataPipeline")
    pipeline = DataPipeline(
        factor_manager=factor_manager,
        processor_configs=[
            (Winsorizer, {"lower": 0.01, "upper": 0.99}),  # 先缩尾处理厚尾分布
            (NullFiller, {"strategy": "mean"}),
            (StandardScaler, {}),  # TabM 需要标准化输入
        ],
        label_processor_configs=[
            # 对 label 进行缩尾处理（去除极端收益率）
            (Winsorizer, {"lower": 0.01, "upper": 0.99}),
            (StandardScaler, {}),
        ],
        filters=[STFilter(data_router=engine.router)],
        stock_pool_filter_func=stock_pool_filter,
        stock_pool_required_columns=STOCK_FILTER_REQUIRED_COLUMNS,
        train_skip_days=TRAIN_SKIP_DAYS,
    )

    # 4. 创建 TabMRegressionTask
    print("\n[4] 创建 TabMRegressionTask")
    task = TabMRegressionTask(
        model_params=MODEL_PARAMS,
        label_name=LABEL_NAME,
    )

    # 5. 创建 Trainer
    print("\n[5] 创建 Trainer")
    trainer = Trainer(
        data_pipeline=pipeline,
        task=task,
        output_config=output_config,
        verbose=True,
    )

    # 6. 执行训练
    print("\n[6] 执行训练")
    results = trainer.run(engine=engine, date_range=date_range)

    # 7. 绘制训练曲线
    print("\n[7] 绘制训练曲线")
    task.plot_training_metrics(
        output_path=os.path.join(OUTPUT_DIR, "tabm_training_curve.png")
    )

    # 8. 保存模型和因子信息（如果启用）
    if SAVE_MODEL:
        print("\n[8] 保存模型和因子信息")
        save_model_with_factors(
            model=task.get_model(),
            model_path=output_config["model_save_path"],
            selected_factors=SELECTED_FACTORS,
            factor_definitions=FACTOR_DEFINITIONS,
            fitted_processors=pipeline.get_fitted_processors(),
        )

    print("\n" + "=" * 80)
    print("TabM 训练流程完成!")
    print(f"结果保存路径: {os.path.join(OUTPUT_DIR, 'tabm_regression_output.csv')}")
    print("=" * 80)

    return results


if __name__ == "__main__":
    main()
