import time
from requests.exceptions import ReadTimeout, ConnectionError
from nba_api.stats.endpoints import scoreboardv2
from nba_api.stats.endpoints import playbyplayv2
from nba_api.stats.endpoints import videoevents

# 1. Mandatory anti-blocking custom headers
HEADERS = {
    'Host': 'stats.nba.com',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'en-US,en;q=0.5',
    'Referer': 'https://stats.nba.com/',
    'Connection': 'keep-alive'
}

def get_games_by_date(game_date, timeout_seconds=600):
    """
    Retrieves all game IDs played on a given date (YYYY-MM-DD).
    """
    try:
        print(f"Searching for games on: {game_date}...")
        # Added explicit timeout parameter directly to endpoint
        sb = scoreboardv2.ScoreboardV2(
            game_date=game_date, 
            headers=HEADERS, 
            timeout=timeout_seconds
        )
        games_df = sb.get_data_frames()[0]
        
        return games_df['GAME_ID'].tolist()
    except ReadTimeout:
        print(f"Timeout: NBA server took too long to return games for {game_date}.")
        return []
    except Exception as e:
        print(f"Error fetching scoreboard: {e}")
        return []

def get_video_url(game_id, event_id, timeout_seconds=60):
    """
    Fetches the actual direct .mp4 CDN video URL for an explicit Event ID.
    """
    try:
        # Added explicit timeout parameter directly to endpoint
        video_spec = videoevents.VideoEvents(
            game_id=game_id, 
            game_event_id=event_id,
            headers=HEADERS,
            timeout=timeout_seconds
        ).get_dict()
        
        playlist = video_spec['resultSets']['playlist']
        if not playlist:
            return None
            
        video_uuid = playlist[0]['uuid']
        return f"https://videos.nba.com/nba/pbp/media/{game_id}/{event_id}/{video_uuid}_1280x720.mp4"
    except ReadTimeout:
        return "[Timeout retrieving video asset]"
    except Exception:
        return None

def download_highlights_by_date(target_date):
    """
    Orchestrator to get games by date and map their video highlight play URLs.
    """
    # Step 1: Find all games on that day
    game_ids = get_games_by_date(target_date, timeout_seconds=60)
    
    if not game_ids:
        print("No games found or request timed out.")
        return

    print(f"Found {len(game_ids)} games. Processing video assets...")
    
    # Step 2: Loop through each game found on that date
    for game_id in game_ids:
        print(f"\n--- Processing Game: {game_id} ---")
        try:
            # Added explicit timeout parameter directly to endpoint
            pbp = playbyplayv2.PlayByPlayV2(
                game_id=game_id, 
                headers=HEADERS, 
                timeout=60
            )
            pbp_df = pbp.get_data_frames()[0]
            
            # Filter for successful made baskets (EVENTMSGTYPE == 1)
            made_shots = pbp_df[pbp_df['EVENTMSGTYPE'] == 1].head(3) # Get first 3 highlights as sample
            
            for _, play in made_shots.iterrows():
                event_id = play['EVENTNUM']
                desc = play['HOMEDESCRIPTION'] if play['HOMEDESCRIPTION'] else play['VISITORDESCRIPTION']
                
                print(f"  [Event {event_id}] {desc}")
                
                # Step 3: Fetch video with safe timeout constraints
                video_url = get_video_url(game_id, event_id, timeout_seconds=60)
                if video_url:
                    print(f"    Direct MP4: {video_url}")
                
                # CRITICAL: Prevent the NBA firewall from intentionally timing you out
                time.sleep(1.5)
                
        except ReadTimeout:
            print(f"  Timeout: Skipping play-by-play parsing for Game {game_id}.")
        
        # Space out calls between games
        time.sleep(2.0)

# --- EXECUTION ---
# Format MUST be YYYY-MM-DD
TARGET_DATE = "2025-11-02" 
download_highlights_by_date(TARGET_DATE)
