# -*- coding: utf-8 -*-
import xbmc
import xbmcgui
import xbmcaddon
from xbmcvfs import translatePath

ADDON = xbmcaddon.Addon('plugin.video.mmirousek_v3')
_ADDON_PATH = translatePath(ADDON.getAddonInfo('path'))
_XML_FILE = 'script-embuary-video.xml'
_REVIEWS_XML = 'csfd_reviews.xml'

class CSFDInfoWindow(xbmcgui.WindowXMLDialog):
    """
    Dialogové okno pro zobrazení detailních informací z ČSFD.
    Využívá script-embuary-video.xml a ListItem properties v Container(10051) pro plnění dat.
    """

    def __init__(self, *args, **kwargs):
        self.info = kwargs.pop('info', {})
        self.chosen_title = kwargs.pop('chosen_title', '')
        self.kodi_fanart = kwargs.pop('kodi_fanart', '')
        self._reviews_text = ''
        self._reviews_fanart = ''
        super().__init__(*args, **kwargs)

    def onInit(self):
        """Volá Kodi po otevření okna – plníme Container(10051) ListItem a Recenze."""
        try:
            # Příprava základních údajů
            title_cz = self.info.get('title_cz') or self.chosen_title
            title_orig = self.info.get('title_orig') or self.info.get('title_en') or ''
            year = self.info.get('year', '')
            rating_csfd_val = self.info.get('rating')  # např. 87
            votes_val = self.info.get('votes')  # např. 1234
            runtime = self.info.get('runtime', 0)  # v minutách
            plot = self.info.get('plot', '')
            poster = self.info.get('poster', '')
            fanart = self.info.get('fanart') or self.kodi_fanart or 'DefaultVideoFanart.png'
            genres_list = self.info.get('genres', [])
            cast_list = self.info.get('cast', [])
            
            # Formátování ČSFD ratingu a hlasů
            rating_csfd_text = f"{rating_csfd_val}%" if rating_csfd_val else ''
            votes_csfd_text = f"({votes_val} hlasů)" if votes_val else ''
            
            # Příprava recenzí
            comments = self.info.get('comments', [])
            has_reviews = '1' if comments else ''
            if comments:
                separator = "\n\n[COLOR C6FFFFFF]────────────────────────────────────────[/COLOR]\n\n"
                self._reviews_text = separator.join(comments)
            else:
                self._reviews_text = "Žádné recenze nejsou k dispozici."
            self._reviews_fanart = fanart
            
            # Vytvoření ListItem pro Container(10051)
            li = xbmcgui.ListItem(label=title_cz)
            
            # Plnění video info tagu (Kodi 19+)
            tag = None
            try:
                tag = li.getVideoInfoTag()
                tag.setTitle(title_cz)
                tag.setOriginalTitle(title_orig)
                if year:
                    tag.setYear(int(year))
                if plot:
                    tag.setPlot(plot)
                if genres_list:
                    if isinstance(genres_list, list):
                        # Pokud jsou to dicty, extrahuj 'name'
                        genre_names = []
                        for g in genres_list:
                            if isinstance(g, dict):
                                genre_names.append(g.get('name', ''))
                            else:
                                genre_names.append(str(g))
                        tag.setGenres(genre_names)
                    else:
                        tag.setGenres(genres_list)
                if runtime:
                    tag.setDuration(int(runtime) * 60 if int(runtime) < 1000 else int(runtime))  # Konverze na sekundy
            except (AttributeError, TypeError) as e:
                xbmc.log(f"[CSFDInfoWindow] getVideoInfoTag() selhalo: {e}", xbmc.LOGWARNING)
                tag = None
            
            # Obrázky
            art = {'thumb': poster or 'DefaultVideoPoster.png', 'poster': poster or 'DefaultVideoPoster.png', 'fanart': fanart}
            li.setArt(art)
            
            # ČSFD properties
            li.setProperty('rating.csfd', rating_csfd_text)
            li.setProperty('votes.csfd', votes_csfd_text)
            li.setProperty('has_reviews', has_reviews)
            
            # Další ratingy (TMDb, IMDb, Rotten Tomatoes, Metacritic)
            xbmc.log(f"[CSFDInfoWindow] tag przítomný: {tag is not None}, rating_csfd_val={rating_csfd_val}", xbmc.LOGINFO)
            if tag:
                tmdb_rating = self.info.get('tmdb_rating')
                tmdb_votes = self.info.get('tmdb_votes')
                xbmc.log(f"[CSFDInfoWindow] TMDb rating: {tmdb_rating}, votes: {tmdb_votes}", xbmc.LOGINFO)
                if tmdb_rating and str(tmdb_rating) != str(rating_csfd_val):
                    try:
                        tag.setRating(float(tmdb_rating))
                        if tmdb_votes:
                            tag.setVotes(int(tmdb_votes))
                    except (ValueError, TypeError):
                        pass
            
            # IMDb rating a votes
            imdb_rating = self.info.get('imdb_rating')
            imdb_votes = self.info.get('imdb_votes')
            if imdb_rating:
                li.setProperty('rating.imdb', str(imdb_rating))
            if imdb_votes:
                li.setProperty('votes.imdb', f"({int(imdb_votes):,})" if isinstance(imdb_votes, (int, float)) else f"({imdb_votes})")
            
            # Rotten Tomatoes rating a votes
            rotten_rating = self.info.get('rotten_rating') or self.info.get('rotten')
            rotten_votes = self.info.get('rotten_votes') or self.info.get('rotten_count')
            if rotten_rating:
                li.setProperty('rating.rotten', str(rotten_rating))
            if rotten_votes:
                li.setProperty('votes.rotten', f"({int(rotten_votes):,})" if isinstance(rotten_votes, (int, float)) else f"({rotten_votes})")
            
            # Metacritic rating
            metacritic_rating = self.info.get('metacritic_rating') or self.info.get('metacritic')
            if metacritic_rating:
                li.setProperty('rating.metacritic', str(metacritic_rating))
            
            # Přidání ListItem do Container(10051)
            container = self.getControl(10051)
            container.reset()
            container.addItem(li)
            
            # Plnění seznamu herců
            self._fill_cast()
            
            xbmc.log(f"[CSFDInfoWindow] Okno inicializováno: {title_cz} ({year}), rating={rating_csfd_text}", xbmc.LOGINFO)
            
        except Exception as e:
            xbmc.log(f"[CSFDInfoWindow] Chyba v onInit: {e}", xbmc.LOGERROR)
            raise

    def _fill_cast(self):
        """Naplní horizontální list herci (Container 10052)."""
        try:
            container = self.getControl(10052)
            container.reset()
            
            cast_list = []
            for actor in self.info.get('cast', []):
                li = xbmcgui.ListItem(actor.get('name', 'Neznámý'))
                thumb = actor.get('thumb')
                if thumb:
                    li.setArt({'thumb': thumb, 'icon': thumb})
                aid = actor.get('id')
                if aid:
                    li.setProperty('tmdb_person_id', str(aid))
                cast_list.append(li)
            
            if cast_list:
                container.addItems(cast_list)
        except Exception as e:
            xbmc.log(f"[CSFDInfoWindow] Chyba při plnění herců: {e}", xbmc.LOGWARNING)

    def _open_person_from_cast_panel(self):
        """Otevře TMDb detail osoby (PersonInfoWindow) pro vybraného herce v panelu 10052."""
        try:
            panel = self.getControl(10052)
            idx = panel.getSelectedPosition()
            if idx is None or idx < 0:
                return
            try:
                if panel.size() >= 0 and idx >= panel.size():
                    return
            except Exception:
                pass
            li = panel.getListItem(idx)
            if not li:
                return
            pid = (li.getProperty('tmdb_person_id') or '').strip()
            if not pid:
                xbmcgui.Dialog().notification(
                    'ČSFD',
                    'Pro tuto osobu není k dispozici odkaz na TMDb.',
                    xbmcgui.NOTIFICATION_INFO,
                    2500,
                )
                return
            from resources.lib.tmdb.tmdb_kodi import open_person_detail_modal

            navigated = open_person_detail_modal(int(pid))
            if navigated:
                self.close()
        except Exception as e:
            xbmc.log(f"[CSFDInfoWindow] Otevření osoby z obsazení: {e}", xbmc.LOGWARNING)

    def _show_reviews(self):
        """Otevření dialogu s recenzemi ČSFD."""
        if not self._reviews_text:
            xbmcgui.Dialog().notification("ČSFD", "Žádné recenze nejsou k dispozici.", 
                                         xbmcgui.NOTIFICATION_INFO, 3000)
            return
        
        title = self.info.get('title_cz') or self.chosen_title
        CSFDReviewsWindow.show_reviews(self._reviews_text, title=title, fanart=self._reviews_fanart)

    def onAction(self, action):
        """Obsluha akcí včetně výběru položky v panelu tlačítek (Enter, myš)."""
        action_id = action.getId()
        
        # Zachycení výběru (Enter/OK) nebo klik myší na panelu tlačítek
        if action_id in (xbmcgui.ACTION_SELECT_ITEM, xbmcgui.ACTION_MOUSE_LEFT_CLICK):
            focused_id = self.getFocusId()
            xbmc.log(f"[CSFDInfoWindow] onAction: action_id={action_id}, focused_id={focused_id}", xbmc.LOGDEBUG)
            if focused_id == 10052:
                self._open_person_from_cast_panel()
                return
            if focused_id == 100 or action_id == xbmcgui.ACTION_MOUSE_LEFT_CLICK:
                try:
                    panel = self.getControl(100)
                    selected_idx = panel.getSelectedPosition()

                    # Panel může krátce vracet nevalidní index (např. při mouse clicku během změny focusu).
                    if selected_idx is None or selected_idx < 0:
                        xbmc.log(f"[CSFDInfoWindow] Nevalidní index panelu: {selected_idx}", xbmc.LOGDEBUG)
                        return

                    try:
                        item_count = panel.size()
                    except Exception:
                        item_count = -1

                    if item_count >= 0 and selected_idx >= item_count:
                        xbmc.log(
                            f"[CSFDInfoWindow] Index mimo rozsah: idx={selected_idx}, count={item_count}",
                            xbmc.LOGWARNING
                        )
                        return

                    selected_item = panel.getListItem(selected_idx)
                    item_label = selected_item.getLabel()
                    
                    xbmc.log(f"[CSFDInfoWindow] Panel klik: label='{item_label}' (idx={selected_idx})", xbmc.LOGINFO)
                    
                    # Detekce podle label textu — "Recenze ČSFD"
                    if "Recenze" in item_label and "ČSFD" in item_label:
                        self._show_reviews()
                        return
                except IndexError as e:
                    xbmc.log(f"[CSFDInfoWindow] IndexError v panelu: {e}", xbmc.LOGWARNING)
                except Exception as e:
                    xbmc.log(f"[CSFDInfoWindow] Chyba při detekci kliknutí na panel: {e}", xbmc.LOGWARNING)
        
        # Obvyklé akce pro zavření okna
        if action_id in (
            xbmcgui.ACTION_NAV_BACK,
            xbmcgui.ACTION_PREVIOUS_MENU,
            xbmcgui.ACTION_STOP,
            xbmcgui.ACTION_PARENT_DIR
        ):
            self.close()

    def onClick(self, controlId):
        """Spolehlivá obsluha kliknutí/aktivace controlu."""
        xbmc.log(f"[CSFDInfoWindow] onClick controlId={controlId}", xbmc.LOGINFO)
        if controlId == 101:
            self._show_reviews()
            return

        if controlId == 10052:
            self._open_person_from_cast_panel()
            return

        if controlId != 100:
            return

        try:
            panel = self.getControl(100)
            selected_idx = panel.getSelectedPosition()

            if selected_idx is None or selected_idx < 0:
                return

            selected_item = panel.getListItem(selected_idx)
            item_label = selected_item.getLabel() or ''

            # Recenze tlačítko - otevře vlastní dialog
            if "Recenze" in item_label and "ČSFD" in item_label:
                self._show_reviews()
        except Exception as e:
            xbmc.log(f"[CSFDInfoWindow] Chyba v onClick(100): {e}", xbmc.LOGWARNING)

    @classmethod
    def show_info(cls, info, chosen_title='', kodi_fanart=''):
        """Tovární metoda pro snadné otevření okna."""
        win = cls(_XML_FILE, _ADDON_PATH, 'Default', '1080i', info=info, chosen_title=chosen_title, kodi_fanart=kodi_fanart)
        win.doModal()
        del win


