import xbmc
import xbmcgui
import xbmcaddon
import urllib.parse
from urllib.parse import urlencode, quote
from typing import Dict, List, Any
from analytics import track
from favorites import favorites_manager
from jet_parser import parse_m3u8
from addon import M3U8_PATH

try:
    from themes import apply_theme_to_window
except ImportError:
    def apply_theme_to_window(window):
        pass  # No theming available

ADDON = xbmcaddon.Addon()

def get_channels():
    """Return the list of channels from the main M3U8 playlist."""
    return parse_m3u8(M3U8_PATH)

class ChannelListWindow(xbmcgui.WindowXML):
    def __init__(self, xml_file: str, addon_path: str, channels: List[Dict[str, Any]] = None):
        super().__init__(xml_file, addon_path, "default")
        self.channels = channels or []
        self.list_control = None
    def onInit(self):
        """Initialize window after creation"""
        try:
            # Apply theme colors
            apply_theme_to_window(self)
            
            # Get list control
            self.list_control = self.getControl(100)
            # Populate channels
            for channel in self.channels:
                name = channel.get('name', channel.get('title', 'Unknown Channel'))
                # Add star to favorites
                if favorites_manager.is_favorite(channel['tvg_id']):
                    name = f"[COLOR gold]★[/COLOR] {name}"
                list_item = xbmcgui.ListItem(name)
                list_item.setArt({'icon': channel.get('logo', '')})
                # Context menu will be handled by onAction
                self.list_control.addItem(list_item)
            # Set focus to list
            self.setFocusId(100)
        except Exception as e:
            xbmcgui.Dialog().ok("Error", f"Failed to initialize channel list: {str(e)}")
            self.close()
    def make_url(self, action: str, channel_id: str) -> str:
        """Create properly encoded plugin URL"""
        base = "plugin://plugin.video.jet_guide/"
        params = urllib.parse.urlencode({'action': action, 'id': channel_id})
        url = f"{base}?{params}"
        xbmc.log(f"ChannelList: Created URL for action={action}, id={channel_id}: {url}", xbmc.LOGINFO)
        return url
    def play_channel(self, channel: Dict[str, Any]):
        """Play a channel directly"""
        try:
            track(event="play", channel_name=channel['name'], channel_id=channel.get('tvg_id', ''), url=channel['url'], source="channellist")
            list_item = xbmcgui.ListItem(channel['name'])
            list_item.setArt({'icon': channel.get('logo', '')})
            # Set stream URL directly
            url = channel['url']
            if '|' in url:
                url = url.split('|')[0].strip()
            xbmc.Player().play(url, list_item)
        except Exception as e:
            xbmcgui.Dialog().ok("Error", f"Failed to play channel: {str(e)}")
