from datetime import datetime

import requests

from sportsgrid_config import get_espn_site_sport, get_sport_stats_config


def get_team_game_stats_data(
    sport,
    team_name,
    get_cached,
    set_cached,
    api_rate_limit_delay,
    debug_log,
    log_error,
    api_headers,
):
    """Get latest game stats + leaders for a specific team."""
    try:
        cached = get_cached(team_name, 'game_stats')
        if cached is not None:
            return cached

        espn_sport = get_espn_site_sport(sport)
        today_str = datetime.now().strftime('%Y%m%d')
        url = f"https://site.api.espn.com/apis/site/v2/{espn_sport}/scoreboard?dates={today_str}"
        debug_log(f"SportsGrid: Fetching game stats from {url}")

        response = requests.get(url, headers=api_headers, timeout=10)
        api_rate_limit_delay()
        if response.status_code != 200:
            log_error(f"SportsGrid: API returned status {response.status_code}")
            return {}

        data = response.json()
        events = data.get('events', [])
        debug_log(f"SportsGrid: Got {len(events)} events for date {today_str}")
        config = get_sport_stats_config(sport)

        def get_event_date(evt):
            date_str = evt.get('date', '')
            if date_str:
                try:
                    return datetime.strptime(date_str[:19], '%Y-%m-%dT%H:%M:%S')
                except Exception:
                    pass
            return datetime.min

        events = sorted(events, key=get_event_date, reverse=True)

        for event in events:
            competition = event.get('competitions', [{}])[0]
            competitors = competition.get('competitors', [])

            for team_data in competitors:
                if not isinstance(team_data, dict):
                    continue
                team = team_data.get('team', {})
                if not isinstance(team, dict):
                    continue
                team_display = team.get('displayName', '').lower()
                if team_name.lower() in team_display or team_display in team_name.lower():
                    debug_log(f"SportsGrid: Matched team {team_display} in {event.get('name', 'unknown')}")

            for team_data in competitors:
                if not isinstance(team_data, dict):
                    continue
                team = team_data.get('team', {})
                if not isinstance(team, dict):
                    continue
                team_display = team.get('displayName', '').lower()
                if team_name.lower() not in team_display and team_display not in team_name.lower():
                    continue

                stats = team_data.get('statistics', [])
                if not isinstance(stats, list):
                    stats = []
                game_stats = {}

                for stat in stats:
                    if not isinstance(stat, dict):
                        continue
                    name = stat.get('name', '')
                    value = stat.get('displayValue', '')
                    for api_key in config['stat_keys']:
                        if name == api_key:
                            game_stats[api_key] = value
                            break

                leaders = team_data.get('leaders', [])
                if not isinstance(leaders, list):
                    leaders = []
                for leader in leaders:
                    if not isinstance(leader, dict):
                        continue
                    lname = leader.get('name', '')
                    leaders_list = leader.get('leaders', [])
                    if not (isinstance(leaders_list, list) and leaders_list):
                        continue
                    top_leader = leaders_list[0]
                    if not isinstance(top_leader, dict):
                        continue
                    athlete = top_leader.get('athlete', {})
                    athlete_name = ''
                    athlete_headshot = ''
                    if isinstance(athlete, dict):
                        athlete_name = athlete.get('displayName', '')
                        athlete_headshot = athlete.get('headshot', '')
                    value = top_leader.get('displayValue', '')
                    for api_key in config['leader_keys']:
                        api_key_base = api_key.replace('leader_', '')
                        if lname == api_key_base:
                            game_stats[api_key] = f"{athlete_name}: {value}"
                            game_stats[f"{api_key}_headshot"] = athlete_headshot
                            break

                team_id = team_data.get('id', '')
                team_score = ''
                score_data = team_data.get('score')
                if isinstance(score_data, dict):
                    team_score = score_data.get('displayValue') or score_data.get('value') or score_data.get('points') or ''
                elif isinstance(score_data, (int, float)):
                    team_score = str(score_data)
                elif isinstance(score_data, str):
                    team_score = score_data

                for opp_data in competitors:
                    if not isinstance(opp_data, dict):
                        continue
                    if opp_data.get('id', '') == team_id:
                        continue
                    opp_team = opp_data.get('team', {})
                    if isinstance(opp_team, dict):
                        game_stats['opponent'] = opp_team.get('displayName', '')
                    opp_score_data = opp_data.get('score')
                    if isinstance(opp_score_data, dict):
                        game_stats['opponent_score'] = opp_score_data.get('displayValue') or opp_score_data.get('value') or opp_score_data.get('points') or ''
                    elif isinstance(opp_score_data, (int, float)):
                        game_stats['opponent_score'] = str(opp_score_data)
                    elif isinstance(opp_score_data, str):
                        game_stats['opponent_score'] = opp_score_data
                    game_stats['team_score'] = team_score
                    break

                debug_log(f"SportsGrid: Checking team_data keys: {list(team_data.keys())}")
                probables = team_data.get('probables', [])
                debug_log(f"SportsGrid: Found {len(probables)} probables for team")
                if probables:
                    for pitcher_data in probables:
                        pitcher_stat_type = pitcher_data.get('name', '')
                        debug_log(f"SportsGrid: Pitcher type: {pitcher_stat_type}")
                        if pitcher_stat_type != 'probableStartingPitcher':
                            continue
                        pitcher_athlete = pitcher_data.get('athlete', {})
                        if not isinstance(pitcher_athlete, dict):
                            continue
                        pitcher_name = pitcher_athlete.get('displayName', '')
                        pitcher_headshot = pitcher_athlete.get('headshot', '')
                        pitcher_stats = pitcher_data.get('statistics', [])
                        pitcher_era = ''
                        pitcher_record = ''
                        for pstat in pitcher_stats:
                            pname = pstat.get('name', '')
                            pvalue = pstat.get('displayValue', '')
                            debug_log(f"SportsGrid: Pitcher stat: {pname} = {pvalue}")
                            if pname == 'ERA':
                                pitcher_era = pvalue
                            elif pname == 'wins':
                                wins = pvalue
                                for ps in pitcher_stats:
                                    if ps.get('name') == 'losses':
                                        losses = ps.get('displayValue', '')
                                        pitcher_record = f"{wins}-{losses}"
                                        break
                        if pitcher_name:
                            debug_log(f"SportsGrid: Found pitcher: {pitcher_name}, ERA: {pitcher_era}, Record: {pitcher_record}")
                            game_stats['leader_era'] = f"{pitcher_name}: {pitcher_era}"
                            game_stats['leader_era_headshot'] = pitcher_headshot
                            game_stats['leader_strikeouts'] = f"{pitcher_name}: Record {pitcher_record}"
                            game_stats['leader_strikeouts_headshot'] = pitcher_headshot
                            game_stats['leader_era_alt'] = f"{pitcher_name}: {pitcher_era} ERA"
                            game_stats['leader_era_alt_headshot'] = pitcher_headshot
                            game_stats['leader_strikeouts_alt'] = f"{pitcher_name}: {pitcher_record}"
                            game_stats['leader_strikeouts_alt_headshot'] = pitcher_headshot

                game_stats['_sport'] = sport
                set_cached(team_name, 'game_stats', game_stats)
                return game_stats

        return {}
    except Exception as e:
        log_error(f"SportsGrid: Error in get_team_game_stats: {str(e)}")
        return {}
