import time
from requests.exceptions import ReadTimeout
from nba_api.stats.static import teams
from nba_api.stats.endpoints import leaguegamefinder
from nba_api.stats.endpoints import playbyplayv2
from nba_api.stats.endpoints import videoevents

# Hardened 2026 browser headers to pass strict playoff/high-traffic firewalls
HEADERS = {
    'Host': 'stats.nba.com',
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36',
    'Accept': 'application/json, text/plain, */*',
    'Accept-Language': 'en-US,en;q=0.9',
    'Referer': 'https://www.nba.com/',
    'Origin': 'https://www.nba.com',
    'Connection': 'keep-alive'
}

def get_team_id(team_abbrev):
    """ Helper to look up unique 10-digit NBA team IDs dynamically (e.g., 'LAL') """
    nba_teams = teams.get_teams()
    match = [t for t in nba_teams if t['abbreviation'] == team_abbrev.upper()]
    if match:
        return match[0]['id']
    raise ValueError(f"Team abbreviation '{team_abbrev}' not recognized.")

def find_game_between_teams(target_date, team_a, team_b, timeout=60):
    """
    Finds the exact Game ID for a matchup on a given date using precise parameter routing.
    date format: 'YYYY-MM-DD'
    """
    id_a = get_team_id(team_a)
    id_b = get_team_id(team_b)
    
    print(f"Searching for {team_a} vs {team_b} on {target_date}...")
    try:
        # LeagueGameFinder matches Team A vs Team B on a concrete date frame
        finder = leaguegamefinder.LeagueGameFinder(
            date_from_nullable=target_date,
            date_to_nullable=target_date,
            team_id_nullable=id_a,
            vs_team_id_nullable=id_b,
            league_id_nullable='00', # Force NBA only
            headers=HEADERS,
            timeout=timeout
        )
        df = finder.get_data_frames()[0]
        
        if df.empty:
            return None
            
        # Return the unique Game ID string
        return df['GAME_ID'].iloc[0]
    except ReadTimeout:
        print("Timeout encountered searching for the game mapping matrix.")
        return None

def get_clip_url(game_id, event_id, timeout=60):
    """ Translates a text timeline event index into an active CDN video stream """
    try:
        video_spec = videoevents.VideoEvents(
            game_id=game_id, game_event_id=event_id, headers=HEADERS, timeout=timeout
        ).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 Exception:
        return None

def get_videos_for_matchup(target_date, team_a, team_b):
    """ Core orchestrator mapping Date + Team A + Team B -> Direct Video Links """
    # Step 1: Find the target Game ID
    game_id = find_game_between_teams(target_date, team_a, team_b, timeout=60)
    
    if not game_id:
        print(f"No game found between {team_a} and {team_b} on {target_date} (or query timed out).")
        return

    print(f"Matchup Verified! Found Game ID: {game_id}. Parsing highlights...")

    try:
        # Step 2: Grab play-by-play timelines
        pbp = playbyplayv2.PlayByPlayV2(game_id=game_id, headers=HEADERS, timeout=60)
        pbp_df = pbp.get_data_frames()[0]
        
        # Filter for successful field goals (EVENTMSGTYPE == 1)
        scoring_plays = pbp_df[pbp_df['EVENTMSGTYPE'] == 1].head(3) # Sample first 3 highlights
        
        for _, play in scoring_plays.iterrows():
            event_id = play['EVENTNUM']
            desc = play['HOMEDESCRIPTION'] if play['HOMEDESCRIPTION'] else play['VISITORDESCRIPTION']
            print(f"\n  - [Event #{event_id}] {desc}")
            
            # Step 3: Extract final MP4 links
            video_url = get_clip_url(game_id, event_id, timeout=60)
            if video_url:
                print(f"    Direct MP4 Link: {video_url}")
            else:
                print("    Video link could not be located.")
                
            # Keep anti-throttling delay active to preserve connection integrity
            time.sleep(1.5)
            
    except ReadTimeout:
        print("The NBA servers took too long to return data for this game's timeline.")

# --- EXECUTION STAGE ---
# Query a classic matchup by date (Format: YYYY-MM-DD)
get_videos_for_matchup(
    target_date="2025-01-20", 
    team_a="GSW", 
    team_b="BOS"
)
