#!/usr/bin/env python3
"""
Fetch TV Broadcast Information from ESPN
Captures which networks are broadcasting each game (ESPN, TNT, ABC, etc.)

ESPN scoreboard includes broadcasts in competitions[0].broadcasts

Run: Daily before games
"""
import requests
import psycopg2
import os
import time
import argparse
from datetime import datetime, timezone, timedelta

ESPN_BASE = 'https://site.api.espn.com/apis/site/v2/sports'
REQUEST_DELAY = 0.3

LEAGUE_CONFIG = {
    'nba': {'sport': 'basketball', 'espn_league': 'nba'},
    'nfl': {'sport': 'football', 'espn_league': 'nfl'},
    'nhl': {'sport': 'hockey', 'espn_league': 'nhl'},
    'mlb': {'sport': 'baseball', 'espn_league': 'mlb'},
    'ncaab': {'sport': 'basketball', 'espn_league': 'mens-college-basketball'},
    'ncaaf': {'sport': 'football', 'espn_league': 'college-football'},
}

# National TV networks (for primetime detection)
NATIONAL_NETWORKS = {'ESPN', 'ESPN2', 'ABC', 'TNT', 'TBS', 'NBC', 'CBS', 'FOX', 'FS1', 'NBA TV', 'NFL Network', 'NHL Network', 'NBCSN', 'USA'}


def load_db_url():
    env_path = '/var/www/html/eventheodds/.env'
    try:
        with open(env_path, 'r') as f:
            for line in f:
                if line.startswith('SPORTS_DATABASE_URL='):
                    return line.split('=', 1)[1].strip().split('?')[0]
    except FileNotFoundError:
        pass
    return os.environ.get('SPORTS_DATABASE_URL', '').split('?')[0]


def ensure_broadcast_table(cur):
    """Create GameBroadcast table if needed"""
    cur.execute('''
        CREATE TABLE IF NOT EXISTS "GameBroadcast" (
            id BIGSERIAL PRIMARY KEY,
            league VARCHAR(50) NOT NULL,
            "gameId" BIGINT,
            "gameDate" TIMESTAMP,
            "homeTeam" VARCHAR(20),
            "awayTeam" VARCHAR(20),
            network VARCHAR(100),
            "isNational" BOOLEAN DEFAULT FALSE,
            market VARCHAR(100),
            "createdAt" TIMESTAMP DEFAULT NOW(),
            UNIQUE(league, "gameId", network)
        )
    ''')
    cur.execute('CREATE INDEX IF NOT EXISTS "GameBroadcast_league_national_idx" ON "GameBroadcast" (league, "isNational")')
    cur.execute('CREATE INDEX IF NOT EXISTS "GameBroadcast_gameId_idx" ON "GameBroadcast" ("gameId")')


def fetch_broadcasts_for_date(sport, espn_league, date_str):
    """Fetch broadcast info for all games on a date"""
    url = f'{ESPN_BASE}/{sport}/{espn_league}/scoreboard?dates={date_str}'
    if espn_league in ['mens-college-basketball', 'college-football']:
        url += '&groups=50&limit=300'

    try:
        resp = requests.get(url, timeout=15)
        if resp.status_code != 200:
            return []

        data = resp.json()
        games = []

        for event in data.get('events', []):
            competitions = event.get('competitions', [])
            if not competitions:
                continue

            comp = competitions[0]

            # Get teams
            home_team = None
            away_team = None
            for competitor in comp.get('competitors', []):
                team = competitor.get('team', {})
                abbrev = team.get('abbreviation', '').upper()
                if competitor.get('homeAway') == 'home':
                    home_team = abbrev
                else:
                    away_team = abbrev

            # Get broadcasts
            broadcasts = comp.get('broadcasts', [])
            game_broadcasts = []

            for broadcast_group in broadcasts:
                market = broadcast_group.get('market', '')
                names = broadcast_group.get('names', [])

                for name in names:
                    is_national = name.upper() in NATIONAL_NETWORKS or market.lower() == 'national'
                    game_broadcasts.append({
                        'network': name,
                        'is_national': is_national,
                        'market': market
                    })

            if home_team and away_team:
                games.append({
                    'home': home_team,
                    'away': away_team,
                    'date': event.get('date'),
                    'broadcasts': game_broadcasts
                })

        return games
    except Exception as e:
        print(f"  Error: {e}")
        return []


