# wcs/ai/DialogAddMedia.py
"""
DialogAddMedia - Unified dialog for adding media (series or movies) to channels/cinemas.

This module provides:
- AddMediaDialog: Controller for inline add media dialog
- create_add_media_controller: Factory function for creating controllers
"""

import xbmc
import xbmcgui
import xbmcaddon
import threading
import requests
from urllib.parse import quote_plus

from wcs import user_data
from wcs.caching import get_cache_manager
from wcs.metadata.TMDbClient import get_tmdb_api_key
from wcs.ai.AIProvider import AIProvider
from wcs.ai.DialogAIChatRecommendation import AIRecommendationPromptBuilder


class AddMediaDialog:
    """
    Controller for the inline Add Media dialog.
    
    Supports both series (TV) and movies (Cinema) based on media_type parameter.
    """
    
    # TMDb Movie genre ID to Czech name mapping
    MOVIE_GENRE_MAP = {
        28: 'Akce', 12: 'Dobrodružný', 16: 'Animovaný', 35: 'Komedie',
        80: 'Krimi', 99: 'Dokument', 18: 'Drama', 10751: 'Rodinný',
        14: 'Fantasy', 36: 'Historický', 27: 'Horor', 10402: 'Hudební',
        9648: 'Záhadný', 10749: 'Romantický', 878: 'Sci-Fi',
        10770: 'TV Film', 53: 'Thriller', 10752: 'Válečný', 37: 'Western'
    }
    
    # TMDb TV genre ID to Czech name mapping (same as original)
    TV_GENRE_MAP = {
        10759: 'Akce a dobrodružství', 16: 'Animovaný', 35: 'Komedie',
        80: 'Krimi', 99: 'Dokument', 18: 'Drama', 10751: 'Rodinný',
        10762: 'Dětský', 9648: 'Záhadný', 10763: 'Zprávy',
        10764: 'Reality', 10765: 'Sci-Fi a fantasy', 10766: 'Telenovela',
        10767: 'Talk Show', 10768: 'Válečný a politický', 37: 'Western'
    }
    
    def __init__(self, parent_window, addon, channel_manager, channel_id, 
                 on_close_callback=None, media_type='tv'):
        """
        Initialize the Add Media dialog controller.
        
        Args:
            parent_window: Parent dialog instance (MyTVDialog or MyCinemaDialog)
            addon: xbmcaddon.Addon instance
            channel_manager: MediaChannelManager instance
            channel_id: ID of the channel to add media to
            on_close_callback: Optional callback function called when dialog closes
            media_type: 'tv' for series, 'cinema' for movies
        """
        self.parent = parent_window
        self.addon = addon
        self.channel_manager = channel_manager
        self.channel_id = channel_id
        self._on_close_callback = on_close_callback
        self.media_type = media_type
        
        # Get channel reference
        self.channel = None
        if self.channel_manager and self.channel_id:
            self.channel = self.channel_manager.get_channel_by_id(self.channel_id)
        
        # Internal state
        self._items = []
        self._cache = get_cache_manager()
        self._media_added = False
        self._is_active = False
        
        # Set genre map based on type
        self.GENRE_MAP = self.MOVIE_GENRE_MAP if media_type == 'cinema' else self.TV_GENRE_MAP
    
    def show(self):
        """Show the inline Add Media dialog."""
        self._is_active = True
        self._media_added = False
        
        # Set descriptions based on media type
        if self.media_type == 'cinema':
            desc = 'Vyberte filmy z vaší uložené knihovny a přidejte je do kina.'
        else:
            desc = 'Vyberte seriály z vaší uložené knihovny a přidejte je do kanálu.'
        
        self.parent.setProperty('WCS.MyTV.AddDialog.Active', 'true')
        self.parent.setProperty('WCS.MyTV.AddDialog.Description', desc)
        self.parent.clearProperty('WCS.MyTV.AddDialog.ListingMode')
        self.parent.clearProperty('WCS.MyTV.AddDialog.ListingTitle')
        
        for attempt in range(5):
            xbmc.sleep(100)
            self.parent.setFocusId(9201)
            xbmc.sleep(50)
            if self.parent.getFocusId() == 9201:
                break
    
    def hide(self):
        """Hide the inline Add Media dialog."""
        self._is_active = False
        self.parent.clearProperty('WCS.MyTV.AddDialog.Active')
        self.parent.clearProperty('WCS.MyTV.AddDialog.ListingMode')
        self.parent.clearProperty('WCS.MyTV.AddDialog.ListingTitle')
        self.parent.clearProperty('WCS.MyTV.AddDialog.Description')
        self.parent.clearProperty('WCS.MyTV.AddDialog.ActionsVisible')
        
        self._clear_ai_loading_properties()
        
        if self._on_close_callback:
            try:
                self._on_close_callback()
            except Exception as e:
                xbmc.log(f"[AddMediaDialog] Error in on_close callback: {e}", xbmc.LOGERROR)
        
        self.parent.setFocusId(9100)
    
    def is_active(self):
        """Return True if the dialog is currently active."""
        return self._is_active
    
    def was_media_added(self):
        """Return True if any media was added during this dialog session."""
        return self._media_added
    
    # Legacy method for backward compatibility
    def was_series_added(self):
        """Return True if any media was added (legacy alias)."""
        return self._media_added
    
    def onAction(self, action):
        """Handle user input actions. Returns True if handled."""
        if not self._is_active:
            return False
        
        action_id = action.getId()
        
        if action_id in [10, 92]:  # ACTION_PREVIOUS_MENU, ACTION_NAV_BACK
            if self.parent.getProperty('WCS.MyTV.AddDialog.ActionsVisible'):
                self._hide_action_buttons()
                return True
            elif self.parent.getProperty('WCS.MyTV.AddDialog.ListingMode'):
                self.parent.clearProperty('WCS.MyTV.AddDialog.ListingMode')
                self.parent.clearProperty('WCS.MyTV.AddDialog.ListingTitle')
                self.parent.setFocusId(9201)
            else:
                self.hide()
            return True
        
        return False
    
    def onClick(self, controlId):
        """Handle click events. Returns True if handled."""
        if not self._is_active:
            return False
        
        if controlId == 9200:
            self.hide()
            return True
        elif controlId == 9201:
            self._show_media_listing('my_library')
            return True
        elif controlId == 9202:
            self._show_media_listing('search')
            return True
        elif controlId == 9203:
            self._show_media_listing('tmdb_recommendations')
            return True
        elif controlId == 9204:
            self._show_media_listing('ai_recommendations')
            return True
        elif controlId == 9211:
            self._show_action_buttons()
            return True
        elif controlId == 9220:
            self._execute_selected_action()
            return True
        
        return False
    
    def onFocus(self, controlId):
        """Handle focus changes to update descriptions."""
        if not self._is_active:
            return
        
        if self.media_type == 'cinema':
            descriptions = {
                9201: 'Vyberte filmy z vaší uložené knihovny a přidejte je do kina.',
                9202: 'Vyhledejte film podle názvu na TMDb.',
                9203: 'Získejte doporučení na základě filmů v kině.',
                9204: 'Nechte AI navrhnout filmy podle vašich preferencí.',
            }
        else:
            descriptions = {
                9201: 'Vyberte seriály z vaší uložené knihovny a přidejte je do kanálu.',
                9202: 'Vyhledejte seriál podle názvu na TMDb.',
                9203: 'Získejte doporučení na základě seriálů v kanálu.',
                9204: 'Nechte AI navrhnout seriály podle vašich preferencí.',
            }
        
        if controlId in descriptions:
            self.parent.setProperty('WCS.MyTV.AddDialog.Description', descriptions[controlId])
    
    def _show_media_listing(self, source):
        """Show media listing for the given source."""
        items = []
        title = ""
        
        if source == 'my_library':
            if self.media_type == 'cinema':
                title = "Z mojí knihovny"
                my_items = user_data.load_tmdb_movies(self.addon)
                if not my_items:
                    self.parent._show_toast("Žádné uložené filmy", "warning")
                    return
            else:
                title = "Z mojí knihovny"
                my_items = user_data.load_tmdb_series(self.addon)
                if not my_items:
                    self.parent._show_toast("Žádné uložené seriály", "warning")
                    return
            
            self.parent.setProperty('WCS.MyTV.AddDialog.ListingMode', source)
            self.parent.setProperty('WCS.MyTV.AddDialog.ListingTitle', title)
            self._items = my_items
            
            threading.Thread(target=self._enrich_library_items, args=(my_items,), daemon=True).start()
            return
        
        elif source == 'search':
            if self.media_type == 'cinema':
                title = "Vyhledávání na TMDb"
                search_query = xbmcgui.Dialog().input("Hledat film", type=xbmcgui.INPUT_ALPHANUM)
                if not search_query:
                    return
                try:
                    url = f'https://api.themoviedb.org/3/search/movie?api_key={get_tmdb_api_key()}&language=cs-CZ&query={quote_plus(search_query)}'
                    response = requests.get(url, timeout=10)
                    items = response.json().get('results', [])
                except Exception as e:
                    xbmc.log(f"[AddMediaDialog] Search error: {e}", xbmc.LOGERROR)
                    return
            else:
                title = "Vyhledávání na TMDb"
                search_query = xbmcgui.Dialog().input("Hledat serial", type=xbmcgui.INPUT_ALPHANUM)
                if not search_query:
                    return
                try:
                    url = f'https://api.themoviedb.org/3/search/tv?api_key={get_tmdb_api_key()}&language=cs-CZ&query={quote_plus(search_query)}'
                    response = requests.get(url, timeout=10)
                    items = response.json().get('results', [])
                except Exception as e:
                    xbmc.log(f"[AddMediaDialog] Search error: {e}", xbmc.LOGERROR)
                    return
            
            if not items:
                self.parent._show_toast("Nic nenalezeno", "warning")
                return
        
        elif source == 'tmdb_recommendations':
            if self.media_type == 'cinema':
                title = "Doporučení z TMDb"
                if not self.channel or not self.channel.media_list:
                    self.parent._show_toast("Kino nemá žádné filmy", "warning")
                    return
                
                all_recs = []
                seen_ids = set()
                current_ids = {str(m.get('id')) for m in self.channel.media_list}
                
                for movie in self.channel.media_list[:3]:
                    movie_id = movie.get('id')
                    try:
                        url = f'https://api.themoviedb.org/3/movie/{movie_id}/recommendations?api_key={get_tmdb_api_key()}&language=cs-CZ'
                        response = requests.get(url, timeout=10)
                        recs = response.json().get('results', [])
                        for rec in recs:
                            rec_id = str(rec.get('id'))
                            if rec_id not in seen_ids and rec_id not in current_ids:
                                seen_ids.add(rec_id)
                                # Add name field for consistency
                                rec['name'] = rec.get('title', '')
                                all_recs.append(rec)
                    except Exception as e:
                        xbmc.log(f"[AddMediaDialog] TMDb recommendations error: {e}", xbmc.LOGERROR)
                
                if not all_recs:
                    self.parent._show_toast("Zadna doporuceni", "info")
                    return
                items = all_recs[:20]
            else:
                # Use original logic for TV
                title = "Doporučení z TMDb"
                if not self.channel or not self.channel.media_list:
                    self.parent._show_toast("Kanál nemá žádné seriály", "warning")
                    return
                
                all_recs = []
                seen_ids = set()
                current_ids = {str(s.get('id')) for s in self.channel.media_list}
                
                for series in self.channel.media_list[:3]:
                    series_id = series.get('id')
                    try:
                        url = f'https://api.themoviedb.org/3/tv/{series_id}/recommendations?api_key={get_tmdb_api_key()}&language=cs-CZ'
                        response = requests.get(url, timeout=10)
                        recs = response.json().get('results', [])
                        for rec in recs:
                            rec_id = str(rec.get('id'))
                            if rec_id not in seen_ids and rec_id not in current_ids:
                                seen_ids.add(rec_id)
                                all_recs.append(rec)
                    except Exception as e:
                        xbmc.log(f"[AddMediaDialog] TMDb recommendations error: {e}", xbmc.LOGERROR)
                
                if not all_recs:
                    self.parent._show_toast("Zadna doporuceni", "info")
                    return
                items = all_recs[:20]
        
        elif source == 'ai_recommendations':
            if self.media_type == 'cinema':
                title = "Doporučení od AI"
                if not self.channel or not self.channel.media_list:
                    self.parent._show_toast("Kino nemá žádné filmy pro kontext", "warning")
                    return
            else:
                title = "Doporučení od AI"
                if not self.channel or not self.channel.media_list:
                    self.parent._show_toast("Kanál nemá žádné seriály pro kontext", "warning")
                    return
            
            self.parent.setProperty('WCS.MyTV.AddDialog.ListingMode', source)
            self.parent.setProperty('WCS.MyTV.AddDialog.ListingTitle', "Načítám AI doporučení...")
            
            threading.Thread(target=self._fetch_ai_recommendations, daemon=True).start()
            return
        
        if not items:
            return
        
        self._items = items
        self.parent.setProperty('WCS.MyTV.AddDialog.ListingMode', source)
        self.parent.setProperty('WCS.MyTV.AddDialog.ListingTitle', title)
        self._populate_list(items)
        self.parent.setFocusId(9211)
    
    def _enrich_library_items(self, items):
        """Enrich library items with TMDb metadata (async worker)."""
        list_control = self.parent.getControl(9211)
        list_control.reset()
        
        current_ids = self._get_current_channel_ids()
        enriched = []
        
        api_type = 'movie' if self.media_type == 'cinema' else 'tv'
        
        for item in items:
            tmdb_id = item.get('id')
            if not tmdb_id:
                enriched.append(item)
                self._add_item_to_list(list_control, item, current_ids)
                continue
            
            cache_key = f"{api_type}_detail_{tmdb_id}"
            cached = self._cache.get(cache_key)
            
            if cached:
                enriched.append(cached)
                self._add_item_to_list(list_control, cached, current_ids)
            else:
                try:
                    url = f'https://api.themoviedb.org/3/{api_type}/{tmdb_id}?api_key={get_tmdb_api_key()}&language=cs-CZ'
                    response = requests.get(url, timeout=5)
                    if response.status_code == 200:
                        full_data = response.json()
                        # Add name for movies
                        if api_type == 'movie' and 'title' in full_data:
                            full_data['name'] = full_data['title']
                        self._cache.set(cache_key, full_data, ttl_seconds=7*24*3600)
                        enriched.append(full_data)
                        self._add_item_to_list(list_control, full_data, current_ids)
                    else:
                        enriched.append(item)
                        self._add_item_to_list(list_control, item, current_ids)
                except Exception as e:
                    xbmc.log(f"[AddMediaDialog] TMDb fetch error: {e}", xbmc.LOGWARNING)
                    enriched.append(item)
                    self._add_item_to_list(list_control, item, current_ids)
        
        self._items = enriched
        self._cache.flush()
        
        if list_control.size() > 0:
            self.parent.setFocusId(9211)
    
    def _fetch_ai_recommendations(self):
        """Fetch AI recommendations (async worker)."""
        import time
        import random
        import json
        
        start_time = time.time()
        stop_animation = threading.Event()
        
        glitch_chars = list("0123456789ABCDEF@#$%&*!?<>[]{}|/\\~`^")
        
        if self.media_type == 'cinema':
            fun_messages = [
                "Hledám v archivech kina",
                "Konzultuji s filmovou akademií",
                "Analyzuji žánry a režiséry",
                "Procházím databáze TMDb",
                "Hledám skryté perly",
            ]
        else:
            fun_messages = [
                "Hledám v multivesmíru seriálů",
                "Konzultuji s Netflixem",
                "Analyzuji žánry a tropy",
                "Procházím databáze TMDb",
                "Hledám skryté perly",
            ]
        
        try:
            ai_provider = AIProvider()
            provider_name = ai_provider.get_current_provider() or "AI"
            model_name = ai_provider.get_current_model() or "Default"
        except:
            provider_name = "AI"
            model_name = "Default"
        
        self.parent.setProperty('WCS.MyTV.AddDialog.AILoading', 'true')
        self.parent.setProperty('WCS.MyTV.AddDialog.Provider', provider_name)
        self.parent.setProperty('WCS.MyTV.AddDialog.Model', model_name)
        self.parent.setProperty('WCS.MyTV.AddDialog.AIStatus', 'Připravuji doporučení...')
        self.parent.setProperty('WCS.MyTV.AddDialog.Timer', '0.0s')
        self.parent.setProperty('WCS.MyTV.AddDialog.FunStatus', random.choice(fun_messages))
        
        try:
            self.parent.setFocusId(9250)
        except:
            pass
        
        def animation_worker():
            fun_idx = 0
            tick = 0
            while not stop_animation.is_set():
                try:
                    elapsed = time.time() - start_time
                    self.parent.setProperty('WCS.MyTV.AddDialog.Timer', f'{elapsed:.1f}s')
                    
                    glitch_text = ''.join(random.choices(glitch_chars, k=20))
                    self.parent.setProperty('WCS.MyTV.AddDialog.GlitchText', glitch_text)
                    
                    tick += 1
                    if tick % 20 == 0:
                        fun_idx = (fun_idx + 1) % len(fun_messages)
                        self.parent.setProperty('WCS.MyTV.AddDialog.FunStatus', fun_messages[fun_idx])
                    
                    time.sleep(0.1)
                except:
                    break
        
        anim_thread = threading.Thread(target=animation_worker, daemon=True)
        anim_thread.start()
        
        try:
            self.parent.setProperty('WCS.MyTV.AddDialog.AIStatus', 'Odesílám dotaz na AI...')
            
            media_items = list(self.channel.media_list)
            
            if self.media_type == 'cinema':
                context = {'type': 'my_movies', 'data': media_items}
                prompt_builder = AIRecommendationPromptBuilder('movies', context)
                media_names = [m.get('name') or m.get('title', '') for m in media_items if m.get('name') or m.get('title')]
                user_msg = f"Na základě těchto filmů doporuč další: {', '.join(media_names[:10])}"
            else:
                context = {'type': 'my_series', 'data': media_items}
                prompt_builder = AIRecommendationPromptBuilder('series', context)
                media_names = [s.get('name', '') for s in media_items if s.get('name')]
                user_msg = f"Na základě těchto seriálů doporuč další: {', '.join(media_names[:10])}"
            
            system_prompt = prompt_builder.build_system_prompt()
            
            self.parent.setProperty('WCS.MyTV.AddDialog.AIStatus', 'AI přemýšlí...')
            
            response, usage = ai_provider.send_prompt(f"{system_prompt}\n\nUser: {user_msg}")
            
            if usage:
                try:
                    from wcs.ai.UsageTracker import track_ai_usage
                    usage_type = "mycinema_recommendation" if self.media_type == 'cinema' else "mytv_recommendation"
                    track_ai_usage(provider_name, model_name, usage, usage_type)
                except:
                    pass
            
            if not response:
                stop_animation.set()
                self._clear_ai_loading_properties()
                self.parent._show_toast("AI nevrátila odpověď", "warning")
                return
            
            self.parent.setProperty('WCS.MyTV.AddDialog.AIStatus', 'Zpracovávám odpověď...')
            
            try:
                data = json.loads(response)
                recommendations = data.get('recommendations', [])
            except json.JSONDecodeError:
                stop_animation.set()
                self._clear_ai_loading_properties()
                self.parent._show_toast("AI odpověď není validní JSON", "error")
                return
            
            if not recommendations:
                stop_animation.set()
                self._clear_ai_loading_properties()
                media_name = "filmy" if self.media_type == 'cinema' else "seriály"
                self.parent._show_toast(f"AI nedoporučila žádné {media_name}", "warning")
                return
            
            self.parent.setProperty('WCS.MyTV.AddDialog.AIStatus', 'Vyhledávám na TMDb...')
            
            current_ids = self._get_current_channel_ids()
            tmdb_items = []
            
            for i, rec in enumerate(recommendations):
                rec_title = rec.get('title') or rec.get('original_title')
                rec_year = rec.get('year')
                
                self.parent.setProperty('WCS.MyTV.AddDialog.AIStatus', 
                    f'TMDb: {i+1}/{len(recommendations)} - {rec_title or "..."}')
                
                tmdb_data = self._search_tmdb(rec_title, rec_year)
                if tmdb_data:
                    item_id = str(tmdb_data.get('id'))
                    if item_id not in current_ids:
                        tmdb_items.append(tmdb_data)
            
            stop_animation.set()
            
            if not tmdb_items:
                self._clear_ai_loading_properties()
                media_name = "filmy" if self.media_type == 'cinema' else "serialy"
                self.parent._show_toast(f"Nenalezeny {media_name} na TMDb", "warning")
                return
            
            self._clear_ai_loading_properties()
            
            self._items = tmdb_items
            title = "Doporučení od AI"
            self.parent.setProperty('WCS.MyTV.AddDialog.ListingTitle', title)
            self._populate_list(tmdb_items)
            self.parent.setFocusId(9211)
            
        except Exception as e:
            stop_animation.set()
            self._clear_ai_loading_properties()
            xbmc.log(f"[AddMediaDialog] AI recommendations error: {e}", xbmc.LOGERROR)
            self.parent._show_toast("Chyba AI doporuceni", "error")
    
    def _search_tmdb(self, title, year=None):
        """Search TMDb for media by title and optional year."""
        if not title:
            return None
        try:
            if self.media_type == 'cinema':
                url = f'https://api.themoviedb.org/3/search/movie?api_key={get_tmdb_api_key()}&language=cs-CZ&query={quote_plus(title)}'
                if year:
                    url += f'&year={year}'
            else:
                url = f'https://api.themoviedb.org/3/search/tv?api_key={get_tmdb_api_key()}&language=cs-CZ&query={quote_plus(title)}'
                if year:
                    url += f'&first_air_date_year={year}'
            response = requests.get(url, timeout=5)
            results = response.json().get('results', [])
            if results:
                result = results[0]
                # Add name for movies
                if self.media_type == 'cinema' and 'title' in result:
                    result['name'] = result['title']
                return result
            return None
        except Exception as e:
            xbmc.log(f"[AddMediaDialog] TMDb search error: {e}", xbmc.LOGWARNING)
            return None
    
    def _clear_ai_loading_properties(self):
        """Clear all AI loading related properties."""
        self.parent.clearProperty('WCS.MyTV.AddDialog.AILoading')
        self.parent.clearProperty('WCS.MyTV.AddDialog.AIStatus')
        self.parent.clearProperty('WCS.MyTV.AddDialog.Timer')
        self.parent.clearProperty('WCS.MyTV.AddDialog.GlitchText')
        self.parent.clearProperty('WCS.MyTV.AddDialog.FunStatus')
        self.parent.clearProperty('WCS.MyTV.AddDialog.Provider')
        self.parent.clearProperty('WCS.MyTV.AddDialog.Model')
    
    def _populate_list(self, items):
        """Populate the media listing control."""
        try:
            list_control = self.parent.getControl(9211)
            list_control.reset()
            
            current_ids = self._get_current_channel_ids()
            
            for item_data in items:
                self._add_item_to_list(list_control, item_data, current_ids)
                
        except Exception as e:
            xbmc.log(f"[AddMediaDialog] Error populating list: {e}", xbmc.LOGERROR)
    
    def _add_item_to_list(self, list_control, item_data, current_ids):
        """Add a single item to the list control."""
        try:
            name = item_data.get('name') or item_data.get('title', '')
            item = xbmcgui.ListItem(label=name)
            
            poster = item_data.get('poster_path') or item_data.get('poster', '')
            if poster and not poster.startswith('http'):
                poster = f"https://image.tmdb.org/t/p/w500{poster}"
            
            fanart = item_data.get('backdrop_path') or item_data.get('fanart', '')
            if fanart and not fanart.startswith('http'):
                fanart = f"https://image.tmdb.org/t/p/w1280{fanart}"
            
            placeholder = 'special://home/addons/plugin.video.milionar/resources/media/placeholder_movie_card.png' if self.media_type == 'cinema' else 'special://home/addons/plugin.video.milionar/resources/media/placeholder_tv_card.png'
            
            item.setArt({
                'poster': poster or placeholder,
                'fanart': fanart or 'special://home/addons/plugin.video.milionar/resources/media/fanart_fallback.jpg'
            })
            
            item.setProperty('tmdb_id', str(item_data.get('id', '')))
            
            # Year handling for movies vs TV
            if self.media_type == 'cinema':
                year_val = item_data.get('release_date', '') or item_data.get('year', '')
            else:
                year_val = item_data.get('first_air_date', '') or item_data.get('year', '')
            item.setProperty('year', str(year_val)[:4] if year_val else '')
            
            rating_val = item_data.get('vote_average') or item_data.get('rating') or 0
            item.setProperty('rating', str(round(float(rating_val), 1)) if rating_val else '0')
            
            plot_val = item_data.get('overview', '') or item_data.get('plot', '')
            item.setProperty('plot', plot_val)
            
            genres = item_data.get('genre_ids', [])
            if genres:
                genre_names = self._map_genre_ids(genres)
            else:
                genre_names = item_data.get('genre', '') or item_data.get('genres', '')
                if isinstance(genre_names, list):
                    genre_names = ', '.join([g.get('name', '') for g in genre_names if isinstance(g, dict)])
            item.setProperty('genre', genre_names if genre_names else '')
            
            if str(item_data.get('id')) in current_ids:
                item.setProperty('is_added', 'true')
            
            list_control.addItem(item)
        except Exception as e:
            xbmc.log(f"[AddMediaDialog] Error adding item: {e}", xbmc.LOGERROR)
    
    def _map_genre_ids(self, genre_ids):
        """Map TMDb genre IDs to names."""
        names = [self.GENRE_MAP.get(gid, '') for gid in genre_ids[:2] if gid in self.GENRE_MAP]
        return ', '.join(names) if names else ''
    
    def _get_current_channel_ids(self):
        """Get set of media IDs currently in the channel."""
        if self.channel and self.channel.media_list:
            return {str(m.get('id')) for m in self.channel.media_list}
        return set()
    
    def _show_action_buttons(self):
        """Show action buttons for the currently selected media."""
        try:
            list_control = self.parent.getControl(9211)
            selected_pos = list_control.getSelectedPosition()
            
            if selected_pos < 0 or not self._items:
                return
            
            self._selected_item = self._items[selected_pos]
            self._selected_pos = selected_pos
            
            action_list = self.parent.getControl(9220)
            action_list.reset()
            
            if self.media_type == 'cinema':
                actions = [
                    ("Přidat do kina", "add_to_channel"),
                    ("Moje filmy", "add_to_my_library"),
                    ("Podobné", "find_similar"),
                ]
            else:
                actions = [
                    ("Můj kanál", "add_to_channel"),
                    ("Moje seriály", "add_to_my_library"),
                    ("Podobné", "find_similar"),
                    ("Hrát hru", "play_game"),
                ]
            
            for label, action_id in actions:
                item = xbmcgui.ListItem(label=label)
                item.setProperty('action_id', action_id)
                action_list.addItem(item)
            
            self.parent.setProperty('WCS.MyTV.AddDialog.ActionsVisible', 'true')
            self.parent.setFocusId(9220)
            
        except Exception as e:
            xbmc.log(f"[AddMediaDialog] Error showing action buttons: {e}", xbmc.LOGERROR)
    
    def _hide_action_buttons(self):
        """Hide action buttons and return focus to media list."""
        self.parent.clearProperty('WCS.MyTV.AddDialog.ActionsVisible')
        self.parent.setFocusId(9211)
    
    def _execute_selected_action(self):
        """Execute the selected action from the action buttons list."""
        try:
            action_list = self.parent.getControl(9220)
            selected_pos = action_list.getSelectedPosition()
            
            if selected_pos < 0:
                return
            
            selected_item = action_list.getListItem(selected_pos)
            action_id = selected_item.getProperty('action_id')
            
            self._hide_action_buttons()
            
            if action_id == 'add_to_channel':
                self._action_add_to_channel()
            elif action_id == 'add_to_my_library':
                self._action_add_to_my_library()
            elif action_id == 'find_similar':
                self._action_find_similar()
            elif action_id == 'play_game':
                self._action_play_game()
                
        except Exception as e:
            xbmc.log(f"[AddMediaDialog] Error executing action: {e}", xbmc.LOGERROR)
    
    def _action_add_to_channel(self):
        """Add the selected media to the channel/cinema."""
        if not hasattr(self, '_selected_item') or not self._selected_item:
            return
        
        selected_item = self._selected_item.copy()  # Make a copy to modify
        media_id = str(selected_item.get('id'))
        
        current_ids = self._get_current_channel_ids()
        if media_id in current_ids:
            media_name = "Film" if self.media_type == 'cinema' else "Seriál"
            self.parent._show_toast(f"{media_name} už je v kanálu", "info")
            return
        
        # For movies, fetch tagline and runtime from TMDb details API
        if self.media_type == 'cinema':
            selected_item = self._enrich_movie_data(selected_item)
        
        self.channel_manager.toggle_media_in_channel(self.channel_id, selected_item)
        
        try:
            list_control = self.parent.getControl(9211)
            list_item = list_control.getListItem(self._selected_pos)
            list_item.setProperty('is_added', 'true')
        except:
            pass
        
        self.channel = self.channel_manager.get_channel_by_id(self.channel_id)
        self._media_added = True
        
        name = selected_item.get('name') or selected_item.get('title', '')
        self.parent._show_toast(f"'{name}' přidáno", "success")
    def _enrich_movie_data(self, movie_data):
        """Fetch additional movie data (tagline, runtime) from TMDb details API."""
        import requests
        from wcs.metadata.TMDbClient import get_tmdb_api_key
        
        movie_id = movie_data.get('id')
        if not movie_id:
            return movie_data
        
        try:
            api_key = get_tmdb_api_key(self.addon)
            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()
                
                # Add tagline if available
                if details.get('tagline'):
                    movie_data['tagline'] = details['tagline']
                
                # Add runtime if available
                if details.get('runtime'):
                    movie_data['runtime'] = details['runtime']
                
                # Update overview if we got a better one
                if details.get('overview') and not movie_data.get('overview'):
                    movie_data['overview'] = details['overview']
                    
        except Exception as e:
            import xbmc
            xbmc.log(f"[AddMediaDialog] Error enriching movie data: {e}", xbmc.LOGWARNING)
        
        return movie_data
    
    def _action_add_to_my_library(self):
        """Add the selected media to user's library."""
        if not hasattr(self, '_selected_item') or not self._selected_item:
            return
        
        selected_item = self._selected_item
        
        if self.media_type == 'cinema':
            media_data = {
                'id': selected_item.get('id'),
                'name': selected_item.get('name') or selected_item.get('title', ''),
                'title': selected_item.get('title', ''),
                'poster_path': selected_item.get('poster_path'),
                'backdrop_path': selected_item.get('backdrop_path'),
                'release_date': selected_item.get('release_date', ''),
                'overview': selected_item.get('overview', ''),
                'vote_average': selected_item.get('vote_average', 0),
            }
            
            existing = user_data.load_tmdb_movies(self.addon) or []
            
            if any(str(m.get('id')) == str(media_data['id']) for m in existing):
                self.parent._show_toast("Film uz je v knihovne", "info")
                return
            
            existing.insert(0, media_data)
            user_data.store_tmdb_movies(self.addon, existing)
            self.parent._show_toast(f"'{media_data['name']}' pridano do Moje filmy", "success")
        else:
            media_data = {
                'id': selected_item.get('id'),
                'name': selected_item.get('name'),
                'poster_path': selected_item.get('poster_path'),
                'backdrop_path': selected_item.get('backdrop_path'),
                'first_air_date': selected_item.get('first_air_date', ''),
                'overview': selected_item.get('overview', ''),
                'vote_average': selected_item.get('vote_average', 0),
            }
            
            existing = user_data.load_tmdb_series(self.addon) or []
            
            if any(str(s.get('id')) == str(media_data['id']) for s in existing):
                self.parent._show_toast("Serial uz je v knihovne", "info")
                return
            
            existing.insert(0, media_data)
            user_data.store_tmdb_series(self.addon, existing)
            self.parent._show_toast(f"'{media_data['name']}' pridano do Moje serialy", "success")
    
    def _action_find_similar(self):
        """Find similar media on TMDb."""
        if not hasattr(self, '_selected_item') or not self._selected_item:
            return
        
        media_id = self._selected_item.get('id')
        if not media_id:
            return
        
        try:
            if self.media_type == 'cinema':
                url = f'https://api.themoviedb.org/3/movie/{media_id}/similar?api_key={get_tmdb_api_key()}&language=cs-CZ'
            else:
                url = f'https://api.themoviedb.org/3/tv/{media_id}/similar?api_key={get_tmdb_api_key()}&language=cs-CZ'
            
            response = requests.get(url, timeout=10)
            similar = response.json().get('results', [])
            
            if not similar:
                self.parent._show_toast("Zadne podobne nenalezeno", "info")
                return
            
            # Add name for movies
            if self.media_type == 'cinema':
                for item in similar:
                    if 'title' in item:
                        item['name'] = item['title']
            
            current_ids = self._get_current_channel_ids()
            filtered = [s for s in similar if str(s.get('id')) not in current_ids]
            
            if not filtered:
                self.parent._show_toast("Vsechny podobne uz mate", "info")
                return
            
            self._items = filtered[:15]
            self.parent.setProperty('WCS.MyTV.AddDialog.ListingTitle', "Podobne")
            self._populate_list(self._items)
            
        except Exception as e:
            xbmc.log(f"[AddMediaDialog] Find similar error: {e}", xbmc.LOGERROR)
            self.parent._show_toast("Chyba pri hledani podobnych", "error")
    
    def _action_play_game(self):
        """Launch Millionaire game for the selected series (TV only)."""
        if self.media_type == 'cinema':
            return  # Not available for movies
        
        if not hasattr(self, '_selected_item') or not self._selected_item:
            return
        
        series_id = self._selected_item.get('id')
        series_name = self._selected_item.get('name', '')
        
        if not series_id:
            return
        
        # Close dialog and launch game
        self.hide()
        self.parent.close()
        
        from wcs.router import navigate_to
        navigate_to(f'milionar_serial/{series_id}/{quote_plus(series_name)}')


# Factory function for creating controllers
def create_add_media_controller(parent_window, addon, channel_manager, channel_id, 
                                 on_close_callback=None, media_type='tv'):
    """
    Factory function for creating AddMediaDialog controller.
    
    Args:
        parent_window: Parent dialog instance
        addon: xbmcaddon.Addon instance
        channel_manager: MediaChannelManager instance
        channel_id: ID of the channel to add media to
        on_close_callback: Optional callback function called when dialog closes
        media_type: 'tv' for series, 'cinema' for movies
    
    Returns:
        AddMediaDialog instance
    """
    return AddMediaDialog(parent_window, addon, channel_manager, channel_id, 
                          on_close_callback, media_type)
