#!/usr/bin/env python3
"""
每天凌晨运行：预计算各队最近表现统计
策略：直接拉整个赛季数据，取最近已完成的比赛
"""
import json, time, statistics, requests
from pathlib import Path
from datetime import datetime, timezone, timedelta

API_KEY = '57b64e857ebeffdc156f0c41d43c7894'
BASE = 'https://v3.football.api-sports.io'
HEADERS = {'x-apisports-key': API_KEY}
TZ = timezone(timedelta(hours=8))
CACHE_FILE = Path('artifacts/team_stats_cache.json')

LEAGUE_IDS = {
    'e0':39,'e1':40,'e2':41,'e2n':42,'e3':183,
    'd1':78,'d2':79,'f1':61,'f2':62,
    'i1':135,'i2':136,'sp1':140,'sp2':141,
    'tr1':203,'p1':94,'b1':144,'g1':197,
    'n1':88,'n2':89,'sc1':179,'cz1':345,
    'a1':188,'r1':235,'br1':71,'m1':253,'j1':98,
}

def rate():
    time.sleep(0.35)

def fetch_all_season_results(league_id):
    """获取联赛整季已完成比赛（按日期倒序）"""
    rate()
    r = requests.get(BASE + '/fixtures', params={
        'league': league_id, 'season': 2025,
        'timezone': 'Asia/Shanghai',
    }, timeout=30, headers=HEADERS)

    if r.status_code != 200:
        return []

    fixtures = r.json().get('response', [])
    # 只保留已完成比赛（主队进球非空）
    completed = []
    for fix in fixtures:
        goals = fix.get('goals', {})
        fthg = goals.get('home')
        ftag = goals.get('away')
        if fthg is None or ftag is None:
            continue
        completed.append(fix)

    # 按日期倒序（最近的最前面）
    completed.sort(key=lambda x: x['fixture']['date'], reverse=True)
    return completed

def compute_team_stats(results_dict):
    """为每队计算统计特征（至少需要2场比赛）"""
    stats = {}
    for team, games in results_dict.items():
        if len(games) < 2:
            continue

        wins = [g[0] for g in games]
        gf = [g[1] for g in games]
        ga = [g[2] for g in games]
        n = len(wins)

        # 近10场
        n10 = min(n, 10)
        wr10 = sum(wins[:n10]) / n10

        # 近3场
        n3 = min(n, 3)
        wr3 = sum(wins[:n3]) / n3

        # 势头
        momentum = wr3 - wr10 if n3 >= 3 else 0

        # 近10场胜负序列（补0.5）
        recent = wins[:10] if n >= 10 else wins
        recent = recent + [0.5] * (10 - len(recent))

        # 场均进球/丢球
        gf_avg = sum(gf[:10]) / min(n, 10) if n >= 1 else 1.5
        ga_avg = sum(ga[:10]) / min(n, 10) if n >= 1 else 1.5
        gd_avg = gf_avg - ga_avg

        # 胜率方差
        var = statistics.variance(wins[:10]) if n >= 2 else 0.25

        stats[team] = {
            'win_rate_10': round(wr10, 4),
            'win_rate_3': round(wr3, 4),
            'momentum': round(momentum, 4),
            'recent_form': [round(float(w), 4) for w in recent],
            'goal_diff_avg': round(gd_avg, 4),
            'goals_for_avg': round(gf_avg, 4),
            'goals_against_avg': round(ga_avg, 4),
            'variance': round(var, 4),
            'games_played': n,
            'last_updated': datetime.now(TZ).strftime('%Y-%m-%d'),
        }
    return stats

def main():
    print(f"[{datetime.now(TZ).strftime('%Y-%m-%d %H:%M')}] 开始预计算球队统计...")
    all_stats = {}

    for code, league_id in sorted(LEAGUE_IDS.items()):
        fixtures = fetch_all_season_results(league_id)
        
        # 按队名收集最近比赛
        results = {}
        for fix in fixtures:
            teams = fix.get('teams', {})
            home = teams.get('home', {}).get('name', '')
            away = teams.get('away', {}).get('name', '')
            goals = fix.get('goals', {})
            fthg = int(goals.get('home', 0))
            ftag = int(goals.get('away', 0))
            if not home or not away:
                continue
            home_win = 1 if fthg > ftag else (0.5 if fthg == ftag else 0)
            away_win = 1 if ftag > fthg else (0.5 if fthg == ftag else 0)
            if home not in results:
                results[home] = []
            if away not in results:
                results[away] = []
            results[home].append((home_win, fthg, ftag))
            results[away].append((away_win, ftag, fthg))

        stats = compute_team_stats(results)
        all_stats[code] = stats
        done = sum(1 for f in fixtures)
        total_teams = len(results)
        qualified = len(stats)
        print(f"  {code}: {done}场已完成, {total_teams}队, {qualified}队有统计")

    CACHE_FILE.parent.mkdir(parents=True, exist_ok=True)
    with open(CACHE_FILE, 'w') as f:
        json.dump(all_stats, f, ensure_ascii=False, indent=2)

    total_teams = sum(len(s) for s in all_stats.values())
    print(f"\n✅ 完成！{total_teams}支球队统计已保存到 {CACHE_FILE}")

if __name__ == '__main__':
    main()
