import json

import requests
import xbmc
import xbmcaddon
import xbmcgui

from tools import debug_log
from widgets import fetch_all_scores_with_cache, get_cache_info


def load_live_scores_widget(self, widget_list=None, force_refresh=False):
    """
    Load Live Scores widget - fetches live game scores from ESPN API with caching support.
    Uses cache for instant loading, fetches fresh data only when cache is old.
    """
    debug_log("DEBUG: Loading Live Scores widget", level=xbmc.LOGINFO)

    if widget_list is None:
        widget_list = self.widget_list2
    if not widget_list:
        debug_log("DEBUG: widget_list is None for live scores", level=xbmc.LOGINFO)
        return

    try:
        widget_list.reset()

        current_addon = xbmcaddon.Addon()

        enabled_sports = []
        sport_settings = {
            'ls_nfl': 'NFL',
            'ls_mlb': 'MLB',
            'ls_ncaabase': 'NCAABASE',
            'ls_nba': 'NBA',
            'ls_nba_summer_league': 'NBA Summer League',
            'ls_nba_utah_summer': 'NBA Utah Summer League',
            'ls_nba_california_classic': 'NBA California Classic',
            'ls_ncaab': 'NCAAB',
            'ls_wnba': 'WNBA',
            'ls_nhl': 'NHL',
            'ls_mls': 'MLS',
            'ls_cfl': 'CFL',
            'ls_la_liga': 'La Liga',
            'ls_bundesliga': 'Bundesliga',
            'ls_serie_a': 'Serie A',
            'ls_ligue_1': 'Ligue 1',
            'ls_champions_league': 'Champions League',
        }
        for setting_id, sport_name in sport_settings.items():
            try:
                if current_addon.getSettingBool(setting_id):
                    enabled_sports.append(sport_name)
            except Exception:
                pass

        if not enabled_sports:
            sport_preference = current_addon.getSetting('live_scores_sport') or 'All'
            if sport_preference != 'All':
                enabled_sports = [sport_preference]
            else:
                enabled_sports = ['NFL', 'MLB','NCAABASE', 'NBA', 'NBA Summer League', 'NBA Utah Summer League', 'NBA California Classic', 'NCAAB', 'WNBA', 'NHL', 'MLS', 'CFL', 'La Liga', 'Bundesliga', 'Serie A', 'Ligue 1', 'Champions League']

        debug_log(f"DEBUG: Live Scores enabled sports: {enabled_sports}, force_refresh: {force_refresh}", level=xbmc.LOGINFO)

        cache_info = get_cache_info()
        if cache_info:
            debug_log(f"DEBUG: Cache info - {cache_info['game_count']} games, {cache_info['cache_age']:.0f}s old", level=xbmc.LOGINFO)
        else:
            debug_log("DEBUG: No cache exists", level=xbmc.LOGINFO)

        games = fetch_all_scores_with_cache(enabled_sports, force_refresh=force_refresh)

        debug_log(f"DEBUG: Found {len(games)} games", level=xbmc.LOGINFO)

        if not games:
            list_item = xbmcgui.ListItem("No live games")
            list_item.setArt({'icon': "special://home/addons/plugin.video.jet_guide/resources/skins/default/720p/media/sports_icon.png"})
            list_item.setProperty("widget_link", "")
            widget_list.addItem(list_item)
        else:
            for game in games:
                status = game.get('status', '')
                period = game.get('period', '')
                clock = game.get('clock', '')
                venue = game.get('venue', '')

                status_display = status
                if period and status in ['In Progress', 'Halftime', 'Final']:
                    if clock:
                        status_display = f"Q{period} {clock}"
                    else:
                        status_display = f"Q{period}"

                label = f"{game['team1']} vs {game['team2']} - {game['score']} ({status_display})"

                list_item = xbmcgui.ListItem(label)
                sport_icon_map = {
                    'NFL': 'nfl',
                    'MLB': 'baseball',
                    'NCAABASE': 'baseball',
                    'NBA': 'nba',
                    'NHL': 'nhl',
                    'WNBA': 'wnba',
                    'NCAAB': 'ncaa_men',
                    'CFL': 'cfl',
                    'MLS': 'soccer',
                    'Premier League': 'soccer',
                    'La Liga': 'soccer',
                    'Bundesliga': 'soccer',
                    'Serie A': 'soccer',
                    'Ligue 1': 'soccer',
                    'Champions League': 'soccer',
                }
                sport_key = game.get('sport', '')
                icon_name = sport_icon_map.get(sport_key, sport_key.lower())
                icon = f"special://home/addons/plugin.video.jet_guide/resources/skins/default/720p/media/sports/{icon_name}.png"
                if sport_key == 'MLB':
                    icon = f"special://home/addons/plugin.video.jet_guide/resources/skins/default/720p/media/sports/mlb.jpg"
                list_item.setArt({'icon': icon, 'thumb': icon})
                list_item.setProperty("widget_link", "")
                list_item.setProperty("game_status", status)
                list_item.setProperty("game_period", period)
                list_item.setProperty("game_clock", clock)
                list_item.setProperty("game_venue", venue)
                list_item.setProperty("game_stats", json.dumps(game.get('stats', {})))
                list_item.setProperty("game_team1", game['team1'])
                list_item.setProperty("game_team2", game['team2'])
                list_item.setProperty("game_score", game['score'])
                list_item.setProperty("game_sport", game['sport'])
                list_item.setProperty("game_event_id", game.get('event_id', ''))
                list_item.setProperty("game_team1_stats", json.dumps(game.get('team1_stats', {})))
                list_item.setProperty("game_team2_stats", json.dumps(game.get('team2_stats', {})))
                list_item.setProperty("game_team1_leaders", json.dumps(game.get('team1_leaders', {})))
                list_item.setProperty("game_team2_leaders", json.dumps(game.get('team2_leaders', {})))
                widget_list.addItem(list_item)

        debug_log("DEBUG: Live Scores widget loaded successfully", level=xbmc.LOGINFO)

    except Exception as e:
        debug_log(f"Error loading Live Scores widget: {str(e)}", level=xbmc.LOGERROR)
        try:
            widget_list.reset()
            list_item = xbmcgui.ListItem("Error loading scores")
            list_item.setArt({'icon': "special://home/addons/plugin.video.jet_guide/resources/skins/default/720p/media/sports_icon.png"})
            widget_list.addItem(list_item)
        except Exception:
            pass


