from datetime import datetime, timedelta

import requests

from sportsgrid_config import get_espn_site_sport


def get_team_recent_games_data(sport, team_name, get_cached, set_cached, debug_log, log_error, api_headers):
    """Get the last 5 final games for a team using ESPN date-range scoreboard APIs."""
    try:
        cached = get_cached(team_name, 'recent_games')
        if cached is not None:
            return cached

        espn_sport = get_espn_site_sport(sport)

        now = datetime.now()
        start_date = now - timedelta(days=60)
        start_str = start_date.strftime('%Y%m%d')
        end_str = now.strftime('%Y%m%d')

        debug_log(f"SportsGrid: Date range for recent games: {start_str} to {end_str}")

        url = f"https://site.api.espn.com/apis/site/v2/{espn_sport}/scoreboard?dates={start_str}-{end_str}"
        debug_log(f"SportsGrid: Fetching recent games from {url}")

        response = requests.get(url, headers=api_headers, timeout=15)
        events = []
        if response.status_code == 200:
            events = response.json().get('events', [])

        if len(events) < 5:
            team_abbrev = ''.join([c for c in team_name.lower() if c.isalpha()])[:3]
            abbrev_overrides = {
                'clippers': 'lac',
                'lakers': 'lal',
                'knicks': 'nyk',
                'warriors': 'gsw',
                'spurs': 'sas',
                'heat': 'mia',
            }
            for key, value in abbrev_overrides.items():
                if key in team_name.lower():
                    team_abbrev = value
                    break

            if team_abbrev:
                team_url = f"https://site.api.espn.com/apis/site/v2/{espn_sport}/teams/{team_abbrev}/schedule?season={datetime.now().year}"
                debug_log(f"SportsGrid: Trying team schedule: {team_url}")
                team_resp = requests.get(team_url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=15)
                if team_resp.status_code == 200:
                    events = team_resp.json().get('events', [])
                    debug_log(f"SportsGrid: Got {len(events)} events from team schedule")

        if not events:
            debug_log("SportsGrid: No events found in date range")
            return []

        recent_games = []

        def teams_match(search_name, api_name):
            s = search_name.lower().replace(' ', '').replace('.', '')
            a = api_name.lower().replace(' ', '').replace('.', '')
            if s in a or a in s:
                return True
            replacements = [
                ('losangeles', 'la'),
                ('new york', 'ny'),
                ('golden state', 'gs'),
                ('goldenstate', 'gs'),
            ]
            for full, abbr in replacements:
                s2 = s.replace(full, abbr)
                a2 = a.replace(full, abbr)
                if s2 in a2 or a2 in s2:
                    return True
            return False

        for event in events:
            competition = event.get('competitions', [{}])[0]
            status = competition.get('status', {})
            status_type = status.get('type', {})
            game_status = status_type.get('description', '')
            if 'final' not in game_status.lower():
                continue

            competitors = competition.get('competitors', [])
            if len(competitors) < 2:
                continue

            team1_data = competitors[0]
            team2_data = competitors[1]
            team1_name = team1_data.get('team', {}).get('displayName', '')
            team2_name = team2_data.get('team', {}).get('displayName', '')

            team1_match = teams_match(team_name, team1_name)
            team2_match = teams_match(team_name, team2_name)
            if not team1_match and not team2_match:
                continue

            debug_log(f"SportsGrid: Matched game for {team_name}: {team1_name} vs {team2_name}")

            team1_score = team1_data.get('score', {})
            team2_score = team2_data.get('score', {})

            if isinstance(team1_score, dict):
                team1_score = team1_score.get('value') or team1_score.get('points') or team1_score.get('displayValue', 0)
            if isinstance(team2_score, dict):
                team2_score = team2_score.get('value') or team2_score.get('points') or team2_score.get('displayValue', 0)

            if team1_match:
                opponent = team2_name
                team_score = team1_score
                opp_score = team2_score
            else:
                opponent = team1_name
                team_score = team2_score
                opp_score = team1_score

            result = 'W' if team_score > opp_score else 'L'
            recent_games.append({
                'result': result,
                'score': f"{team_score}-{opp_score}",
                'opponent': opponent,
                'date': event.get('date', ''),
            })

        debug_log(f"SportsGrid: All games before sort: {[(g['date'], g['opponent'], g['score']) for g in recent_games]}")
        recent_games.sort(key=lambda x: x.get('date', ''), reverse=True)
        debug_log(f"SportsGrid: All games after sort: {[(g['date'], g['opponent'], g['score']) for g in recent_games]}")

        recent_games = recent_games[:5]
        debug_log(f"SportsGrid: Found {len(recent_games)} recent games for {team_name}")
        set_cached(team_name, 'recent_games', recent_games)
        return recent_games
    except Exception as e:
        log_error(f"SportsGrid: Error in get_team_recent_games: {str(e)}")
        return []


def get_next_game_data(sport, team_name, get_cached, set_cached, debug_log, log_error, api_headers):
    """Get the next upcoming game for a team."""
    try:
        cached = get_cached(team_name, 'next_game')
        if cached is not None:
            return cached

        espn_sport = get_espn_site_sport(sport)

        now = datetime.now()
        start_str = now.strftime('%Y%m%d')
        end_str = (now + timedelta(days=14)).strftime('%Y%m%d')

        url = f"https://site.api.espn.com/apis/site/v2/{espn_sport}/scoreboard?dates={start_str}-{end_str}"
        debug_log(f"SportsGrid: Fetching next game from {url}")

        response = requests.get(url, headers=api_headers, timeout=15)
        if response.status_code != 200:
            debug_log(f"SportsGrid: Failed to get next game, status {response.status_code}")
            return {}

        events = response.json().get('events', [])

        for event in events:
            competition = event.get('competitions', [{}])[0]
            status = competition.get('status', {})
            status_type = status.get('type', {})
            game_status = status_type.get('description', '')
            if 'final' in game_status.lower() or 'postponed' in game_status.lower():
                continue

            competitors = competition.get('competitors', [])
            if len(competitors) < 2:
                continue

            team1 = competitors[0].get('team', {})
            team2 = competitors[1].get('team', {})
            team1_name = team1.get('displayName', '')
            team2_name = team2.get('displayName', '')

            if team_name.lower() not in team1_name.lower() and team_name.lower() not in team2_name.lower():
                continue

            game_time = ''
            date_obj = event.get('date', '')
            if date_obj:
                try:
                    game_dt = datetime.fromisoformat(date_obj.replace('Z', '+00:00'))
                    local_tz = datetime.now().astimezone().tzinfo
                    game_time = game_dt.astimezone(local_tz).strftime('%a, %b %d at %I:%M %p')
                except Exception:
                    game_time = date_obj

            if team_name.lower() in team1_name.lower():
                opponent = team2_name
            else:
                opponent = team1_name

            networks = competition.get('broadcasts', [])
            network = networks[0].get('names', ['TBD'])[0] if networks else 'TBD'

            debug_log(f"SportsGrid: Found next game for {team_name}: vs {opponent} on {game_time}")
            result = {
                'opponent': opponent,
                'time': game_time,
                'network': network,
            }
            set_cached(team_name, 'next_game', result)
            return result

        debug_log(f"SportsGrid: No upcoming games found for {team_name}")
        set_cached(team_name, 'next_game', {})
        return {}
    except Exception as e:
        log_error(f"SportsGrid: Error in get_next_game: {str(e)}")
        return {}
