import xbmc
import xbmcgui
import xbmcaddon
import sys

try:
    ADDON = xbmcaddon.Addon()
except:
    ADDON = None

def debug_log(msg, level=xbmc.LOGINFO):
    xbmc.log(f"[jet_guide] {msg}", level)

SPORT_STATS_CONFIG = {
    'nba': {
        'stat_labels': ['Points', 'Rebounds', 'Assists', 'FG%', '3PT%'],
        'leader_labels': ['Points Leader', 'Rebounds Leader', 'Assists Leader'],
    },
    'mlb': {
        'stat_labels': ['Runs', 'Hits', 'Home Runs', 'RBI', 'ERA'],
        'leader_labels': ['Batting Avg', 'Home Run', 'RBI', 'ERA', 'Strikeouts'],
    },
    'nhl': {
        'stat_labels': ['Goals', 'Assists', 'Points', 'Shots', 'Saves'],
        'leader_labels': ['Goals Leader', 'Assists Leader', 'Points Leader'],
    },
    'mls': {
        'stat_labels': ['Goals', 'Assists', 'Shots', 'Shots On Goal', 'Corners'],
        'leader_labels': ['Goals Leader', 'Assists Leader', 'Points Leader'],
    },
    'cfl': {
        'stat_labels': ['Points', 'Total Yards', 'Pass Yards', 'Rush Yards', 'Turnovers'],
        'leader_labels': ['Passing Leader', 'Rushing Leader', 'Receiving Leader'],
    },
    'ncaab': {
        'stat_labels': ['Points', 'Rebounds', 'Assists', 'FG%', '3PT%'],
        'leader_labels': ['Points Leader', 'Rebounds Leader', 'Assists Leader'],
    },
    'premierleague': {
        'stat_labels': ['Goals', 'Assists', 'Shots', 'Shots On Goal', 'Clean Sheets'],
        'leader_labels': ['Goals Leader', 'Assists Leader', 'Clean Sheets Leader'],
    },
    'bundesliga': {
        'stat_labels': ['Goals', 'Assists', 'Shots', 'Shots On Goal', 'Clean Sheets'],
        'leader_labels': ['Goals Leader', 'Assists Leader', 'Clean Sheets Leader'],
    },
    'seriea': {
        'stat_labels': ['Goals', 'Assists', 'Shots', 'Shots On Goal', 'Clean Sheets'],
        'leader_labels': ['Goals Leader', 'Assists Leader', 'Clean Sheets Leader'],
    },
    'ligue1': {
        'stat_labels': ['Goals', 'Assists', 'Shots', 'Shots On Goal', 'Clean Sheets'],
        'leader_labels': ['Goals Leader', 'Assists Leader', 'Clean Sheets Leader'],
    },
    'championsleague': {
        'stat_labels': ['Goals', 'Assists', 'Shots', 'Shots On Goal', 'Clean Sheets'],
        'leader_labels': ['Goals Leader', 'Assists Leader', 'Clean Sheets Leader'],
    },
}

def get_sport_config(sport):
    return SPORT_STATS_CONFIG.get(sport.lower(), SPORT_STATS_CONFIG.get('nba'))

