import xbmc
import xbmcgui
import xbmcaddon
import threading
import time
from tools import debug_log

SLIDESHOW_INTERVAL = 2.0  # Default 2 seconds


def is_game_live(status):
    """Check if a game/race is currently live based on status text."""
    if not status:
        return False
    status_lower = status.lower()
    if 'final' in status_lower:
        return False
    # First check for base status keywords that definitively indicate the game is active.
    # These must appear in the status to consider it live.
    active_base_hints = [
        'live', 'in progress', 'halftime', 'half time',
        'delayed', 'suspended',
    ]
    has_active_base = any(hint in status_lower for hint in active_base_hints)
    # For statuses like "In Progress - 2Q 5:30" or "Halftime", the active base
    # hint is already matched above. But some statuses embed period/clock info
    # without an active base hint (e.g. "Scheduled - 1Q 12:00" from ESPN),
    # so we also check for period/clock hints ONLY when an active base hint
    # is present, OR when the status looks like a live-game detail string
    # (contains a dash with quarter/period/inning info but NOT "scheduled").
    period_clock_hints = [
        'quarter', 'period', 'inning',
        'bot', 'top', 'current', 'lap',
        ' q1', ' q2', ' q3', ' q4',
        ' ot', '1st', '2nd', '3rd', '4th',
    ]
    if has_active_base:
        return True
    # Reject scheduled/pre-game statuses - do not treat them as live even if
    # they contain period/clock keywords
    if 'scheduled' in status_lower or 'pre' == status_lower.strip():
        return False
    # Fall back: if period/clock hints are present AND the status does not
    # look like a pre-game/scheduled string, consider it live
    return any(hint in status_lower for hint in period_clock_hints)


def filter_live_games(games):
    """Filter games/races to only include live ones."""
    return [g for g in games if is_game_live(g.get('status', ''))]


def format_slideshow_item(game, channels):
    """Format a live game/race for slideshow display."""
    # Check if this is racing data
    if 'event_name' in game or 'circuit' in game:
        # Racing format
        event_name = game.get('event_name', '')
        circuit = game.get('circuit', '')
        status = game.get('status', '')
        winner = game.get('winner', {})
        
        winner_name = winner.get('name', '') if winner else ''
        winner_flag = winner.get('flag', '') if winner else ''
        
        # Build display text with lap info for live races
        display_text = event_name.upper()
        if circuit:
            display_text += f" - {circuit}"
        
        # Add lap progress for live races
        lap = game.get('lap', '')
        if lap:
            display_text += f" | Lap {lap}"
        
        if winner_name:
            display_text += f" | Winner: {winner_name}"
        
        return {
            'team1': event_name,
            'team2': '',
            'team1_display': event_name.upper(),
            'team2_display': '',
            'score1': '',
            'score2': '',
            'status': status,
            'network': game.get('network', 'TBD'),
            'broadcaster': game.get('broadcaster', 'TBD'),
            'logo1': winner_flag or '',
            'logo2': '',
            'display_text': display_text
        }
    
    # Traditional sports format
    team1 = game.get('team1', '')
    team2 = game.get('team2', '')
    score1 = game.get('score1', '')
    score2 = game.get('score2', '')
    status = game.get('status', '')
    network = game.get('network', 'TBD')
    broadcaster = game.get('broadcaster', 'TBD')

    # Get team logos - first try from game data, then from channels
    logo1 = game.get('logo1', '')
    logo2 = game.get('logo2', '')

    # If no logos in game data, try to get from channels list
    if not logo1 or not logo2:
        for ch in channels:
            if ch.get('name', '').lower() == team1.lower():
                logo1 = logo1 or ch.get('logo', '')
            if ch.get('name', '').lower() == team2.lower():
                logo2 = logo2 or ch.get('logo', '')

    return {
        'team1': team1,
        'team2': team2,
        'team1_display': team1.upper(),
        'team2_display': team2.upper(),
        'score1': score1,
        'score2': score2,
        'status': status,
        'network': network,
        'broadcaster': broadcaster,
        'logo1': logo1,
        'logo2': logo2,
        'display_text': f"{team1.upper()} {score1} - {score2} {team2.upper()}"
    }