class CSFDReviewsWindow(xbmcgui.WindowXMLDialog):
    """
    Dialogové okno pro zobrazení recenzí z ČSFD s posuvníkem.
    Využívá csfd_reviews.xml a Window Properties pro plnění textů.
    """

    def __init__(self, *args, **kwargs):
        self.reviews_text = kwargs.pop('reviews_text', '')
        self.reviews_title = kwargs.pop('reviews_title', '')
        self.reviews_fanart = kwargs.pop('reviews_fanart', '')
        super().__init__(*args, **kwargs)

    def onInit(self):
        """Volá Kodi po otevření okna – plníme Window Properties."""
        self.setProperty('reviews_title', self.reviews_title)
        self.setProperty('reviews_text', self.reviews_text)
        self.setProperty('reviews_fanart', self.reviews_fanart)
        xbmc.log(f"[CSFDReviewsWindow] Dialog se recenzemi inicializován: {self.reviews_title}", xbmc.LOGINFO)

    def onAction(self, action):
        """Obsluha akcí pro zavření okna."""
        if action.getId() in (
            xbmcgui.ACTION_NAV_BACK,
            xbmcgui.ACTION_PREVIOUS_MENU,
            xbmcgui.ACTION_STOP,
            xbmcgui.ACTION_PARENT_DIR
        ):
            self.close()

    @classmethod
    def show_reviews(cls, reviews_text, title='', fanart=''):
        """Tovární metoda pro otevření okna s recenzemi."""
        win = cls(_REVIEWS_XML, _ADDON_PATH, 'Default', '1080i', 
                 reviews_text=reviews_text, reviews_title=title, reviews_fanart=fanart)
        win.doModal()
        del win