class TeamInfoWindow(xbmcgui.WindowXML):
    def onInit(self):
        self.setProperty('TeamName', getattr(self, '_team_name', ''))
        self.setProperty('TeamLogo', getattr(self, '_team_logo', ''))
        self.setProperty('TeamRecord', getattr(self, '_team_record', ''))
        self.setProperty('Wins', getattr(self, '_wins', ''))
        self.setProperty('Losses', getattr(self, '_losses', ''))
        self.setProperty('Pct', getattr(self, '_pct', ''))
        self.setProperty('GB', getattr(self, '_gb', ''))
        self.setProperty('Home', getattr(self, '_home', ''))
        self.setProperty('Away', getattr(self, '_away', ''))
        self.setProperty('Last10', getattr(self, '_l10', ''))
        self.setProperty('Streak', getattr(self, '_strk', ''))
        
        sport = getattr(self, '_sport', 'nba')
        debug_log(f"TeamInfoWindow: sport='{sport}'", xbmc.LOGINFO)
        config = get_sport_config(sport)
        
        self.setProperty('Stat1Label', config['stat_labels'][0])
        self.setProperty('Stat2Label', config['stat_labels'][1])
        self.setProperty('Stat3Label', config['stat_labels'][2])
        self.setProperty('Stat4Label', config['stat_labels'][3])
        self.setProperty('Stat5Label', config['stat_labels'][4])
        
        self.setProperty('Stat1Value', getattr(self, '_stat1', ''))
        self.setProperty('Stat2Value', getattr(self, '_stat2', ''))
        self.setProperty('Stat3Value', getattr(self, '_stat3', ''))
        self.setProperty('Stat4Value', getattr(self, '_stat4', ''))
        self.setProperty('Stat5Value', getattr(self, '_stat5', ''))
        
        self.setProperty('Leader1Label', config['leader_labels'][0])
        self.setProperty('Leader2Label', config['leader_labels'][1])
        self.setProperty('Leader3Label', config['leader_labels'][2])
        if len(config['leader_labels']) > 3:
            self.setProperty('Leader4Label', config['leader_labels'][3])
        if len(config['leader_labels']) > 4:
            self.setProperty('Leader5Label', config['leader_labels'][4])
        
        self.setProperty('Leader1Value', getattr(self, '_leader1', ''))
        self.setProperty('Leader2Value', getattr(self, '_leader2', ''))
        self.setProperty('Leader3Value', getattr(self, '_leader3', ''))
        self.setProperty('Leader4Value', getattr(self, '_leader4', ''))
        self.setProperty('Leader5Value', getattr(self, '_leader5', ''))
        
        self.setProperty('Leader1Headshot', getattr(self, '_leader1_headshot', ''))
        self.setProperty('Leader2Headshot', getattr(self, '_leader2_headshot', ''))
        self.setProperty('Leader3Headshot', getattr(self, '_leader3_headshot', ''))
        self.setProperty('Leader4Headshot', getattr(self, '_leader4_headshot', ''))
        self.setProperty('Leader5Headshot', getattr(self, '_leader5_headshot', ''))
        
        self.setProperty('LeaderEraAltValue', getattr(self, '_leader_era_alt', ''))
        self.setProperty('LeaderStrikeoutsAltValue', getattr(self, '_leader_strikeouts_alt', ''))
        self.setProperty('LeaderEraAltHeadshot', getattr(self, '_leader_era_alt_headshot', ''))
        self.setProperty('LeaderStrikeoutsAltHeadshot', getattr(self, '_leader_strikeouts_alt_headshot', ''))
        
        self.setProperty('ShowAltLeaders', 'false')
        self.setProperty('Leader4Original', getattr(self, '_leader4', ''))
        self.setProperty('Leader5Original', getattr(self, '_leader5', ''))
        self.setProperty('Leader4OriginalHeadshot', getattr(self, '_leader4_headshot', ''))
        self.setProperty('Leader5OriginalHeadshot', getattr(self, '_leader5_headshot', ''))
        debug_log(f"TeamInfoWindow: Saving originals - Leader4='{getattr(self, '_leader4', '')}', Leader5='{getattr(self, '_leader5', '')}'", xbmc.LOGINFO)
        debug_log(f"TeamInfoWindow: Pitcher data - LeaderEraAltValue='{getattr(self, '_leader_era_alt', '')}', LeaderStrikeoutsAltValue='{getattr(self, '_leader_strikeouts_alt', '')}'", xbmc.LOGINFO)
        
        opponent = getattr(self, '_opponent', '')
        team_score = getattr(self, '_team_score', '')
        opponent_score = getattr(self, '_opponent_score', '')
        if opponent and team_score and opponent_score:
            self.setProperty('GameResult', f"vs {opponent}: {team_score} - {opponent_score}")
        else:
            self.setProperty('GameResult', '')
        
        # Recent games (last 5)
        recent_games = getattr(self, '_recent_games', '')
        if recent_games:
            self.setProperty('RecentGames', recent_games)
        else:
            self.setProperty('RecentGames', '')
        
        # Division/Conference records
        division_record = getattr(self, '_division_record', '')
        conference_record = getattr(self, '_conference_record', '')
        if division_record:
            self.setProperty('DivisionRecord', division_record)
        else:
            self.setProperty('DivisionRecord', '')
        if conference_record:
            self.setProperty('ConferenceRecord', conference_record)
        else:
            self.setProperty('ConferenceRecord', '')
        
        # Point/Run differential
        differential = getattr(self, '_differential', '')
        if differential:
            self.setProperty('Differential', differential)
        else:
            self.setProperty('Differential', '')
        
        # Team color (convert to Kodi format)
        team_color = getattr(self, '_team_color', '')
        xbmc.log(f"[jet_guide] TeamInfoWindow: _team_color = '{team_color}'", xbmc.LOGINFO)
        if team_color:
            try:
                # Check if it's hex (contains letters) or decimal string
                if any(c in 'abcdefABCDEF' for c in team_color):
                    # It's hex like "c8102e" - use directly
                    r = int(team_color[0:2], 16)
                    g = int(team_color[2:4], 16)
                    b = int(team_color[4:6], 16)
                else:
                    # It's decimal string like "552583" - interpret as HEX (not decimal!)
                    color_int = int(team_color, 16)  # Read as hex!
                    r = (color_int >> 16) & 0xFF
                    g = (color_int >> 8) & 0xFF
                    b = color_int & 0xFF
                # Kodi uses AARRGGBB format (hex with alpha first)
                kodi_color = f"FF{r:02X}{g:02X}{b:02X}"
                xbmc.log(f"[jet_guide] TeamInfoWindow: RGB = ({r}, {g}, {b}), Kodi color = {kodi_color}", xbmc.LOGINFO)
            except Exception as e:
                kodi_color = 'FFFFFFFF'  # Default white
                xbmc.log(f"[jet_guide] TeamInfoWindow: Color conversion failed: {e}", xbmc.LOGERROR)
            self.setProperty('TeamColor', kodi_color)
            xbmc.log(f"[jet_guide] TeamInfoWindow: Set TeamColor property to {kodi_color}", xbmc.LOGINFO)
            self.setProperty('TeamColorHex', team_color)
        else:
            self.setProperty('TeamColor', 'FF333333')
            self.setProperty('TeamColorHex', '')
        
        # Next game info
        next_game = getattr(self, '_next_game', '')
        if next_game:
            self.setProperty('NextGame', next_game)
        else:
            self.setProperty('NextGame', '')
        
        # Season leaders/rankings
        season_leaders = getattr(self, '_season_leaders', {})
        if season_leaders:
            # Format as readable string: "Stat: Rank | Stat: Rank"
            leader_parts = []
            player_leader_parts = []
            for key, val in season_leaders.items():
                if key == 'player_leaders' and isinstance(val, dict):
                    # Handle player leaders separately
                    for pname, pstats in val.items():
                        player_leader_parts.append(f"{pname}: {pstats}")
                elif isinstance(val, dict):
                    name = val.get('name', key)
                    value = val.get('value', '')
                    if name and value:
                        leader_parts.append(f"{name}: {value}")
            if leader_parts:
                # Split into rows: first 3 stats on row1, next 3 on row2, remaining on row3
                row1 = leader_parts[:3]
                row2 = leader_parts[3:6]
                row3 = leader_parts[6:9]
                # Format with spacing to create columns effect
                if len(row1) >= 2:
                    season_str = '  |  '.join(row1) + '\n'
                else:
                    season_str = '\n'.join(row1) + '\n'
                if row2:
                    season_str += '  |  '.join(row2) + '\n'
                if row3:
                    season_str += '  |  '.join(row3)
                self.setProperty('SeasonLeaders', season_str)
            else:
                self.setProperty('SeasonLeaders', '')
            
            # Set player leaders - use newlines for scrollable textbox
            if player_leader_parts:
                self.setProperty('PlayerLeaders', '\n'.join(player_leader_parts))
            else:
                self.setProperty('PlayerLeaders', '')
        else:
            self.setProperty('SeasonLeaders', '')
            self.setProperty('PlayerLeaders', '')

    def onAction(self, action):
        action_id = action.getId()
        if action_id in (10, 92):
            self.close()

    def onClick(self, control_id):
        debug_log(f"TeamInfoWindow: onClick called with control_id={control_id}", xbmc.LOGINFO)
        self.close()