def fetch_broadcasts_for_league(league, days_back=7, days_forward=7):
    """Fetch broadcast info for a league"""
    if league not in LEAGUE_CONFIG:
        print(f"Unknown league: {league}")
        return {'games': 0, 'broadcasts': 0}

    config = LEAGUE_CONFIG[league]
    db_url = load_db_url()
    conn = psycopg2.connect(db_url)
    cur = conn.cursor()

    ensure_broadcast_table(cur)
    conn.commit()

    today = datetime.now(timezone.utc).date()
    start_date = today - timedelta(days=days_back)
    end_date = today + timedelta(days=days_forward)

    print(f"\n{league.upper()}: Fetching broadcasts from {start_date} to {end_date}")

    total_games = 0
    total_broadcasts = 0

    current_date = start_date
    while current_date <= end_date:
        date_str = current_date.strftime('%Y%m%d')
        time.sleep(REQUEST_DELAY)

        games = fetch_broadcasts_for_date(config['sport'], config['espn_league'], date_str)

        for game in games:
            if not game['broadcasts']:
                continue

            # Find matching game in SportsGame
            cur.execute('''
                SELECT id, "gameDate" FROM "SportsGame"
                WHERE league = %s
                  AND "homeTeam" = %s AND "awayTeam" = %s
                  AND "gameDate"::date = %s
                LIMIT 1
            ''', (league, game['home'], game['away'], current_date))

            db_game = cur.fetchone()
            game_id = db_game[0] if db_game else None
            game_date = db_game[1] if db_game else current_date

            for broadcast in game['broadcasts']:
                try:
                    cur.execute('''
                        INSERT INTO "GameBroadcast" (
                            league, "gameId", "gameDate", "homeTeam", "awayTeam",
                            network, "isNational", market
                        )
                        VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
                        ON CONFLICT (league, "gameId", network) DO UPDATE SET
                            "isNational" = EXCLUDED."isNational",
                            market = EXCLUDED.market
                    ''', (
                        league, game_id, game_date, game['home'], game['away'],
                        broadcast['network'], broadcast['is_national'], broadcast['market']
                    ))
                    total_broadcasts += 1
                except Exception as e:
                    pass

            total_games += 1

        current_date += timedelta(days=1)

    conn.commit()

    # Summary stats
    cur.execute('''
        SELECT COUNT(DISTINCT "gameId"), COUNT(*), SUM(CASE WHEN "isNational" THEN 1 ELSE 0 END)
        FROM "GameBroadcast"
        WHERE league = %s
    ''', (league,))
    stats = cur.fetchone()

    cur.close()
    conn.close()

    print(f"  {league}: {stats[0]} games, {stats[1]} broadcasts ({stats[2]} national)")
    return {'games': total_games, 'broadcasts': total_broadcasts}


def main():
    parser = argparse.ArgumentParser(description='Fetch broadcast info from ESPN')
    parser.add_argument('--leagues', type=str, default='nba,nfl,nhl',
                        help='Comma-separated leagues')
    parser.add_argument('--days-back', type=int, default=30,
                        help='Days to look back')
    parser.add_argument('--days-forward', type=int, default=7,
                        help='Days to look forward')
    args = parser.parse_args()

    print("=" * 60)
    print("FETCH TV BROADCAST INFO FROM ESPN")
    print(f"Time: {datetime.now(timezone.utc).isoformat()}")
    print("=" * 60)

    leagues = [l.strip().lower() for l in args.leagues.split(',')]

    total_games = 0
    total_broadcasts = 0

    for league in leagues:
        result = fetch_broadcasts_for_league(league, args.days_back, args.days_forward)
        total_games += result['games']
        total_broadcasts += result['broadcasts']

    print(f"\n{'='*60}")
    print(f"TOTAL: {total_games} games, {total_broadcasts} broadcasts")
    print("=" * 60)


if __name__ == '__main__':
    main()