def fetch_espn_scores(self, sport_endpoint, sport_name):
    games = []
    try:
        sport_map = {
            'NFL': 'sports/football/nfl',
            'MLB': 'sports/baseball/mlb',
            'NCAABASE': 'sports/baseball/college-baseball',
            'NBA': 'sports/basketball/nba',
            'NBA Summer League': 'sports/basketball/nba-summer-las-vegas',
            'NBA Utah Summer League': 'sports/basketball/nba-summer-utah',
            'NBA California Classic': 'sports/basketball/nba-summer-california',
            "NCAAB": 'sports/basketball/mens-college-basketball',
            'NHL': 'sports/hockey/nhl',
            'MLS': 'sports/soccer/usa.1',
            'CFL': 'sports/football/nfl',
        }

        espn_sport = sport_map.get(sport_name)
        if not espn_sport:
            debug_log(f"DEBUG: No ESPN endpoint for sport: {sport_name}", level=xbmc.LOGINFO)
            return games

        url = f"https://site.api.espn.com/apis/site/v2/{espn_sport}/scoreboard"
        debug_log(f"DEBUG: Fetching ESPN scores from {url}", level=xbmc.LOGINFO)

        response = requests.get(
            url,
            headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'},
            timeout=10,
        )
        response.raise_for_status()

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

        debug_log(f"DEBUG: Found {len(events)} events for {sport_name}", level=xbmc.LOGINFO)

        for event in events:
            try:
                competition = event.get('competitions', [{}])[0]
                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 not team1_name or not team2_name:
                    continue

                score1 = str(competitors[0].get('score', '0'))
                score2 = str(competitors[1].get('score', '0'))

                status_obj = competition.get('status', {})
                status_type = status_obj.get('type', {})
                status = status_type.get('description', 'Scheduled')

                period = str(status_obj.get('period', '') or '')
                clock = str(status_obj.get('displayClock', '') or '')

                detailed_status = status
                if period and clock and status in ['In Progress', 'Halftime', 'Final']:
                    detailed_status = f"Q{period}" if not clock else f"Q{period} {clock}"

                venue = competition.get('venue', {})
                venue_name = venue.get('fullName', '')

                team1_stats = {}
                team2_stats = {}
                team1_leaders = {}
                team2_leaders = {}

                team1_statistics = competitors[0].get('statistics', [])
                for stat in team1_statistics:
                    team1_stats[stat.get('name', '')] = {
                        'abbreviation': stat.get('abbreviation', ''),
                        'displayValue': stat.get('displayValue', ''),
                    }

                team2_statistics = competitors[1].get('statistics', [])
                for stat in team2_statistics:
                    team2_stats[stat.get('name', '')] = {
                        'abbreviation': stat.get('abbreviation', ''),
                        'displayValue': stat.get('displayValue', ''),
                    }

                team1_leaders_data = competitors[0].get('leaders', [])
                team2_leaders_data = competitors[1].get('leaders', [])

                for leader in team1_leaders_data:
                    stat_name = leader.get('name', '')
                    leaders_list = leader.get('leaders', [])
                    if leaders_list:
                        top_leader = leaders_list[0]
                        athlete = top_leader.get('athlete', {})
                        athlete_name = athlete.get('displayName', top_leader.get('athlete', {}).get('fullName', ''))
                        value = top_leader.get('displayValue', '')
                        if stat_name and athlete_name:
                            team1_leaders[stat_name] = {'name': athlete_name, 'value': value}

                for leader in team2_leaders_data:
                    stat_name = leader.get('name', '')
                    leaders_list = leader.get('leaders', [])
                    if leaders_list:
                        top_leader = leaders_list[0]
                        athlete = top_leader.get('athlete', {})
                        athlete_name = athlete.get('displayName', top_leader.get('athlete', {}).get('fullName', ''))
                        value = top_leader.get('displayValue', '')
                        if stat_name and athlete_name:
                            team2_leaders[stat_name] = {'name': athlete_name, 'value': value}

                leaders = competition.get('leaders', [])
                stats_data = {}
                if leaders:
                    for leader in leaders:
                        stat_name = leader.get('name', '')
                        leaders_list = leader.get('leaders', [])
                        if leaders_list:
                            for l in leaders_list:
                                athlete = l.get('athlete', {})
                                athlete_name = athlete.get('fullName', '')
                                value = l.get('displayValue', '')
                                if stat_name and athlete_name:
                                    stats_data[f"{stat_name}_leader"] = f"{athlete_name}: {value}"

                games.append({
                    'team1': team1_name,
                    'team2': team2_name,
                    'score': f"{score1} - {score2}",
                    'status': detailed_status,
                    'full_status': status,
                    'sport': sport_name,
                    'venue': venue_name,
                    'period': period,
                    'clock': clock,
                    'stats': stats_data,
                    'team1_stats': team1_stats,
                    'team2_stats': team2_stats,
                    'team1_leaders': team1_leaders,
                    'team2_leaders': team2_leaders,
                    'event_id': event.get('id', ''),
                })
            except Exception as e:
                debug_log(f"DEBUG: Error parsing event: {e}", level=xbmc.LOGDEBUG)
                continue

        debug_log(f"DEBUG: Parsed {len(games)} games from ESPN for {sport_name}", level=xbmc.LOGINFO)

    except requests.exceptions.HTTPError as e:
        debug_log(f"HTTP Error fetching {sport_name} scores from ESPN: {str(e)}", level=xbmc.LOGERROR)
    except Exception as e:
        debug_log(f"Error fetching {sport_name} scores from ESPN: {str(e)}", level=xbmc.LOGERROR)

    return games


