# wcs/ai/DialogMyCinema.py
"""
MyCinema Dialog - Kino budoucnosti.

Rozširuje MyTV dialog pro správu filmových kin místo TV kanálu se seriály.
Většina logiky je sdílená, přepisujeme pouze specifické cásti pro filmy.

Modulární architektura:
- Dědí z MyTVDialog
- Přepisuje jen metody specifické pro filmy
- Používá sdílený AddMediaDialog s media_type='cinema'
"""

import xbmc
import xbmcgui
import xbmcaddon
import random
import threading

from wcs.ai.DialogMyTV import MyTVDialog
from wcs.ai.MediaChannelManager import MediaChannelManager
from wcs.ai.DialogAddMedia import AddMediaDialog, create_add_media_controller
from wcs.ai import ChannelHistory
from wcs.caching import get_cache_manager


class MyCinemaDialog(MyTVDialog):
    """
    Dialog pro MyCinema - správa filmových kin.
    
    Dědí z MyTVDialog a přepisuje pouze specifické cásti pro filmy.
    Používá stejný AddMediaDialog jako MyTV, jen s media_type='cinema'.
    """
    
    def __init__(self, xml_filename, addon_path, *args, **kwargs):
        # Override channel type before calling parent __init__
        self._channel_type = 'cinema'
        super(MyCinemaDialog, self).__init__(xml_filename, addon_path, *args, **kwargs)
        
        # Override with cinema channel manager
        self.channel_manager = MediaChannelManager(self.addon, channel_type='cinema')
        
        # Nav section for sidebar
        self._nav_section_id = 'my_cinema'
    
    def onInit(self):
        """Initialize dialog with cinema-specific settings."""
        self._reset_state()
        
        # Cinema-specific title
        self.setProperty('WCS.AIChat.Title', 'MyCinema - kino budoucnosti')
        self.setProperty('WCS.AIChat.Status', 'Pripraveno')
        
        # Set media type property for XML conditional visibility
        self.setProperty('WCS.MediaType', 'cinema')
        
        # Cinema-specific button labels
        self.setProperty('WCS.Button.Play', 'Prehrat filmy')
        self.setProperty('WCS.Button.Delete', 'Smazat kino')
        self.setProperty('WCS.Button.DeleteConfirm', 'Opravdu smazat kino?')
        
        # Always start with the first channel
        self.current_channel_index = 0
        
        # CLEAR ALL BACKGROUND PROPERTIES - Start fresh with matte layer
        self.clearProperty('WCS.MyTV.Background.Custom')
        self.clearProperty('WCS.MyTV.Background.Ready')
        
        # Clear any leftover confirmation dialogs from previous session
        self.clearProperty('WCS.MyTV.DeleteSeriesConfirm')
        self.clearProperty('WCS.MyTV.DeleteConfirm')
        
        # RESET PROGRAM LIST IMMEDIATELY - Clear cached items
        try:
            program_list = self.getControl(9000)
            program_list.reset()
        except:
            pass
        
        # Set background mode and animation properties
        self._setup_background_properties()
        
        # Static mode: Only set Ready if no processing needed
        if self._bg_mode == self.BG_STATIC and not self._is_background_processing_needed():
            self.setProperty('WCS.MyTV.Background.Ready', 'true')
        
        # Poster collage: Start background generation IMMEDIATELY
        if self._bg_mode == self.BG_COLLAGE_POSTERS:
            self._update_background()
        
        # Static mode with effects: Generate blurred version
        if self._bg_mode == self.BG_STATIC and self._is_background_processing_needed():
            self._update_background()
        
        # Load View
        self.refresh_channels_view(set_focus=True)
        
        # Trigger background generation for other modes
        if self._bg_mode not in (self.BG_STATIC, self.BG_COLLAGE_POSTERS):
            self._update_background()
        
        # Ensure sidebar is hidden initially
        if self._show_nav_on_init:
            self._show_nav_sidebar(animate=False)
        else:
            self.clearProperty('WCS.AIChat.Visible')
    
    # ==================================================================================
    # OVERRIDE: ADD MEDIA DIALOG - Používá sdílený AddMediaDialog s media_type='cinema'
    # ==================================================================================
    
    def _show_add_series_dialog(self):
        """
        Override: Show the inline Add Media dialog for MOVIES.
        
        Toto je klíčová přepsaná metoda - parent volá tuto metodu pro grid,
        my ji přepisujeme aby používala media_type='cinema' místo 'tv'.
        """
        list_control = self.getControl(2000)
        channel_id = list_control.getSelectedItem().getProperty('channel_id')
        
        # Create controller using unified AddMediaDialog with media_type='cinema'
        self._add_series_controller = create_add_media_controller(
            self, self.addon, self.channel_manager, channel_id,
            on_close_callback=None,
            media_type='cinema'
        )
        
        # Show the inline dialog
        self._add_series_controller.show()
    
    def _close_add_series_dialog(self):
        """
        Override: Close the inline Add Media dialog and refresh if needed.
        Handles cinema-specific naming and channel creation logic.
        """
        if not hasattr(self, '_add_series_controller') or not self._add_series_controller:
            return
        
        media_added = self._add_series_controller.was_media_added()
        channel_id = self._add_series_controller.channel_id
        self._add_series_controller.hide()
        self._add_series_controller = None
        
        # Check if this was a newly created cinema that needs auto-naming
        pending_channel_id = getattr(self, '_pending_new_channel_id', None)
        
        if pending_channel_id and pending_channel_id == channel_id:
            self._pending_new_channel_id = None
            
            channel = self.channel_manager.get_channel_by_id(channel_id)
            
            if not channel or not channel.media_list:
                # No movies added - delete the empty cinema
                self.channel_manager.delete_channel(channel_id)
                self._show_toast("Kino nebylo vytvoreno - nepridali jste zadne filmy", "warning")
            else:
                # Generate cinema name based on genres
                from wcs.ai.ChannelNameGenerator import ChannelNameGenerator
                generator = ChannelNameGenerator(self.addon)
                
                naming_mode = self.addon.getSetting('mytv_channel_naming') or ''
                
                if 'AI' in naming_mode or naming_mode == '1':
                    # AI mode - use temporary name and generate asynchronously
                    temp_name = generator.generate_from_genres(channel.media_list, media_type='cinema')
                    self.channel_manager.rename_channel(channel_id, temp_name)
                    self.channel_manager.generate_channel_composite(channel_id)
                    self._generate_ai_channel_name_async(channel_id, channel.media_list, generator)
                else:
                    # Sync genre-based naming
                    new_name = generator.generate_from_genres(channel.media_list, media_type='cinema')
                    self.channel_manager.rename_channel(channel_id, new_name)
                    self.channel_manager.generate_channel_composite(channel_id)
                    self._show_toast(f"Kino '{new_name}' vytvoreno", "success")
            
            # Full refresh
            self.current_channel_index = 0
            self.refresh_channels_view(set_focus=True)
        
        elif media_added:
            # Just refresh the current channel
            self.channel_manager.generate_channel_composite(channel_id)
            self.update_editor_view()
            self.refresh_program_view()
            self.refresh_channels_view()
    
    def _generate_ai_channel_name_async(self, channel_id, media_list, generator):
        """Generate AI name for cinema asynchronously."""
        def worker():
            try:
                ai_name = generator.generate_from_ai(media_list, media_type='cinema')
                if ai_name:
                    self.channel_manager.rename_channel(channel_id, ai_name)
                    self.refresh_channels_view()
                    self._show_toast(f"AI pojmenovalo kino: {ai_name}", "success")
            except Exception as e:
                xbmc.log(f"[MyCinema] AI naming error: {e}", xbmc.LOGERROR)
        
        threading.Thread(target=worker, daemon=True).start()
    
    # ==================================================================================
    # OVERRIDE: CHANNEL LIST VIEW - Cinema-specific labels and placeholders
    # ==================================================================================
    
    def refresh_channels_view(self, set_focus=False):
        """Populate the bottom list with cinema channels (kina)."""
        channels = self.channel_manager.get_all_channels()
        list_control = self.getControl(2000)
        list_control.reset()
        
        for ch in channels:
            item = xbmcgui.ListItem(label=ch.name)
            icon = ch.icon if ch.icon else 'special://home/addons/plugin.video.milionar/resources/media/placeholder_movie_card.png'
            item.setArt({'poster': icon})
            item.setProperty('channel_id', ch.id)
            list_control.addItem(item)
            
        # Add "Create New Cinema" item
        create_item = xbmcgui.ListItem(label="Vytvorit nove kino")
        create_item.setArt({'poster': 'special://home/addons/plugin.video.milionar/resources/media/plus_card.png'})
        create_item.setProperty('is_create_button', 'true')
        list_control.addItem(create_item)
            
        # Select first if available
        if self.current_channel_index >= list_control.size():
            self.current_channel_index = 0
            
        if list_control.size() > 0:
            list_control.selectItem(self.current_channel_index)
            self.update_editor_view()
            self.refresh_program_view()
            if set_focus:
                self._delayed_focus(2000, delay=0.5)
    
    # ==================================================================================
    # OVERRIDE: EDITOR GRID - Shows movies instead of series
    # ==================================================================================
    
    def update_editor_view(self):
        """Update grid 9100 based on selected cinema - shows movies."""
        list_control = self.getControl(2000)
        idx = list_control.getSelectedPosition()
        if idx < 0:
            return
            
        item = list_control.getListItem(idx)
        
        # If "Create New" is selected, clear editor and return
        if item.getProperty('is_create_button') == 'true':
            self.getControl(9100).reset()
            return
            
        channel_id = item.getProperty('channel_id')
        channel = self.channel_manager.get_channel_by_id(channel_id)
        
        grid_control = self.getControl(9100)
        grid_control.reset()
        
        if channel:
            # Add existing movies
            for movie in channel.media_list:
                m_item = xbmcgui.ListItem(label=movie.get('name') or movie.get('title', ''))
                poster = movie.get('poster_path') or movie.get('poster')
                if poster and not poster.startswith('http'):
                     poster = f"https://image.tmdb.org/t/p/w500{poster}"
                elif not poster:
                     poster = 'special://home/addons/plugin.video.milionar/resources/media/placeholder_movie_card.png'
                
                m_item.setArt({'poster': poster})
                m_item.setProperty('movie_id', str(movie.get('id')))
                m_item.setProperty('channel_id', channel_id)
                grid_control.addItem(m_item)

            # Always add "Add Movie" card at the end of the grid
            add_item = xbmcgui.ListItem(label="Pridat film")
            add_item.setArt({'poster': 'special://home/addons/plugin.video.milionar/resources/media/plus_card.png'})
            add_item.setProperty('is_add_button', 'true')
            add_item.setProperty('channel_id', channel_id)
            grid_control.addItem(add_item)
    
    # ==================================================================================
    # OVERRIDE: PROGRAM VIEW - Shows movie list (simplified, no episodes)
    # ==================================================================================
    
    def refresh_program_view(self):
        """Load movie list for the current cinema (simplified - no episodes)."""
        # Initialize state if needed
        if not hasattr(self, '_program_load_token'):
            self._program_load_token = 0
        if not hasattr(self, '_program_load_timer'):
            self._program_load_timer = None
        
        # Increment token
        self._program_load_token += 1
        current_token = self._program_load_token
        
        # Get channel ID
        list_control = self.getControl(2000)
        idx = list_control.getSelectedPosition()
        if idx < 0:
            return
        
        item = list_control.getListItem(idx)
        channel_id = item.getProperty('channel_id')
        if not channel_id:
            return
        
        self._current_loaded_channel_id = channel_id
        
        # Update channel statistics display
        self._update_channel_stats(channel_id)
        
        # Cancel existing timer
        if self._program_load_timer:
            self._program_load_timer.cancel()
        
        # Schedule debounced async refresh
        self._program_load_timer = threading.Timer(
            0.3,
            self._async_movie_load,
            args=(current_token, channel_id)
        )
        self._program_load_timer.daemon = True
        self._program_load_timer.start()
    
    def _async_movie_load(self, token, channel_id):
        """Load movies for the program list (async worker)."""
        # Check if still valid
        if token != self._program_load_token:
            return
        
        channel = self.channel_manager.get_channel_by_id(channel_id)
        if not channel or not channel.media_list:
            try:
                program_list = self.getControl(9000)
                program_list.reset()
            except:
                pass
            return
        
        # Shuffle movies
        movies = list(channel.media_list)
        random.shuffle(movies)
        
        # Update UI on main thread
        try:
            program_list = self.getControl(9000)
            program_list.reset()
            
            for movie in movies[:20]:  # Limit to 20 movies
                item = self._create_movie_list_item(movie, channel_id)
                if item:
                    program_list.addItem(item)
            
            # Update background
            self._update_background(channel_id=channel_id)
            
        except Exception as e:
            xbmc.log(f"[MyCinema] Error loading movies: {e}", xbmc.LOGERROR)
    
    def _create_movie_list_item(self, movie, channel_id):
        """Create ListItem for movie in program list."""
        try:
            name = movie.get('name') or movie.get('title', 'Neznamy film')
            item = xbmcgui.ListItem(label=name)
            
            # Poster/thumb
            poster = movie.get('poster_path') or movie.get('poster')
            if poster and not poster.startswith('http'):
                poster = f"https://image.tmdb.org/t/p/w500{poster}"
            
            backdrop = movie.get('backdrop_path') or movie.get('fanart')
            if backdrop and not backdrop.startswith('http'):
                backdrop = f"https://image.tmdb.org/t/p/w1280{backdrop}"
            
            item.setArt({
                'poster': poster or 'special://home/addons/plugin.video.milionar/resources/media/placeholder_movie_card.png',
                'thumb': backdrop or poster or '',
                'fanart': backdrop or ''
            })
            
            # Properties
            year = movie.get('release_date', '')[:4] if movie.get('release_date') else ''
            runtime = movie.get('runtime', 0)
            if runtime:
                item.setLabel2(f"{runtime} min")
            
            item.setProperty('movie_id', str(movie.get('id', '')))
            item.setProperty('channel_id', channel_id)
            item.setProperty('year', year)
            item.setProperty('plot', movie.get('overview', ''))
            item.setProperty('plot_short', (movie.get('overview', '')[:100] + '...') if len(movie.get('overview', '')) > 100 else movie.get('overview', ''))
            
            # For UI compatibility with TV layout
            # Use tagline if available, otherwise empty
            item.setProperty('episode_title', movie.get('tagline', ''))
            item.setProperty('ep_code', year)
            
            # Check if movie was watched
            movie_id = movie.get('id')
            if movie_id and channel_id:
                if ChannelHistory.is_movie_watched(channel_id, movie_id):
                    item.setProperty('watched', 'true')
            
            return item
        except Exception as e:
            xbmc.log(f"[MyCinema] Error creating movie item: {e}", xbmc.LOGERROR)
            return None
    
    # ==================================================================================
    # OVERRIDE: GRID CLICK - Handle movie cards (uses movie_id instead of series_id)
    # ==================================================================================
    
    def _handle_grid_click(self):
        """Handle click on grid items - movies or add button."""
        self._block_sidebar = True
        try:
            grid = self.getControl(9100)
            item = grid.getSelectedItem()
            if not item:
                return
            
            # Check if it's the "Add Movie" placeholder
            if item.getProperty('is_add_button') == 'true':
                # Show Add Media dialog for movies
                self._show_add_series_dialog()  # Uses our override with media_type='cinema'
                return

            # Show Movie Detail dialog (reusing the Series Detail UI)
            movie_id = item.getProperty('movie_id')
            channel_id = item.getProperty('channel_id')
            self._show_movie_detail_dialog(movie_id, channel_id)
        finally:
            self._block_sidebar = False
    
    def _show_movie_detail_dialog(self, movie_id, channel_id):
        """Show the inline Movie Detail dialog (reuses Series Detail UI)."""
        # Store current movie info for removal action
        self._series_detail_series_id = movie_id  # Reuse same property name for removal
        self._series_detail_channel_id = channel_id
        
        # Get movie data from channel
        channel = self.channel_manager.get_channel_by_id(channel_id)
        movie_data = None
        if channel:
            for m in channel.media_list:
                if str(m.get('id')) == str(movie_id):
                    movie_data = m
                    break
        
        if not movie_data:
            xbmc.log(f"[MyCinema] Movie data not found for id={movie_id}", xbmc.LOGWARNING)
            return
        
        # Fetch additional metadata from TMDb
        metadata = self._get_movie_metadata(movie_id, movie_data)
        
        # Set window properties for XML (using same SeriesDetail properties)
        self.setProperty('WCS.MyTV.SeriesDetail.Name', metadata.get('name', ''))
        self.setProperty('WCS.MyTV.SeriesDetail.Year', str(metadata.get('year', '')))
        self.setProperty('WCS.MyTV.SeriesDetail.Genre', metadata.get('genre', ''))
        self.setProperty('WCS.MyTV.SeriesDetail.Rating', str(metadata.get('rating', '')))
        self.setProperty('WCS.MyTV.SeriesDetail.Plot', metadata.get('plot', ''))
        self.setProperty('WCS.MyTV.SeriesDetail.Fanart', metadata.get('fanart', ''))
        self.setProperty('WCS.MyTV.SeriesDetail.Logo', metadata.get('logo', ''))
        self.setProperty('WCS.MyTV.SeriesDetail.Poster', metadata.get('poster', ''))
        
        # Show the dialog
        self.setProperty('WCS.MyTV.SeriesDetail.Active', 'true')
        
        # Focus on remove button
        self._delayed_focus(9300, delay=0.1)
    
    def _get_movie_metadata(self, movie_id, movie_data):
        """Get movie metadata from cache or TMDb."""
        import requests
        from wcs.metadata.TMDbClient import get_tmdb_api_key
        
        # Try cache first - only use if it has meaningful data
        cache_key = f"movie_detail_{movie_id}"
        cached = self._cache.get(cache_key)
        if cached and (cached.get('fanart') or cached.get('genre') or cached.get('rating')):
            return cached
        
        # Build basic metadata from what we have
        metadata = {
            'name': movie_data.get('name') or movie_data.get('title', ''),
            'year': movie_data.get('year', '') or (movie_data.get('release_date', '')[:4] if movie_data.get('release_date') else ''),
            'genre': '',
            'rating': '',
            'plot': movie_data.get('overview', '') or movie_data.get('plot', ''),
            'fanart': '',
            'logo': '',
            'poster': ''
        }
        
        # Get poster
        poster = movie_data.get('poster_path') or movie_data.get('poster')
        if poster:
            if not poster.startswith('http'):
                poster = f"https://image.tmdb.org/t/p/w500{poster}"
            metadata['poster'] = poster
        
        # Fetch full details from TMDb
        try:
            api_key = get_tmdb_api_key(self.addon)
            
            # Fetch movie details
            details_url = f'https://api.themoviedb.org/3/movie/{movie_id}?api_key={api_key}&language=cs-CZ'
            response = requests.get(details_url, timeout=10)
            if response.status_code == 200:
                details = response.json()
                
                metadata['name'] = details.get('title', metadata['name'])
                metadata['plot'] = details.get('overview', metadata['plot'])
                metadata['rating'] = f"{details.get('vote_average', 0):.1f}"
                
                # Year
                if details.get('release_date'):
                    metadata['year'] = details['release_date'][:4]
                
                # Genres
                genres = details.get('genres', [])
                if genres:
                    metadata['genre'] = ', '.join([g.get('name', '') for g in genres[:3]])
                
                # Fanart/backdrop
                backdrop = details.get('backdrop_path')
                if backdrop:
                    metadata['fanart'] = f"https://image.tmdb.org/t/p/w1280{backdrop}"
            else:
                xbmc.log(f"[MyCinema] TMDb API error for movie {movie_id}: {response.status_code}", xbmc.LOGWARNING)
            
            # Fetch images for clearlogo
            images_url = f'https://api.themoviedb.org/3/movie/{movie_id}/images?api_key={api_key}'
            response = requests.get(images_url, timeout=10)
            if response.status_code == 200:
                images = response.json()
                logos = images.get('logos', [])
                # Prefer Czech or English logo
                for logo in logos:
                    if logo.get('iso_639_1') in ('cs', 'en', None):
                        logo_path = logo.get('file_path')
                        if logo_path:
                            metadata['logo'] = f"https://image.tmdb.org/t/p/w500{logo_path}"
                            break
            
            # Cache the result
            self._cache.set(cache_key, metadata, ttl_seconds=24*3600)
            
        except Exception as e:
            xbmc.log(f"[MyCinema] Error fetching movie metadata: {e}", xbmc.LOGWARNING)
        
        return metadata
    
    # ==================================================================================
    # OVERRIDE: NEW CHANNEL CREATION - Cinema-specific labels
    # ==================================================================================
    
    def _create_new_channel(self):
        """Create a new cinema with automatic naming based on added movies."""
        self._block_sidebar = True
        
        # Create channel with temporary name
        temp_name = f"Nove kino {len(self.channel_manager.channels) + 1}"
        new_channel = self.channel_manager.create_channel(temp_name)
        
        # Store the new channel ID for auto-naming after dialog closes
        self._pending_new_channel_id = new_channel.id
        
        # Select the new channel (first one - new channels are prepended)
        self.current_channel_index = 0
        
        # Only refresh channel list - NO program refresh needed for empty channel
        list_control = self.getControl(2000)
        list_control.reset()
        for ch in self.channel_manager.get_all_channels():
            item = xbmcgui.ListItem(label=ch.name)
            icon = ch.icon if ch.icon else 'special://home/addons/plugin.video.milionar/resources/media/placeholder_movie_card.png'
            item.setArt({'poster': icon})
            item.setProperty('channel_id', ch.id)
            list_control.addItem(item)
        
        # Add "Create New Cinema" item
        create_item = xbmcgui.ListItem(label="Vytvorit nove kino")
        create_item.setArt({'poster': 'special://home/addons/plugin.video.milionar/resources/media/plus_card.png'})
        create_item.setProperty('is_create_button', 'true')
        list_control.addItem(create_item)
        
        # Clear editor grid (empty channel)
        self.getControl(9100).reset()
        
        # Try to move focus  
        self.setFocusId(9100)
        xbmc.sleep(50)
        
        # Unblock sidebar before showing dialog
        self._block_sidebar = False
        
        # Open AddMediaDialog for movies
        self._show_add_series_dialog()  # Uses our override with media_type='cinema'
    
    # ==================================================================================
    # OVERRIDE: PLAY BROADCAST - Play random movie from cinema
    # ==================================================================================
    
    def _play_broadcast(self):
        """Plays all movies in the program list as a continuous playlist."""
        from urllib.parse import quote_plus
        
        list_control = self.getControl(9000)
        size = list_control.size()
        if size == 0:
            self._show_toast("Zadne filmy k prehrani", "warning")
            return
            
        self.close()
        
        # Get Playlist
        playlist = xbmc.PlayList(xbmc.PLAYLIST_VIDEO)
        playlist.clear()
        
        # Get current channel ID for history tracking
        channel_list = self.getControl(2000)
        current_channel_item = channel_list.getSelectedItem()
        channel_id = current_channel_item.getProperty('channel_id') if current_channel_item else ''
        
        # Add all movies to playlist
        for i in range(size):
            item = list_control.getListItem(i)
            
            movie_id = item.getProperty('movie_id')
            movie_name = item.getLabel()
            
            if not movie_id or not movie_name:
                continue

            # Metadata params
            plot = item.getProperty('plot') or ''
            year = item.getProperty('year') or ''
            poster = item.getArt('poster') or ''
            fanart = item.getArt('fanart') or ''
            
            # Construct plugin URL for movie playback
            url = (f"plugin://{self.addon.getAddonInfo('id')}?action=play_movie_from_addon_playlist"
                   f"&movie_name={quote_plus(movie_name)}"
                   f"&tmdb_id={movie_id}"
                   f"&plot={quote_plus(plot)}"
                   f"&poster={quote_plus(poster)}"
                   f"&fanart={quote_plus(fanart)}"
                   f"&year={quote_plus(year)}"
                   f"&mycinema_channel_id={quote_plus(channel_id)}")
            
            # Create list item for playlist
            li = xbmcgui.ListItem(label=movie_name)
            li.setInfo('video', {
                'title': movie_name,
                'plot': plot, 
                'year': int(year) if year.isdigit() else 0,
                'mediatype': 'movie'
            })
            li.setArt({
                'poster': poster,
                'fanart': fanart,
                'thumb': poster
            })
            
            playlist.add(url, li)
            
        # Start playback
        xbmc.Player().play(playlist)
    
    # ==================================================================================
    # OVERRIDE: DELETE CHANNEL - Cinema-specific toast message
    # ==================================================================================
    
    def _confirm_delete_channel(self):
        """Delete the cinema after confirmation (cinema-specific toast)."""
        channel_id = getattr(self, '_pending_delete_channel_id', None)
        if not channel_id:
            return
        
        # Hide confirmation dialog
        self.clearProperty('WCS.MyTV.DeleteConfirm')
        
        # Delete channel and its history
        ChannelHistory.delete_channel_history(channel_id)
        self.channel_manager.delete_channel(channel_id)
        
        # Clear pending data
        self._pending_delete_channel_id = None
        self._pending_delete_channel_name = None
        
        # Refresh
        self.current_channel_index = 0
        self.refresh_channels_view()
        
        # Focus on first channel
        self._delayed_focus(2000, delay=0.1)
        
        self._show_toast("Kino smazano", "success")
    
    def _play_program_item(self):
        """Play selected movie from program list."""
        try:
            program_list = self.getControl(9000)
            item = program_list.getSelectedItem()
            if not item:
                return
            
            movie_id = item.getProperty('movie_id')
            channel_id = item.getProperty('channel_id')
            movie_name = item.getLabel()
            
            if not movie_id:
                return
            
            # Mark as watched (correct arg order: channel_id, movie_id)
            ChannelHistory.mark_movie_watched(channel_id, movie_id)
            
            # Get metadata from item
            year = item.getProperty('year') or ''
            plot = item.getProperty('plot') or ''
            poster = item.getArt('poster') or ''
            fanart = item.getArt('fanart') or ''
            
            # Close dialog first
            self.close()
            
            # Play movie using the standard play function
            from wcs.utils import play_movie_from_addon
            meta = {
                'title': movie_name,
                'year': year,
                'plot': plot,
                'poster': poster,
                'fanart': fanart,
                'tmdb_id': movie_id
            }
            play_movie_from_addon(meta, self.addon)
            
        except Exception as e:
            xbmc.log(f"[MyCinema] Error playing movie: {e}", xbmc.LOGERROR)


def show_my_cinema_dialog(addon, show_nav_sidebar=False, nav_position=0):
    """Factory function to show MyCinema dialog."""
    dialog = MyCinemaDialog(
        "ai/DialogMyTV.xml",
        addon.getAddonInfo('path'),
        "Default",
        "1080i",
        show_nav_sidebar=show_nav_sidebar,
        nav_position=nav_position
    )
    dialog.doModal()
    del dialog

