#!/usr/bin/env python3
"""
Script to populate the games cache with historical data from Aug 2025 to Nov 24, 2025
Run this once to populate the cache, then the app will use it for faster loading
"""
import os
import cfbd
import pickle
from dotenv import load_dotenv
from datetime import datetime

load_dotenv()

# CFBD API setup
api_key = os.getenv('CFBD_API_KEY', '')
configuration = cfbd.Configuration(access_token=api_key)
api_client = cfbd.ApiClient(configuration)

CURRENT_YEAR = datetime.now().year
cache_file = 'games_cache.pkl'

def populate_cache():
    """Fetch and cache all games from weeks 1-15"""
    games_api = cfbd.GamesApi(api_client)
    cached_games = {}
    
    print("Fetching games for caching...")
    for week in range(1, 16):
        try:
            print(f"Fetching week {week}...", end=' ')
            games = games_api.get_games(
                year=CURRENT_YEAR, 
                week=week, 
                season_type='regular', 
                classification='fbs'
            )
            if games:
                cached_games[week] = games
                print(f"✓ {len(games)} games")
            else:
                print("✓ 0 games")
        except Exception as e:
            print(f"✗ Error: {e}")
            continue
    
    # Save to cache file
    try:
        with open(cache_file, 'wb') as f:
            pickle.dump(cached_games, f)
        total_games = sum(len(games) for games in cached_games.values())
        print(f"\n✓ Cache populated with {total_games} total games across {len(cached_games)} weeks")
        print(f"Cache saved to {cache_file}")
    except Exception as e:
        print(f"\n✗ Error saving cache: {e}")

if __name__ == '__main__':
    populate_cache()