if __name__ == '__main__':
    args = sys.argv[1:] if len(sys.argv) > 1 else []
    team_name = args[0].replace('|', ',') if len(args) > 0 else ''
    team_logo = args[1].replace('|', ',') if len(args) > 1 else ''
    team_record = args[2].replace('|', ',') if len(args) > 2 else ''
    wins = args[3].replace('|', ',') if len(args) > 3 else ''
    losses = args[4].replace('|', ',') if len(args) > 4 else ''
    pct = args[5].replace('|', ',') if len(args) > 5 else ''
    gb = args[6].replace('|', ',') if len(args) > 6 else ''
    home = args[7].replace('|', ',') if len(args) > 7 else ''
    away = args[8].replace('|', ',') if len(args) > 8 else ''
    l10 = args[9].replace('|', ',').replace('___PIPE___', ',') if len(args) > 9 else ''
    strk = args[10].replace('|', ',') if len(args) > 10 else ''
    stat1 = args[11].replace('|', ',') if len(args) > 11 else ''
    stat2 = args[12].replace('|', ',') if len(args) > 12 else ''
    stat3 = args[13].replace('|', ',') if len(args) > 13 else ''
    stat4 = args[14].replace('|', ',') if len(args) > 14 else ''
    stat5 = args[15].replace('|', ',') if len(args) > 15 else ''
    leader1 = args[16].replace('|', ',').replace('___PIPE___', ',') if len(args) > 16 else ''
    leader2 = args[17].replace('|', ',').replace('___PIPE___', ',') if len(args) > 17 else ''
    leader3 = args[18].replace('|', ',').replace('___PIPE___', ',') if len(args) > 18 else ''
    leader4 = args[19].replace('|', ',').replace('___PIPE___', ',') if len(args) > 19 else ''
    leader5 = args[20].replace('|', ',').replace('___PIPE___', ',') if len(args) > 20 else ''
    sport = args[21].replace('|', ',').replace('___PIPE___', ',') if len(args) > 21 else 'nba'
    opponent = args[22].replace('|', ',').replace('___PIPE___', ',') if len(args) > 22 else ''
    team_score = args[23].replace('|', ',').replace('___PIPE___', ',') if len(args) > 23 else ''
    opponent_score = args[24].replace('|', ',').replace('___PIPE___', ',') if len(args) > 24 else ''
    leader1_headshot = args[25].replace('|', ',').replace('___PIPE___', ',') if len(args) > 25 else ''
    leader2_headshot = args[26].replace('|', ',').replace('___PIPE___', ',') if len(args) > 26 else ''
    leader3_headshot = args[27].replace('|', ',').replace('___PIPE___', ',') if len(args) > 27 else ''
    leader4_headshot = args[28].replace('|', ',').replace('___PIPE___', ',') if len(args) > 28 else ''
    leader5_headshot = args[29].replace('|', ',').replace('___PIPE___', ',') if len(args) > 29 else ''
    
    recent_games = args[30].replace('|', ',').replace('___PIPE___', ',') if len(args) > 30 else ''
    division_record = args[31].replace('|', ',').replace('___PIPE___', ',') if len(args) > 31 else ''
    conference_record = args[32].replace('|', ',').replace('___PIPE___', ',') if len(args) > 32 else ''
    next_game = args[33].replace('|', ',').replace('___PIPE___', ',') if len(args) > 33 else ''
    season_leaders_str = args[34].replace('|', ',').replace('___PIPE___', ',') if len(args) > 34 else ''
    differential = args[35].replace('|', ',').replace('___PIPE___', ',') if len(args) > 35 else ''
    team_color = args[36].replace('|', ',').replace('___PIPE___', ',') if len(args) > 36 else ''
    leader_era_alt = args[37].replace('|', ',').replace('___PIPE___', ',') if len(args) > 37 else ''
    leader_strikeouts_alt = args[38].replace('|', ',').replace('___PIPE___', ',') if len(args) > 38 else ''
    leader_era_alt_headshot = args[39].replace('|', ',').replace('___PIPE___', ',') if len(args) > 39 else ''
    leader_strikeouts_alt_headshot = args[40].replace('|', ',').replace('___PIPE___', ',') if len(args) > 40 else ''
    
    # Parse season leaders dict from string
    import ast
    season_leaders = {}
    if season_leaders_str and season_leaders_str != 'None':
        try:
            season_leaders = ast.literal_eval(season_leaders_str)
        except:
            season_leaders = {}
    
    addon_path = ADDON.getAddonInfo('path') if ADDON else 'special://home/addons/plugin.video.jet_guide'
    win = TeamInfoWindow('team_info.xml', addon_path)
    win._team_name = team_name
    win._team_logo = team_logo
    win._team_record = team_record
    win._wins = wins
    win._losses = losses
    win._pct = pct
    win._gb = gb
    win._home = home
    win._away = away
    win._l10 = l10
    win._strk = strk
    win._stat1 = stat1
    win._stat2 = stat2
    win._stat3 = stat3
    win._stat4 = stat4
    win._stat5 = stat5
    win._leader1 = leader1
    win._leader2 = leader2
    win._leader3 = leader3
    win._leader4 = leader4
    win._leader5 = leader5
    win._leader1_headshot = leader1_headshot
    win._leader2_headshot = leader2_headshot
    win._leader3_headshot = leader3_headshot
    win._leader4_headshot = leader4_headshot
    win._leader5_headshot = leader5_headshot
    win._sport = sport
    win._opponent = opponent
    win._team_score = team_score
    win._opponent_score = opponent_score
    win._recent_games = recent_games
    win._division_record = division_record
    win._conference_record = conference_record
    win._next_game = next_game
    win._season_leaders = season_leaders
    win._differential = differential
    win._team_color = team_color
    win._leader_era_alt = leader_era_alt
    win._leader_strikeouts_alt = leader_strikeouts_alt
    win._leader_era_alt_headshot = leader_era_alt_headshot
    win._leader_strikeouts_alt_headshot = leader_strikeouts_alt_headshot
    win.doModal()
    del win
