#!/usr/bin/env python3
"""
Update Injury Timestamps from ESPN
Fetches current injury data with proper reportedAt timestamps.

ESPN endpoints:
- /sports/basketball/nba/injuries
- /sports/football/nfl/injuries
- etc.

Run: Every 4 hours with injury sync
"""
import requests
import psycopg2
import os
from datetime import datetime, timezone, timedelta
import argparse

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

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'},
}


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 fetch_espn_injuries(sport, espn_league):
    """Fetch injuries from ESPN with timestamps"""
    url = f'{ESPN_BASE}/{sport}/{espn_league}/injuries'

    try:
        resp = requests.get(url, timeout=30)
        if resp.status_code != 200:
            print(f"  ESPN returned {resp.status_code}")
            return []

        data = resp.json()
        injuries = []

        # ESPN structure: injuries[] where each item is a team with nested injuries
        for team_data in data.get('injuries', []):
            team_name = team_data.get('displayName', '')
            # Try to get team abbrev from name or id
            team_abbrev = team_name[:3].upper() if team_name else ''

            for injury in team_data.get('injuries', []):
                athlete = injury.get('athlete', {})

                # Get timestamp - ESPN provides date field
                date_str = injury.get('date')
                reported_at = None
                if date_str:
                    try:
                        reported_at = datetime.fromisoformat(date_str.replace('Z', '+00:00'))
                    except:
                        pass

                # Get injury type
                injury_type_data = injury.get('type', {})
                injury_type = injury_type_data.get('text') if isinstance(injury_type_data, dict) else injury_type_data

                # Get details
                details = injury.get('details', {})
                if isinstance(details, dict):
                    if not injury_type:
                        injury_type = details.get('type')
                    return_date = details.get('returnDate')
                else:
                    return_date = None

                # Get athlete ID from links if not in athlete dict
                athlete_id = athlete.get('id', '')
                if not athlete_id:
                    links = athlete.get('links', [])
                    for link in links:
                        href = link.get('href', '')
                        if '/id/' in href:
                            athlete_id = href.split('/id/')[-1].split('/')[0]
                            break

                injuries.append({
                    'player_id': str(athlete_id) if athlete_id else '',
                    'player_name': athlete.get('displayName') or athlete.get('fullName', ''),
                    'team': team_abbrev,
                    'team_name': team_name,
                    'position': athlete.get('position', {}).get('abbreviation') if isinstance(athlete.get('position'), dict) else None,
                    'status': injury.get('status', ''),
                    'injury_type': injury_type,
                    'description': injury.get('longComment') or injury.get('shortComment'),
                    'reported_at': reported_at,
                    'return_date': return_date,
                })

        return injuries
    except Exception as e:
        print(f"  Error fetching injuries: {e}")
        import traceback
        traceback.print_exc()
        return []


def update_injury_timestamps(league):
    """Update injury timestamps for a league"""
    if league not in LEAGUE_CONFIG:
        print(f"Unknown league: {league}")
        return {'updated': 0, 'new': 0}

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

    print(f"\n{league.upper()}: Fetching injuries from ESPN...")

    injuries = fetch_espn_injuries(config['sport'], config['espn_league'])
    print(f"  Found {len(injuries)} injuries")

    updated = 0
    new_injuries = 0

    for inj in injuries:
        if not inj['player_name']:
            continue

        # Try to update existing injury
        cur.execute('''
            UPDATE "PlayerInjury"
            SET "reportedAt" = COALESCE(%s, "reportedAt"),
                status = COALESCE(%s, status),
                "injuryType" = COALESCE(%s, "injuryType"),
                description = COALESCE(%s, description),
                "expectedReturn" = COALESCE(%s, "expectedReturn"),
                "updatedAt" = NOW()
            WHERE league = %s
              AND (LOWER("playerName") = LOWER(%s) OR "playerExternalId" = %s)
            RETURNING id
        ''', (
            inj['reported_at'], inj['status'], inj['injury_type'],
            inj['description'], inj['return_date'],
            league, inj['player_name'], inj['player_id']
        ))

        if cur.rowcount > 0:
            updated += 1
        else:
            # Insert new injury
            try:
                cur.execute('''
                    INSERT INTO "PlayerInjury" (
                        league, "playerExternalId", "playerName", team, position,
                        status, "injuryType", description, "reportedAt", "expectedReturn",
                        source, "createdAt", "updatedAt"
                    )
                    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, 'espn', NOW(), NOW())
                    ON CONFLICT (league, "playerExternalId", source) DO UPDATE SET
                        status = EXCLUDED.status,
                        "injuryType" = EXCLUDED."injuryType",
                        description = EXCLUDED.description,
                        "reportedAt" = COALESCE(EXCLUDED."reportedAt", "PlayerInjury"."reportedAt"),
                        "updatedAt" = NOW()
                ''', (
                    league, inj['player_id'], inj['player_name'], inj['team'],
                    inj['position'], inj['status'], inj['injury_type'],
                    inj['description'], inj['reported_at'], inj['return_date']
                ))
                new_injuries += 1
            except Exception as e:
                pass

    conn.commit()

    # Check how many now have timestamps
    cur.execute('''
        SELECT COUNT(*), COUNT("reportedAt")
        FROM "PlayerInjury"
        WHERE league = %s
    ''', (league,))
    total, with_ts = cur.fetchone()

    cur.close()
    conn.close()

    print(f"  {league}: Updated {updated}, New {new_injuries}, Total {total} ({with_ts} with timestamps)")
    return {'updated': updated, 'new': new_injuries}


def main():
    parser = argparse.ArgumentParser(description='Update injury timestamps from ESPN')
    parser.add_argument('--leagues', type=str, default='nba,nfl,nhl,mlb',
                        help='Comma-separated leagues')
    args = parser.parse_args()

    print("=" * 60)
    print("UPDATE INJURY TIMESTAMPS FROM ESPN")
    print(f"Time: {datetime.now(timezone.utc).isoformat()}")
    print("=" * 60)

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

    total_updated = 0
    total_new = 0

    for league in leagues:
        result = update_injury_timestamps(league)
        total_updated += result['updated']
        total_new += result['new']

    print(f"\n{'='*60}")
    print(f"TOTAL: {total_updated} updated, {total_new} new injuries")
    print("=" * 60)


if __name__ == '__main__':
    main()
