import xbmc
import xbmcgui
import xbmcaddon
import xbmcplugin
import json
import threading
import requests
from wcs.ai import AIHandler as ai_handler
from wcs.metadata.TMDbClient import get_tmdb_api_key
from wcs import utils
from wcs.ui import UI
from wcs.webshare import WebshareClient as webshare_api

class AIChatRecommendationDialog(xbmcgui.WindowXMLDialog):
    def __init__(self, xml_filename, addon_path, *args, **kwargs):
        super(AIChatRecommendationDialog, self).__init__(xml_filename, addon_path)
        self.addon = xbmcaddon.Addon()
        self.history = [] # List of {"role": "...", "content": "..."}
        self.media_type = None # "movie" or "series"
        self.tmdb_results = []
        self._thinking_stop = threading.Event()
        self._thinking_thread = None
        self._dot_count = 0
        self.context = kwargs.get('context', None)
        
    def onInit(self):
        # Pokud máme kontext, přeskočíme úvodní výběr
        if self.context:
            self.media_type = self.context.get('media_type', 'movie')
            
            # Zobrazit uživatelskou "tichou" zprávu nebo uvítání
            welcome_msg = "Analyzuji váš výběr..."
            self.append_chat_message("AI", welcome_msg)
            
            # Simulovat první zprávu uživatele (která se odešle AI)
            initial_user_msg = self.context.get('initial_message')
            
            if not initial_user_msg:
                c_type = self.context.get('type')
                c_val = self.context.get('value')
                if self.media_type == "movie":
                    media_label = "filmy"
                elif self.media_type == "collection":
                    media_label = "filmové kolekce"
                else:
                    media_label = "seriály"
                
                if c_type == 'genre':
                    initial_user_msg = f"Doporuč mi nejlepší {media_label} v žánru {c_val}."
                elif c_type == 'person':
                    p_type = self.context.get('person_type', 'osoba') # actor/director...
                    role_map = {'actor': 'kde hraje', 'director': 'od režiséra', 'writer': 'od scenáristy'}
                    role_str = role_map.get(p_type, 'od')
                    initial_user_msg = f"Doporuč mi {media_label} {role_str} {c_val}."
                elif c_type in ['favorite_actors', 'favorite_directors', 'favorite_writers']:
                    what_map = {'favorite_actors': 'oblíbených herců', 'favorite_directors': 'oblíbených režisérů', 'favorite_writers': 'oblíbených scenáristů'}
                    what = what_map.get(c_type, 'oblíbených osobností')
                    initial_user_msg = f"Doporuč mi {media_label} na základě mých {what}."
                elif c_type == 'country':
                    initial_user_msg = f"Doporuč mi {media_label} ze země {c_val}."
                elif c_type == 'year':
                    initial_user_msg = f"Doporuč mi {media_label} z roku {c_val}."
                elif c_type == 'my_mixed_collection':
                    initial_user_msg = "Doporuč mi filmy nebo seriály podle mé celé sbírky."
                elif c_type == 'my_collections':
                    initial_user_msg = "Doporuč mi filmové kolekce a ságy, které by se mi mohly líbit podle mých uložených kolekcí."
                elif c_type == 'collection':
                    initial_user_msg = f"Doporuč mi {media_label} z kolekce {c_val}."
                elif c_type == 'category':
                    initial_user_msg = f"Doporuč mi {media_label} z kategorie {c_val}."
                elif c_type == 'section_root':
                    # Uživatel klikl na "Poradit se s AI" přímo v sekci Filmy nebo Seriály
                    # Chceme přeskočit výběr typu média (už je v media_type), ale jinak začít "od nuly"
                    # Initial message simulates generic request for this media type
                    sing_label = "film" if self.media_type == "movie" else "seriál"
                    initial_user_msg = f"Ahoj, hledám nějaký {sing_label}."
                else:
                    initial_user_msg = f"Doporuč mi {media_label} na základě aktuálního výběru."

            self.history.append({"role": "user", "content": initial_user_msg})
            
            # IHNED start AI conversation
            self._start_ai_conversation(is_initial_context=True)
            return

        # Standardní flow bez kontextu
        # Initial Welcome Message
        welcome_msg = "Co chcete doporučit?"
        self.append_chat_message("AI", welcome_msg)
        
        # Initial Buttons - CHOOSE TYPE FIRST
        self.update_buttons([
            {"label": "Filmy", "value": "set_mode:movie"},
            {"label": "Seriály", "value": "set_mode:series"}
        ])
        
        # Clear recommendations
        self.getControl(2000).reset()
        
        # Ensure Input is hidden initially
        self.clearProperty('WCS.AIChat.ShowInput')
        
        # Set focus on buttons list, NOT input field
        self.setFocusId(4000)

    def append_chat_message(self, sender, text):
        """Append message to chat history textbox."""
        history_control = self.getControl(1000)
        current_text = history_control.getText()
        
        # Format: Sender: Message
        # Using colors
        if sender == "AI":
            line = f"[COLOR blue]AI:[/COLOR] {text}\n"
        else:
            line = f"[COLOR orange]Ty:[/COLOR] {text}\n"
            
        new_text = current_text + line
        history_control.setText(new_text)
        
        # Auto-scroll not easily possible on TextBox without tricky calculations or ensuring 'pagecontrol' works.
        # But we set pagecontrol to scrollbar in XML, so user can scroll.\n        
    def update_buttons(self, buttons):
        """Update dynamic buttons list."""
        # buttons: list of dicts {"label": str, "value": str}
        list_control = self.getControl(4000)
        list_control.reset()
        
        for btn in buttons:
            item = xbmcgui.ListItem(label=btn['label'])
            item.setProperty('value', btn['value'])
            list_control.addItem(item)
            
    def onClick(self, controlId):
        # Action Buttons (Dynamic)
        if controlId == 4000:
            list_control = self.getControl(4000)
            item = list_control.getSelectedItem()
            if not item: return
            
            val = item.getProperty('value')
            label = item.getLabel()
            
            # Handle Local Mode Switching
            if val.startswith("set_mode:"):
                self.media_type = val.split(":")[1]
                
                if self.media_type == "movie":
                    display_msg = "Mám chuť na dobrý film."
                    llm_prompt = (
                        "Uživatel si vybral sekci FILMY.\n"
                        "1. Přeskoč úvodní pozdravy.\n"
                        "2. Funguj jako expert na filmy.\n"
                        "3. Polož mi stručnou, ale trefnou otázku ohledně mé nálady nebo preferovaného žánru.\n"
                        "4. Nabídni mi v tlačítkách konkrétní žánry (Sci-fi, Thriller, Komedie) nebo nálady (Oddechovka, K zamyšlení)."
                    )
                else:
                    display_msg = "Mám chuť na dobrý seriál."
                    llm_prompt = (
                        "Uživatel si vybral sekci SERIÁLY.\n"
                        "1. Přeskoč úvodní pozdravy.\n"
                        "2. Funguj jako expert na seriály.\n"
                        "3. Zeptej se mě, jestli hledám spíše Minisérii na víkend, nebo dlouhý seriál na maraton.\n"
                        "4. Nabídni v tlačítkách možnosti jako 'Minisérie', 'Dlouhý seriál', 'Sitcom', 'Krimi'."
                    )

                self.append_chat_message("Ty", display_msg)
                self.history.append({"role": "user", "content": llm_prompt})
                
                # IHNED start AI conversation - PRVNÍ DOTAZ
                self._start_ai_conversation()
            else:
                # Send button label/value as user text
                self.handle_user_input(label)
                
        # Send Text Button
        elif controlId == 3001:
            input_control = self.getControl(3000)
            text = input_control.getText()
            if text:
                input_control.setText("") # Clear input
                self.handle_user_input(text)
                
        # Recommendations Panel
        elif controlId == 2000:
            self.handle_recommendation_click()
    
    def _start_ai_conversation(self, is_initial_context=False):
        """Start AI conversation immediately after media type selection or on init with context."""
        # Start animated thinking indicator
        self._start_thinking_animation()
        
        # Call AI in thread
        # Pokud jde o initial context, posíláme prázdný user_text, protože zpráva je už v historii v onInit
        user_text = "" 
        t = threading.Thread(target=self._ai_worker, args=(user_text,))
        t.start()
    
    def _start_thinking_animation(self):
        """Start the animated dots animation."""
        self._thinking_stop.clear()
        self._dot_count = 0
        self._thinking_thread = threading.Thread(target=self._animate_dots)
        self._thinking_thread.start()
    
    def _stop_thinking_animation(self):
        """Stop the animated dots animation."""
        self._thinking_stop.set()
        if self._thinking_thread:
            self._thinking_thread.join(timeout=1)
            self._thinking_thread = None
    
    def _animate_dots(self):
        """Animate the dots in thinking status."""
        import time
        while not self._thinking_stop.is_set():
            dots = "." * (self._dot_count % 4)
            self.setProperty('WCS.AIChat.Status', f'AI přemýšlí{dots}')
            self._dot_count += 1
            time.sleep(0.4)
            
    def handle_user_input(self, user_text):
        """Process user input, update UI, and call AI."""
        if not self.media_type:
            # Should not happen if UI is correct, but fallback
            self.media_type = "movie"
            
        # 1. Update Chat UI
        self.append_chat_message("Ty", user_text)
        
        # 2. Add to history
        self.history.append({"role": "user", "content": user_text})
        
        # 3. Start animated thinking indicator
        self._start_thinking_animation()
        
        # 4. Call AI in thread
        t = threading.Thread(target=self._ai_worker, args=(user_text,))
        t.start()
        
    def _ai_worker(self, user_text):
        # Call AIHandler
        data, usage = ai_handler.chat_recommendation_step(self.history, user_text, self.media_type, context=self.context)
        
        # Stop the thinking animation
        self._stop_thinking_animation()
        
        if not data:
            self.setProperty('WCS.AIChat.Status', 'Chyba komunikace')
            return

        # Update History with AI response
        ai_msg = data.get('message', '')
        self.history.append({"role": "assistant", "content": ai_msg})
        
        # Schedule UI Update on main thread logic (using xbmc operations is mostly safe, but let's be careful)
        # We can call methods directly as they mostly use Kodi GUI calls which are thread-safe enough for property/control setting usually
        self.append_chat_message("AI", ai_msg)
        self.setProperty('WCS.AIChat.Status', 'Připraven')
        
        # SHOW INPUT FIELD after first AI response
        self.setProperty('WCS.AIChat.ShowInput', 'true')
        
        # Update Buttons
        buttons = data.get('buttons', [])
        # Always add specific buttons if list is empty or to allow exit?
        # Let's trust AI, but maybe add "Zpět" if needed?
        self.update_buttons(buttons)
        
        # Handle Recommendations
        recs = data.get('recommendations', [])
        if recs:
            self.fetch_and_display_recommendations(recs)
            
    def fetch_and_display_recommendations(self, recommendations):
        """Fetch TMDB data and populate list."""
        # Use a worker to fetch TMDB to avoid freezing
        t = threading.Thread(target=self._tmdb_worker, args=(recommendations,))
        t.start()
        
    def _tmdb_worker(self, recommendations):
        list_control = self.getControl(2000)
        list_control.reset()
        
        for rec in recommendations:
            title = rec.get('title')
            year = rec.get('year')
            # Determine media type for this specific item (mixed content support)
            # Default to self.media_type if not specified by AI
            item_media_type = rec.get('type')
            if item_media_type not in ['movie', 'tv']:
                 item_media_type = self.media_type
                 
            # Fetch TMDB
            tmdb_data = self._search_tmdb(title, year, item_media_type)
            
            if tmdb_data:
                # Create ListItem - pro seriály TMDb vrací 'name' místo 'title'
                display_title = tmdb_data.get('title') or tmdb_data.get('name') or title
                item = xbmcgui.ListItem(label=display_title)
                poster = tmdb_data.get('poster_path')
                if poster:
                    item.setArt({'poster': f'https://image.tmdb.org/t/p/w500{poster}'})
                    
                # Store metadata for actions
                item.setProperty('tmdb_id', str(tmdb_data.get('id')))
                item.setProperty('media_type', item_media_type)
                item.setProperty('title', tmdb_data.get('title') or tmdb_data.get('name') or '')
                item.setProperty('year', tmdb_data.get('release_date', '')[:4] if item_media_type=='movie' else tmdb_data.get('first_air_date', '')[:4])
                item.setProperty('original_title', tmdb_data.get('original_title', tmdb_data.get('original_name','')))
                
                list_control.addItem(item)
                
    def _search_tmdb(self, title, year, media_type):
        """Identify movie/series/collection in TMDB."""
        try:
            api_key = get_tmdb_api_key()
            if media_type == "movie":
                endpoint = "search/movie"
            elif media_type == "collection":
                endpoint = "search/collection"
            else:
                endpoint = "search/tv"

            params = {'api_key': api_key, 'language': 'cs-CZ', 'query': title}
            if year and media_type != "collection": # Collections dont handle year filter well in search
                if media_type == "movie":
                     params['year'] = year
                else:
                     params['first_air_date_year'] = year
                    
            resp = requests.get(f'https://api.themoviedb.org/3/{endpoint}', params=params, timeout=5)
            if resp.status_code == 200:
                results = resp.json().get('results', [])
                if results:
                    return results[0]
        except Exception as e:
            xbmc.log(f"TMDB Error: {e}", xbmc.LOGERROR)
        return None

    def handle_recommendation_click(self):
        """Handle click on recommendation card."""
        list_control = self.getControl(2000)
        item = list_control.getSelectedItem()
        if not item: return
        
        tmdb_id = item.getProperty('tmdb_id')
        title = item.getProperty('title')
        year = item.getProperty('year')
        media_type = item.getProperty('media_type')
        
        # Načíst preferovanou akci z nastavení
        # Values: "Vyhledat na Webshare", "Vyhledat a přehrát", "Zobrazit WCS detaily", "Zobrazit menu akcí"
        click_action = self.addon.getSetting('ai_click_action')
        
        # Pro kolekce vždy zobrazíme menu, nebo pokud uživatel explicitně chce menu
        if media_type == "collection" or click_action == "Zobrazit menu akcí":
            self._show_action_menu(tmdb_id, title, year, media_type, item)
            return

        # Rychlé akce pro Film a Seriál
        if click_action == "Vyhledat na Webshare":
            # Varianta 1: Rovnou vyhledá na webshare (textové hledání)
            if media_type == "movie":
                # Pro filmy se chová stejně jako akce "Přehrát" - tj. vyhledá soubory a nabídne výběr (process play)
                plot = item.getProperty('plot') or ''
                poster = item.getArt('poster') or ''
                from wcs.utils import search_and_play_movie
                search_and_play_movie(title, year, plot, poster, '', '', '', '', '', self.addon)
                # NEZAVÍRAT self.close() - zavře se samo pokud začne přehrávání (Dialog.Close(all)), jinak zůstane otevřeno
            else:
                # Pro seriály/kolekce použijeme fallback na menu
                self._show_action_menu(tmdb_id, title, year, media_type, item)

        elif click_action == "Vyhledat a přehrát":
            # Varianta 2: Rovnou vyhledá na webshare a automaticky přehraje (pokud to jde, jinak search & play)
            if media_type == "movie":
                plot = item.getProperty('plot') or ''
                poster = item.getArt('poster') or ''
                from wcs.utils import search_and_play_movie
                # search_and_play_movie zahájí proces výběru a přehrání s vynuceným autoplay
                search_and_play_movie(title, year, plot, poster, '', '', '', '', '', self.addon, autoplay=True)
                # NEZAVÍRAT self.close()
            else:
                # Pro seriály/kolekce použijeme fallback na menu
                self._show_action_menu(tmdb_id, title, year, media_type, item)
                
        elif click_action == "Zobrazit WCS detaily":
            # Varianta 3: Rovnou otevře dialog WCS Details
            m_type = "tv" if media_type in ["series", "tv"] else "movie"
            detail_url = f"plugin://{self.addon.getAddonInfo('id')}?action=show_wcs_details&media_type={m_type}&tmdb_id={tmdb_id}"
            xbmc.executebuiltin(f"RunPlugin({detail_url})")

    def _show_action_menu(self, tmdb_id, title, year, media_type, item):
        """Standardní modální dialog s akcemi (původní chování)."""
        dialog = xbmcgui.Dialog()
        
        if media_type == "collection":
            # KOLEKCE
            opts = [
                "Zobrazit filmy v kolekci",
                f"Inspiruj se: {title}",
                "Přidat do Moje filmy",
                "Přidat do knihovny Kodi"
            ]
            sel = dialog.select(f"Akce: {title}", opts)
            
            if sel == 0:
                # Zobrazit kolekci 
                from urllib.parse import quote_plus
                url = f"plugin://{self.addon.getAddonInfo('id')}?action=list_collection_movies&collection_id={tmdb_id}&collection_name={quote_plus(title)}"
                xbmc.executebuiltin(f"Container.Update({url})")
            elif sel == 1:
                inspiration_text = f"Najdi podobné filmové kolekce jako: {title}"
                self.handle_user_input(inspiration_text)
            elif sel == 2:
                # Přidat do Moje filmy
                url = f"plugin://{self.addon.getAddonInfo('id')}?action=add_collection_to_my_movies&collection_id={tmdb_id}"
                xbmc.executebuiltin(f"RunPlugin({url})")
            elif sel == 3:
                # Přidat do knihovny Kodi
                url = f"plugin://{self.addon.getAddonInfo('id')}?action=add_collection_to_library&collection_id={tmdb_id}"
                xbmc.executebuiltin(f"RunPlugin({url})")
                
        elif media_type == "series" or media_type == "tv":
            # SERIÁL
            opts = [
                "Zobrazit detaily",
                "Zobrazit sezóny",
                f"Inspiruj se: {title}",
                "Přidat do Moje seriály",
                "Přidat do knihovny Kodi"
            ]
            sel = dialog.select(f"Akce: {title} ({year})", opts)
            
            if sel == 0:
                detail_url = f"plugin://{self.addon.getAddonInfo('id')}?action=show_wcs_details&media_type=tv&tmdb_id={tmdb_id}"
                xbmc.executebuiltin(f"RunPlugin({detail_url})")
            elif sel == 1:
                from urllib.parse import quote_plus
                seasons_url = f"plugin://{self.addon.getAddonInfo('id')}?action=display_series_seasons&series_id={tmdb_id}&name={quote_plus(title)}"
                self.close()
                xbmc.executebuiltin(f'AlarmClock(OpenSeasons,Container.Update({seasons_url}),00:01,silent)')
            elif sel == 2:
                inspiration_text = f"Najdi podobné seriály jako: {title} ({year})"
                self.handle_user_input(inspiration_text)
            elif sel == 3:
                from wcs.ui.UI import add_series_item_to_list
                add_series_item_to_list(self.addon, tmdb_id, title)
            elif sel == 4:
                from wcs.library import LibraryManager as library
                library.check_settings_and_add_item({'media_type': 'series', 'series_id': tmdb_id}, self.addon)
        else:
            # FILM
            opts = [
                "Zobrazit detaily",
                "Přehrát",
                f"Inspiruj se: {title}",
                "Přidat do Moje filmy",
                "Přidat do knihovny Kodi"
            ]
            sel = dialog.select(f"Akce: {title} ({year})", opts)
            
            if sel == 0:
                detail_url = f"plugin://{self.addon.getAddonInfo('id')}?action=show_wcs_details&media_type=movie&tmdb_id={tmdb_id}"
                xbmc.executebuiltin(f"RunPlugin({detail_url})")
            elif sel == 1:
                plot = item.getProperty('plot') or ''
                poster = item.getArt('poster') or ''
                from wcs.utils import search_and_play_movie
                search_and_play_movie(title, year, plot, poster, '', '', '', '', '', self.addon)
                self.close()
            elif sel == 2:
                inspiration_text = f"Najdi podobné filmy jako: {title} ({year})"
                self.handle_user_input(inspiration_text)
            elif sel == 3:
                from wcs.ui.UI import add_movie_item_to_list
                add_movie_item_to_list(self.addon, tmdb_id, title)
            elif sel == 4:
                from wcs.library import LibraryManager as library
                library.check_settings_and_add_item({'media_type': 'movie', 'movie_id': tmdb_id}, self.addon)
