import re

import requests
import xbmc
import xbmcaddon

from tools import debug_log


def fetch_games(self, addon_id):
    try:
        livescore_addon_id = "script.service.livescore_alerts"
        livescore_addon = xbmcaddon.Addon(id=livescore_addon_id)
        sports_settings = {
            "mlb": False,
            "ncaabase": False,
            "nba": False,
            "nba_summer_league": False,
            "nba_utah_summer": False,
            "nba_california_classic": False,
            "wnba": False,
            "nhl": False,
            "nfl": False,
            "college_football": False,
            "mls": False,
            "premier_league": False,
            "fifa_club_world_cup": False,
        }
        for sport in sports_settings:
            setting_id = f'sport_{sport}'
            try:
                sports_settings[sport] = livescore_addon.getSettingBool(setting_id)
            except Exception as e:
                debug_log(f"Error accessing setting {setting_id}: {str(e)}", level=xbmc.LOGERROR)
                sports_settings[sport] = False

        enabled_sports = [sport for sport, enabled in sports_settings.items() if enabled]
        if not enabled_sports:
            debug_log("No sports selected for notifications", level=xbmc.LOGINFO)
            return {}

        games = {}
        for sport in enabled_sports:
            sport_map = {
                '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': 'sports/basketball/nba-summer-utah',
                'nba_california_classic': 'sports/basketball/nba-summer-california',
                'wnba': 'sports/basketball/wnba',
                'nhl': 'sports/hockey/nhl',
                'nfl': 'sports/football/nfl',
                'ncaab': 'sports/basketball/mens-college-basketball',
                'college_football': 'sports/football/college-football',
                'mls': 'sports/soccer/usa.1',
                'premier_league': 'sports/soccer/eng.1',
                'laliga': 'sports/soccer/esp.1',
                'bundesliga': 'sports/soccer/ger.1',
                'seriea': 'sports/soccer/ita.1',
                'ligue1': 'sports/soccer/fra.1',
                'championsleague': 'sports/soccer/uefa.champions',
                'fifa_club_world_cup': 'sports/soccer/fifa.club-world-cup',
                'cfl': 'sports/football/nfl',
            }
            espn_sport = sport_map.get(sport, f'sports/{sport}')
            url = f"https://site.api.espn.com/apis/site/v2/{espn_sport}/scoreboard"
            debug_log(f"Fetching scores for {sport.upper()} from {url} -- {addon_id}", level=xbmc.LOGINFO)
            try:
                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', [])
                for event in events:
                    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', ''))
                    score2 = str(competitors[1].get('score', ''))
                    status_obj = competition.get('status', {})
                    status_type = status_obj.get('type', {})
                    status_text = status_type.get('description', 'TBD')
                    
                    period = status_obj.get('period', '')
                    clock = status_obj.get('displayClock', '')
                    
                    if period and clock and status_text in ['In Progress', 'Halftime']:
                        status_text = f"Q{period} {clock}"
                    elif period and status_text in ['In Progress', 'Halftime']:
                        status_text = f"Q{period}"
                    
                    if status_text == 'Scheduled':
                        continue
                    
                    key = f"[COLOR yellow]{sport.upper().replace('_', ' ')}[/COLOR]: {team1_name} vs {team2_name}"
                    games[key] = {
                        'score': f"[COLOR aqua]{score1} - {score2}[/COLOR]",
                        'status': f"[COLOR lime]{status_text}[/COLOR]",
                        'sport': f"[COLOR yellow]{sport.upper().replace('_', ' ')}[/COLOR]",
                    }
            except Exception as e:
                debug_log(f"Error fetching {sport.upper()} scores: {str(e)}", level=xbmc.LOGERROR)
                continue
        return games
    except Exception as e:
        debug_log(f"Error in fetch_games: {str(e)}", level=xbmc.LOGERROR)
        return {}


def get_game_status(self, gamecard):
    try:
        team_keywords = [
            'twins', 'cardinals', 'rays', 'reds', 'angels', 'guardians', 'orioles',
            'astros', 'giants', 'royals', 'white sox', 'yankees', 'dodgers', 'cubs',
            'mets', 'phillies', 'braves', 'marlins', 'nationals', 'pirates',
            'brewers', 'tigers', 'rangers', 'athletics', 'mariners', 'padres',
            'diamondbacks', 'rockies', 'blue jays', 'red sox', 'indians', "a's",
            'fever', 'sky', 'sun', 'wings', 'aces', 'lynx', 'liberty', 'mercury',
            'storm', 'mystics', 'dream',
        ]
        status_div = gamecard.find("div", class_="status")
        if status_div:
            status_text = status_div.get_text(separator=" ", strip=True)
            if status_text and status_text.lower() not in team_keywords:
                return status_text
        for span in gamecard.find_all("span"):
            text = span.get_text(strip=True)
            if text and any(keyword in text for keyword in ["Final", "inning", "Inning", "Top", "Bot", "Quarter", "Period", "Half", "OT", "Live", "Ppd"]):
                if text.lower() not in team_keywords:
                    return text
        all_text = gamecard.get_text(separator=" ", strip=True)
        if re.search(r'(Top|Bot)\s+\d+', all_text, re.IGNORECASE):
            return re.search(r'(Top|Bot)\s+\d+', all_text, re.IGNORECASE).group(0)
        if re.search(r'\bFinal\b', all_text, re.IGNORECASE):
            return "Final"
        if re.search(r'\bPpd\b', all_text, re.IGNORECASE):
            return "Postponed"
        if re.search(r'\d+(st|nd|rd|th)\s+(Quarter|Period|Inning)', all_text, re.IGNORECASE):
            return re.search(r'\d+(st|nd|rd|th)\s+(Quarter|Period|Inning)', all_text, re.IGNORECASE).group(0)
        if re.search(r'\bLive\b', all_text, re.IGNORECASE):
            return "Live"
        if re.search(r'\d{1,2}:\d{2}\s*(AM|PM)', all_text, re.IGNORECASE):
            time_match = re.search(r'\d{1,2}:\d{2}\s*(AM|PM)', all_text, re.IGNORECASE)
            return f"Starts {time_match.group(0)}"
        status_selectors = [
            'div.Ta\(end\) Cl\(b\) Fw\(b\) YahooSans Fw\(700\)! Fz\(11px\)!',
            'div.game-status',
            'div.Fz\(12px\)',
            'span[data-tst="game-status"]',
        ]
        for selector in status_selectors:
            try:
                elements = gamecard.select(selector)
                for elem in elements:
                    text = elem.get_text(strip=True)
                    if text and text not in ['', ' '] and text.lower() not in team_keywords:
                        return text
            except Exception:
                continue
        return "Scheduled"
    except Exception:
        return "TBD"
