import nba_api
import time
import requests
import pandas as pd
from nba_api.stats.static import teams, players
from nba_api.stats.endpoints import leaguegamefinder, playbyplayv2

def get_player_matchup_highlights(player_name, team_a_abbr, team_b_abbr, game_date):
    """
    Finds direct video highlights for a player during a matchup on a given date.
    :param game_date: Date string formatted as 'MM/DD/YYYY' (e.g., '12/25/2025')
    """
    # 1. Resolve Team and Player IDs
    try:
        team_a_id = teams.find_team_by_abbreviation(team_a_abbr)['id']
        team_b_id = teams.find_team_by_abbreviation(team_b_abbr)['id']
        player_id = players.find_players_by_full_name(player_name)[0]['id']
    except IndexError:
        print("Error: Could not verify player or team parameters.")
        return None

    print(f"Searching for game on {game_date} between {team_a_abbr} and {team_b_abbr}...")

    # 2. Query LeagueGameFinder to locate the precise Game ID
    # Note: date_from and date_to require 'MM/DD/YYYY' format strings
    game_finder = leaguegamefinder.LeagueGameFinder(
        team_id_nullable=team_a_id,
        date_from_nullable=game_date,
        date_to_nullable=game_date,
        league_id_nullable='00' # Filter for NBA regular/post-season games only
    )
    df_games = game_finder.league_game_finder_results.get_data_frame()

    if df_games.empty:
        print(f"No game found for {team_a_abbr} on {game_date}.")
        return None

    # Filter the results down to verify the opponent matched Team B
    matchup_game = df_games[df_games['VS_TEAM_ID'] == team_b_id]
    if matchup_game.empty:
        print(f"Game found for {team_a_abbr}, but opponent was not {team_b_abbr}.")
        return None

    game_id = matchup_game.iloc[0]['GAME_ID']
    print(f"Match found! Game ID: {game_id}. Parsing play-by-play video assets...")

    # 3. Pull Play-By-Play logs for the discovered Game ID
    pbp = playbyplayv2.PlayByPlayV2(game_id=game_id)
    df_pbp = pbp.play_by_play.get_data_frame()

    # Filter plays where the player is listed as actor 1, 2, or 3
    player_plays = df_pbp[
        (df_pbp['PLAYER1_ID'] == player_id) | 
        (df_pbp['PLAYER2_ID'] == player_id) | 
        (df_pbp['PLAYER3_ID'] == player_id)
    ]

    if player_plays.empty:
        print(f"No specific recorded plays found for {player_name} in this game.")
        return None

    # Modern headers to prevent 403 blocks from the video assets endpoint
    headers = {
        'Host': 'stats.nba.com',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0) Gecko/20100101 Firefox/120.0',
        'Accept': 'application/json, text/plain, */*',
        'Origin': 'https://www.nba.com',
        'Referer': 'https://www.nba.com/',
        'x-nba-stats-origin': 'stats',
        'x-nba-stats-token': 'true'
    }

    highlights = []

    # 4. Loop through player events to fetch direct CDN video links
    for _, row in player_plays.head(10).iterrows(): # Limiting loop to 10 rows to maintain API safety
        event_id = row['GAME_EVENT_ID']
        description = row['HOMEDESCRIPTION'] if row['HOMEDESCRIPTION'] else row['VISITORDESCRIPTION']
        
        video_endpoint = f"https://stats.nba.com/stats/videoeventsasset?GameEventID={event_id}&GameID={game_id}"
        
        try:
            res = requests.get(video_endpoint, headers=headers, timeout=8)
            if res.status_code == 200:
                data = res.json()
                video_urls = data['resultSets']['Meta']['videoUrls']
                
                if video_urls:
                    # 'lurl' represents the highest definition continuous MP4 stream
                    mp4_link = video_urls[0]['lurl']
                    highlights.append({
                        "Time": row['PCTIMESTRING'],
                        "Period": row['PERIOD'],
                        "Play": description,
                        "Video_URL": mp4_link
                    })
        except Exception:
            pass
        
        time.sleep(1.2) # Dynamic pause behavior to bypass standard CDN rate limits

    return pd.DataFrame(highlights)

# --- Run Example ---
# Date format must be MM/DD/YYYY
df_highlights = get_player_matchup_highlights(
    player_name="Victor Wembanyama", 
    team_a_abbr="OKC", 
    team_b_abbr="SAS", 
    game_date="01/07/2026"
)

if df_highlights is not None and not df_highlights.empty:
    pd.set_option('display.max_colwidth', None)
    print(df_highlights)
