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

# Browser-spoofing headers (Mandatory to bypass NBA firewall blocks)
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_game_ids_by_date(target_date, timeout_limit=60):
    """ Finds all Game IDs played on a given date (Format: 'YYYY-MM-DD') """
    try:
        print(f"Scanning NBA schedule for date: {target_date}...")
        sb = scoreboardv2.ScoreboardV2(game_date=target_date, headers=HEADERS, timeout=timeout_limit)
        df = sb.get_data_frames()[0]
        return df['GAME_ID'].tolist()
    except ReadTimeout:
        print(f"Timeout: Scoreboard request took longer than {timeout_limit} seconds.")
        return []
    except Exception as e:
        print(f"Error mapping schedule: {e}")
        return []

def get_mp4_video_url(game_id, event_id, timeout_limit=60):
    """ Connects to NBA's media endpoint to extract the raw .mp4 CDN clip link """
    try:
        video_spec = videoevents.VideoEvents(
            game_id=game_id, game_event_id=event_id, headers=HEADERS, timeout=timeout_limit
        ).get_dict()
        
        playlist = video_spec['resultSets']['playlist']
        if not playlist:
            return None
            
        # The unique asset hash used by NBA.com media players
        video_uuid = playlist[0]['uuid']
        
        # Build the formal CDN download link
        return f"https://videos.nba.com/nba/pbp/media/{game_id}/{event_id}/{video_uuid}_1280x720.mp4"
    except ReadTimeout:
        return "[Timeout retrieving clip uuid]"
    except Exception:
        return None

def process_videos_by_date(game_date):
    """ Main workflow logic """
    game_ids = get_game_ids_by_date(game_date)
    if not game_ids:
        print("No games found on this date or API failed.")
        return

    print(f"Found {len(game_ids)} games. Pulling highlight events...")

    for game_id in game_ids:
        print(f"\nEvaluating Game ID: {game_id}")
        try:
            # Step 2: Grab play-by-play logs for the game
            pbp = playbyplayv2.PlayByPlayV2(game_id=game_id, headers=HEADERS, timeout=60)
            pbp_df = pbp.get_data_frames()[0]
            
            # Filter rows for EVENTMSGTYPE == 1 (Successful Field Goals)
            scoring_plays = pbp_df[pbp_df['EVENTMSGTYPE'] == 1].head(2) # Sample first 2 plays
            
            for _, play in scoring_plays.iterrows():
                event_id = play['EVENTNUM']
                desc = play['HOMEDESCRIPTION'] if play['HOMEDESCRIPTION'] else play['VISITORDESCRIPTION']
                print(f"  - Event #{event_id}: {desc}")
                
                # Step 3: Fetch the direct video stream link
                video_url = get_mp4_video_url(game_id, event_id)
                if video_url:
                    print(f"    Direct Video Link: {video_url}")
                
                # Critical throttle threshold to avoid generating intentional connection hangs
                time.sleep(1.5)
                
        except ReadTimeout:
            print(f"  Timeout threshold breached fetching timeline for Game {game_id}.")
        
        time.sleep(2.0)

# --- RUN THE CODE ---
# Date format MUST be strict YYYY-MM-DD (with leading zeros)
TARGET_DATE = "2026-05-30" 
process_videos_by_date(TARGET_DATE)
