#!/usr/bin/env python3
"""Batch train all leagues for 80%+ accuracy."""

import sys
import subprocess
from pathlib import Path
import json

# Leagues to train (excluding sp1 which is done)
LEAGUES = {
    'a1': {'name': '澳超'},
    'br1': {'name': '巴甲'},
    'd2': {'name': '德乙'},
    'e0': {'name': '英超'},
    'e1': {'name': '英甲'},
    'e2': {'name': '英冠'},
    'f1': {'name': '法甲'},
    'f2': {'name': '法乙'},
    'g1': {'name': '希腊超'},
    'j1': {'name': '日职联'},
    'm1': {'name': '美职联'},
    'r1': {'name': '俄超'},
    'uz1': {'name': '乌兹别克超'},
}

print("="*70)
print("批量训练所有联赛")
print("目标：80%+ 准确率")
print("="*70)

results = []
for league_code, league_info in LEAGUES.items():
    print(f"\n{'='*60}")
    print(f"训练 {league_code} ({league_info['name']})")
    print(f"{'='*60}")
    
    cmd = [sys.executable, 'scripts/train_fast.py', league_code]
    
    try:
        result = subprocess.run(
            cmd,
            capture_output=True,
            text=True,
            timeout=1800,  # 30 minutes per league
            cwd=Path('.').resolve()
        )
        
        # Parse output
        output_lines = result.stdout.split('\n')
        
        # Look for final result
        bet_acc = None
        for line in output_lines:
            if 'Bet accuracy:' in line:
                bet_acc = float(line.split(':')[1].strip().replace('%', ''))
        
        if bet_acc is not None:
            results.append({
                'league': league_code,
                'league_name': league_info['name'],
                'bet_acc': bet_acc,
                'status': 'completed',
                'output': result.stdout[-500:],  # Last 500 chars
            })
            
            status = "✓" if bet_acc >= 0.80 else "✗"
            print(f"  {status} 准确率: {bet_acc:.2%}")
        else:
            results.append({
                'league': league_code,
                'league_name': league_info['name'],
                'bet_acc': 0.0,
                'status': 'failed',
                'error': result.stderr,
            })
            print(f"  ✗ 训练失败")
        
    except subprocess.TimeoutExpired:
        print(f"  ✗ 超时（30分钟）")
        results.append({
            'league': league_code,
            'league_name': league_info['name'],
            'bet_acc': 0.0,
            'status': 'timeout',
        })
    except Exception as e:
        print(f"  ✗ 错误: {e}")
        results.append({
            'league': league_code,
            'league_name': league_info['name'],
            'bet_acc': 0.0,
            'status': 'error',
            'error': str(e),
        })

# Summary
print(f"\n{'='*70}")
print("训练总结")
print(f"{'='*70}")

results_sorted = sorted(results, key=lambda x: x['bet_acc'], reverse=True)

for idx, result in enumerate(results_sorted, 1):
    status = "✓" if result['bet_acc'] >= 0.80 else "✗"
    print(f"  {idx}. {result['league']} ({result['league_name']}): {status}")
    print(f"     准确率: {result['bet_acc']:.2%}")
    print(f"     状态: {result['status']}")

high_accuracy = [r for r in results if r['bet_acc'] >= 0.80]
print(f"\n达到 80%+ 目标的联赛: {len(high_accuracy)}/{len(results)}")

# Save summary
summary_path = Path('experiments/batch_train_summary.json')
with open(summary_path, 'w', encoding='utf-8') as f:
    json.dump(results_sorted, f, ensure_ascii=False, indent=2)

print(f"\n总结已保存到: {summary_path}")
