#!/usr/bin/env python3
from __future__ import annotations

import argparse
from pathlib import Path

import joblib
import pandas as pd

from train_models import FEATURE_COLUMNS, create_features


def recommend_level(conf: float):
    if conf >= 72:
        return '★★★ 强烈推荐', 3
    if conf >= 62:
        return '★★ 推荐', 2
    if conf >= 52:
        return '★ 谨慎推荐', 1
    return '✗ 不建议', 0


def main():
    parser = argparse.ArgumentParser(description='Predict football matches from prepared odds/features CSV')
    parser.add_argument('--input', type=Path, required=True, help='CSV with one row per match')
    parser.add_argument('--models-dir', type=Path, default=Path('models'))
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--default-league-col', type=str, default='联赛代码')
    args = parser.parse_args()

    df = pd.read_csv(args.input)
    if args.default_league_col not in df.columns:
        raise SystemExit(f'输入文件缺少列: {args.default_league_col}')

    features = create_features(df)
    rows = []

    for idx, row in df.iterrows():
        league_code = row[args.default_league_col]
        model_path = args.models_dir / f'{league_code}_pro_v4_model.pkl'
        config_path = args.models_dir / f'{league_code}_pro_v4_config.pkl'
        if not model_path.exists() or not config_path.exists():
            raise FileNotFoundError(f'缺少模型或配置: {league_code}')

        pipe = joblib.load(model_path)
        config = joblib.load(config_path)
        X = pd.DataFrame([features.iloc[idx].reindex(FEATURE_COLUMNS)])
        probs = pipe.predict_proba(X)[0]
        prob_up = float(probs[1] * 100)
        prob_down = float(probs[0] * 100)
        pred = '上盘' if prob_up > prob_down else '下盘'
        conf = max(prob_up, prob_down)
        rec, rec_level = recommend_level(conf)

        out = row.to_dict()
        out.update({
            '上盘概率': round(prob_up, 1),
            '下盘概率': round(prob_down, 1),
            '预测方向': pred,
            '置信度': round(conf, 1),
            '推荐等级': rec,
            '推荐级别': rec_level,
            '模型准确率': round(float(config.get('bet_acc', config.get('test_acc', 0))) * 100, 1),
            '模型类型': config.get('model_name'),
        })
        rows.append(out)

    out_df = pd.DataFrame(rows)
    args.output.parent.mkdir(parents=True, exist_ok=True)
    out_df.to_csv(args.output, index=False, encoding='utf-8-sig')
    print(f'Wrote {len(out_df)} rows to {args.output}')


if __name__ == '__main__':
    main()