def show_live_scores_details(self, item):
    try:
        team1 = item.getProperty("game_team1")
        team2 = item.getProperty("game_team2")
        score = item.getProperty("game_score")
        status = item.getProperty("game_status")
        period = item.getProperty("game_period")
        clock = item.getProperty("game_clock")
        venue = item.getProperty("game_venue")
        sport = item.getProperty("game_sport") or ""

        team1_stats = {}
        team2_stats = {}
        team1_leaders = {}
        team2_leaders = {}

        team1_stats_json = item.getProperty("game_team1_stats")
        team2_stats_json = item.getProperty("game_team2_stats")

        if team1_stats_json:
            try:
                team1_stats = json.loads(team1_stats_json)
            except Exception:
                pass

        if team2_stats_json:
            try:
                team2_stats = json.loads(team2_stats_json)
            except Exception:
                pass

        team1_leaders_json = item.getProperty("game_team1_leaders")
        team2_leaders_json = item.getProperty("game_team2_leaders")

        if team1_leaders_json:
            try:
                team1_leaders = json.loads(team1_leaders_json)
            except Exception:
                pass

        if team2_leaders_json:
            try:
                team2_leaders = json.loads(team2_leaders_json)
            except Exception:
                pass

        stats_json = item.getProperty("game_stats")
        stats_data = {}
        if stats_json:
            try:
                stats_data = json.loads(stats_json)
            except Exception:
                pass

        info_lines = []
        info_lines.append(f"[B]{team1} vs {team2}[/B]")
        info_lines.append(f"Score: {score}")
        info_lines.append(f"Status: {status}")

        if period and clock:
            info_lines.append(f"Time: {period} {clock}")
        elif period:
            info_lines.append(f"Period: {period}")

        if venue:
            info_lines.append(f"Venue: {venue}")

        if sport:
            info_lines.append(f"Sport: {sport}")

        if team1_leaders or team2_leaders:
            info_lines.append("")
            info_lines.append("[B]Game Leaders:[/B]")
            leader_stats = ['points', 'rebounds', 'assists']
            t1_short = team1[:10] if len(team1) > 10 else team1
            t2_short = team2[:10] if len(team2) > 10 else team2
            for stat_key in leader_stats:
                t1_leader = team1_leaders.get(stat_key)
                t2_leader = team2_leaders.get(stat_key)
                stat_name = stat_key.title()
                if t1_leader and t2_leader:
                    t1_name = t1_leader.get('name', '')[:15]
                    t1_val = t1_leader.get('value', '-')
                    t2_name = t2_leader.get('name', '')[:15]
                    t2_val = t2_leader.get('value', '-')
                    info_lines.append(f"{stat_name}:")
                    info_lines.append(f"  {t1_short}: {t1_name} - {t1_val}")
                    info_lines.append(f"  {t2_short}: {t2_name} - {t2_val}")

        if team1_stats or team2_stats:
            info_lines.append("")
            info_lines.append("[B]Team Statistics:[/B]")

            stat_names = [
                'points', 'rebounds', 'assists',
                'fieldGoalsMade', 'fieldGoalsAttempted', 'fieldGoalPct',
                'threePointFieldGoalsMade', 'threePointFieldGoalsAttempted', 'threePointPct',
                'freeThrowsMade', 'freeThrowsAttempted', 'freeThrowPct',
                'turnovers', 'steals', 'blocks', 'personalFouls',
            ]

            stat_abbrevs = {
                'points': 'PTS', 'rebounds': 'REB', 'assists': 'AST',
                'fieldGoalsMade': 'FGM', 'fieldGoalsAttempted': 'FGA', 'fieldGoalPct': 'FG%',
                'threePointFieldGoalsMade': '3PM', 'threePointFieldGoalsAttempted': '3PA', 'threePointPct': '3P%',
                'freeThrowsMade': 'FTM', 'freeThrowsAttempted': 'FTA', 'freeThrowPct': 'FT%',
                'turnovers': 'TO', 'steals': 'STL', 'blocks': 'BLK', 'personalFouls': 'PF',
            }

            info_lines.append("")
            t1_short = team1[:8] if len(team1) > 8 else team1
            t2_short = team2[:8] if len(team2) > 8 else team2
            info_lines.append(f"{'Stat':<12} {t1_short:>8} {t2_short:>8}")
            info_lines.append("-" * 30)

            for stat_key in stat_names:
                t1_val = team1_stats.get(stat_key)
                t2_val = team2_stats.get(stat_key)
                if t1_val and t2_val:
                    t1_display = t1_val.get('displayValue', '-')
                    t2_display = t2_val.get('displayValue', '-')
                    stat_abbrev = stat_abbrevs.get(stat_key, stat_key[:3].upper())
                    info_lines.append(f"{stat_abbrev:<12} {t1_display:>8} {t2_display:>8}")

        if stats_data:
            info_lines.append("")
            info_lines.append("[B]League Leaders:[/B]")
            for key, value in stats_data.items():
                stat_name = key.replace('_leader', '').title()
                info_lines.append(f"{stat_name}: {value}")

        info_text = "\n".join(info_lines)
        xbmcgui.Dialog().textviewer(f"Game Details - {sport}", info_text)

    except Exception as e:
        debug_log(f"Error showing live scores details: {str(e)}", level=xbmc.LOGERROR)
        xbmcgui.Dialog().ok("Error", f"Unable to load game details.\n{str(e)}")