class LiveGamesSlideshow:
    """Manages the live games slideshow in the sports grid."""
    
    _instance = None
    _lock = threading.Lock()
    
    def __init__(self, parent_window):
        self.parent = parent_window
        self.live_games = []
        self.current_index = 0
        self.is_running = False
        self._stop_event = threading.Event()
        self._thread = None
        # Get slideshow interval from settings (default 2 seconds)
        try:
            addon = xbmcaddon.Addon()
            self.interval = float(addon.getSetting('slideshow_interval') or '2')
        except Exception:
            self.interval = SLIDESHOW_INTERVAL
        
    def start(self, games, channels):
        """Start the slideshow with current live games."""
        self._stop_event.clear()
        self.live_games = filter_live_games(games)
        self.current_index = 0
        
        if not self.live_games:
            self._clear_display()
            return
            
        self.is_running = True
        self._show_current_game(channels)
        
        # Start background thread for slideshow updates
        if self._thread is None or not self._thread.is_alive():
            self._thread = threading.Thread(target=self._slideshow_loop, daemon=True)
            self._thread.start()
            
    def stop(self):
        """Stop the slideshow."""
        self.is_running = False
        self._stop_event.set()
        
    def refresh(self, games, channels):
        """Refresh the slideshow with new game data."""
        with self._lock:
            self.live_games = filter_live_games(games)
            self.current_index = 0
            if self.live_games:
                self._show_current_game(channels)
            else:
                self._clear_display()
            
    def _slideshow_loop(self):
        """Background thread loop for slideshow updates."""
        while not self._stop_event.is_set() and self.is_running:
            with self._lock:
                if not self.live_games:
                    break
                self.current_index = (self.current_index + 1) % len(self.live_games)
                self._show_current_game(self.parent.channels if hasattr(self.parent, 'channels') else [])
            time.sleep(self.interval)
        
    def _show_current_game(self, channels):
        """Display the current live game in the slideshow."""
        if not self.live_games:
            return
            
        game = self.live_games[self.current_index]
        item = format_slideshow_item(game, channels)
        
        # Update window properties for XML skin
        self.parent.setProperty('SlideshowTeam1', item['team1_display'])
        self.parent.setProperty('SlideshowTeam2', item['team2_display'])
        self.parent.setProperty('SlideshowScore1', item['score1'])
        self.parent.setProperty('SlideshowScore2', item['score2'])
        self.parent.setProperty('SlideshowStatus', item['status'])
        self.parent.setProperty('SlideshowNetwork', item['network'])
        self.parent.setProperty('SlideshowBroadcaster', item.get('broadcaster', 'TBD'))
        self.parent.setProperty('SlideshowLogo1', item['logo1'])
        self.parent.setProperty('SlideshowLogo2', item['logo2'])
        
        # debug_log(f"LiveGamesSlideshow: Showing {item['display_text']}", xbmc.LOGINFO)
        # debug_log(f"LiveGamesSlideshow: Logo1={item['logo1'][:80] if item['logo1'] else 'NONE'}", xbmc.LOGINFO)
        # debug_log(f"LiveGamesSlideshow: Logo2={item['logo2'][:80] if item['logo2'] else 'NONE'}", xbmc.LOGINFO)
        
    def _clear_display(self):
        """Clear the slideshow display."""
        self.parent.setProperty('SlideshowTeam1', '')
        self.parent.setProperty('SlideshowTeam2', '')
        self.parent.setProperty('SlideshowScore1', '')
        self.parent.setProperty('SlideshowScore2', '')
        self.parent.setProperty('SlideshowStatus', '')
        self.parent.setProperty('SlideshowNetwork', '')
        self.parent.setProperty('SlideshowBroadcaster', '')
        self.parent.setProperty('SlideshowLogo1', '')
        self.parent.setProperty('SlideshowLogo2', '')