# wcs/playback/dialogs/media_info.py
# MediaInfoDialog -- jednotný dialog pro film i epizodu

import xbmc
import xbmcgui
import xbmcaddon
import threading
import time

from wcs.playback.metadata import MediaMetadata


class MediaInfoDialog(xbmcgui.WindowXMLDialog):
    """
    Jednotný dialog pro zobrazení informací o filmu nebo epizodě; „Hrát hru“ otevře hru Milionář (wcs/games/millionaire).

    media_type:
      - "movie": používá prefix `WCS.Movie.*` a filmové XML
      - "series": používá prefix `WCS.Episode.*` a epizodní XML
    """

    def __init__(
        self,
        xmlFilename,
        addonPath,
        skin="Default",
        theme="Default",
        *,
        media_type="movie",
        # Movie fields
        movie_title="",
        movie_year="",
        movie_thumb="",
        genre="",
        director="",
        runtime="",
        # Episode fields
        series_name="",
        episode_title="",
        season_number=None,
        episode_number=None,
        episode_thumb="",
        year="",
        # Common fields
        rating="",
        plot="",
        tmdb_id="",
        fanart="",
    ):
        super().__init__()
        self.media_type = media_type

        # Common
        self.rating = rating
        self.plot = plot
        self.tmdb_id = tmdb_id
        self.fanart = fanart

        # Movie
        self.movie_title = movie_title
        self.movie_year = movie_year
        self.movie_thumb = movie_thumb
        self.genre = genre
        self.director = director
        self.runtime = runtime

        # Episode
        self.series_name = series_name
        self.episode_title = episode_title
        self.season_number = season_number
        self.episode_number = episode_number
        self.episode_thumb = episode_thumb
        self.year = year

        # State
        self.auto_close_thread = None
        self.is_running = False
        self.plot_visible = False
        self.future_feature_mode = False

    @staticmethod
    def _clean_image_url(url):
        """Dekoduje Kodi image:// URL na cistu URL pro spravne renderovani s diffuse maskou."""
        if url and url.startswith('image://'):
            from urllib.parse import unquote
            return unquote(url[8:].rstrip('/'))
        return url or ""

    @staticmethod
    def _get_dialog_xml_filename_for_media(media_type: str) -> str:
        try:
            addon = xbmcaddon.Addon()
            style_index = int(addon.getSetting('dialog_style') or 0)
            if media_type == "movie":
                style_files = [
                    'notifications/classic/DialogMovieInfoWithGame.xml',
                    'notifications/modern/DialogMovieInfoWithGame.xml',
                    'notifications/minimal/DialogMovieInfoWithGame.xml',
                    'notifications/premium/DialogMovieInfoWithGame.xml',
                ]
            else:
                style_files = [
                    'notifications/classic/DialogEpisodeInfoWithGame.xml',
                    'notifications/modern/DialogEpisodeInfoWithGame.xml',
                    'notifications/minimal/DialogEpisodeInfoWithGame.xml',
                    'notifications/premium/DialogEpisodeInfoWithGame.xml',
                ]
            filename = style_files[style_index] if 0 <= style_index < len(style_files) else style_files[0]
            xbmc.log(f"[plugin.video.wcs] MediaInfoDialog: Using style index '{style_index}' -> {filename}", level=xbmc.LOGINFO)
            return filename
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] MediaInfoDialog: Error getting dialog style, using default: {e}", level=xbmc.LOGWARNING)
            return 'notifications/classic/DialogMovieInfoWithGame.xml' if media_type == "movie" else 'notifications/classic/DialogEpisodeInfoWithGame.xml'

    def _prefix(self) -> str:
        return 'WCS.Movie' if self.media_type == 'movie' else 'WCS.Episode'

    # ---------- Lifecycle ----------
    def onInit(self):
        xbmc.log("[plugin.video.wcs] MediaInfoDialog: Initializing", level=xbmc.LOGINFO)

        if self.media_type == 'movie':
            self._init_movie_properties()
        else:
            self._init_episode_properties()

        # Inicializace viditelnosti sekcí
        self.setProperty(f'{self._prefix()}.ShowPlot', 'false')

        # Akční tlačítka (pill-shaped list)
        self._populate_action_buttons()

        # Auto-close
        self.is_running = True
        self.auto_close_thread = threading.Thread(target=self._auto_close_worker)
        self.auto_close_thread.daemon = True
        self.auto_close_thread.start()

    def _populate_action_buttons(self):
        """Naplní pill-shaped akční tlačítka (list control 103).

        Některé styly (např. premium) používají místo seznamu pevná tlačítka
        v XML, tato metoda se pak přeskočí.
        """
        try:
            action_list = self.getControl(103)
        except Exception:
            xbmc.log(
                "[plugin.video.wcs] MediaInfoDialog: No action list control 103, dialog uses XML buttons",
                level=xbmc.LOGINFO,
            )
            return
        try:
            action_list.reset()
            buttons = [
                ('info', 'Info'),
                ('play_game', 'Hrát hru'),
                ('close', 'Zavřít'),
            ]
            for action_id, label in buttons:
                item = xbmcgui.ListItem(label)
                item.setProperty('action_id', action_id)
                action_list.addItem(item)
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] MediaInfoDialog: Failed to populate action buttons: {e}", level=xbmc.LOGERROR)

    def _auto_close_worker(self):
        time.sleep(5)
        if self.is_running:
            xbmc.executebuiltin("Action(Back)")

    # ---------- Init helpers ----------
    def _format_rating_properties(self, rating_value: str, year_value: str):
        rating_formatted = ""
        rating_only_text = ""
        year_only_text = ""
        if rating_value:
            try:
                rating_float = float(rating_value)
                rating_formatted = f"{rating_float:.1f}"
            except (ValueError, TypeError):
                rating_formatted = str(rating_value)
            rating_only_text = f"★ {rating_formatted}/10"
            if year_value:
                rating_text = f"★ {rating_formatted}/10 • {year_value}"
                year_only_text = year_value
            else:
                rating_text = f"★ {rating_formatted}/10"
        else:
            rating_text = year_value if year_value else ""
            if year_value:
                year_only_text = year_value

        try:
            rating_progress = min(100, max(0, int(float(rating_formatted) * 10))) if rating_formatted else 0
        except (ValueError, TypeError):
            rating_progress = 0
        return rating_text, rating_formatted, rating_only_text, year_only_text, rating_progress

    @staticmethod
    def _compose_meta_line(parts, rating_text):
        """Sestaví meta řádek (SxxExx • rok • ★ hodnocení) s barvami pro premium styl."""
        separator = '  •  '
        values = [part for part in parts if part]
        colored = [f'[COLOR FFC9CAD0]{value}[/COLOR]' for value in values]
        text = f'[COLOR FF7F7F86]{separator}[/COLOR]'.join(colored)
        if rating_text:
            rating = f'[COLOR FFF2DD56]{rating_text}[/COLOR]'
            if text:
                text += f'[COLOR FF7F7F86]{separator}[/COLOR]{rating}'
            else:
                text = rating
        return text

    def _init_movie_properties(self):
        # Základní
        self.setProperty('WCS.Movie.Title', self.movie_title)
        self.setProperty('WCS.Movie.Year', self.movie_year)
        self.setProperty('WCS.Movie.Thumb', self._clean_image_url(self.movie_thumb))
        self.setProperty('WCS.Movie.Fanart', self._clean_image_url(self.fanart))
        self.setProperty('WCS.Movie.Genre', self.genre)
        self.setProperty('WCS.Movie.Director', self.director)
        self.setProperty('WCS.Movie.Runtime', self.runtime)

        rating_text, rating_formatted, rating_only_text, year_only_text, rating_progress = self._format_rating_properties(self.rating, self.movie_year)
        self.setProperty('WCS.Movie.Rating', rating_text)
        self.setProperty('WCS.Movie.RatingFormatted', rating_formatted)
        self.setProperty('WCS.Movie.RatingOnly', rating_only_text)
        self.setProperty('WCS.Movie.YearOnly', year_only_text)
        self.setProperty('WCS.Movie.RatingProgress', str(rating_progress))

        self.setProperty('WCS.Movie.TMDBID', self.tmdb_id)
        self.setProperty('WCS.Movie.Fanart', self._clean_image_url(self.fanart))
        self.setProperty('WCS.Movie.Plot', self.plot or "Popis filmu není dostupný.")
        self.setProperty('WCS.Movie.MetaLine', self._compose_meta_line([self.movie_year], rating_only_text))

        full_info_text = self._create_full_info_text_movie()
        self.setProperty('WCS.Movie.FullInfo', full_info_text)

    def _init_episode_properties(self):
        # Základní
        self.setProperty('WCS.Episode.SeriesName', self.series_name)
        self.setProperty('WCS.Episode.Title', self.episode_title)

        if self.season_number and self.episode_number:
            season_episode = f"S{int(self.season_number):02d}E{int(self.episode_number):02d}"
        else:
            season_episode = "Neznámá epizoda"
        self.setProperty('WCS.Episode.SeasonEpisode', season_episode)
        has_season_episode = bool(self.season_number and self.episode_number)

        self.setProperty('WCS.Episode.Thumb', self._clean_image_url(self.episode_thumb))

        rating_text, rating_formatted, rating_only_text, year_only_text, rating_progress = self._format_rating_properties(self.rating, self.year)
        self.setProperty('WCS.Episode.Rating', rating_text)
        self.setProperty('WCS.Episode.RatingFormatted', rating_formatted)
        self.setProperty('WCS.Episode.RatingOnly', rating_only_text)
        self.setProperty('WCS.Episode.YearOnly', year_only_text)
        self.setProperty('WCS.Episode.RatingProgress', str(rating_progress))

        self.setProperty('WCS.Episode.SeriesTMDBID', self.tmdb_id)
        self.setProperty('WCS.Episode.SeriesFanart', self._clean_image_url(self.fanart))
        self.setProperty('WCS.Episode.Plot', self.plot or "Popis epizody není dostupný.")
        self.setProperty(
            'WCS.Episode.MetaLine',
            self._compose_meta_line([season_episode if has_season_episode else '', self.year], rating_only_text),
        )

        full_info_text = self._create_full_info_text_episode()
        self.setProperty('WCS.Episode.FullInfo', full_info_text)

    # ---------- Kodi actions ----------
    def onAction(self, action):
        navigation_actions = [
            xbmcgui.ACTION_MOVE_LEFT,
            xbmcgui.ACTION_MOVE_RIGHT,
            xbmcgui.ACTION_MOVE_UP,
            xbmcgui.ACTION_MOVE_DOWN,
            xbmcgui.ACTION_SELECT_ITEM,
            xbmcgui.ACTION_MOUSE_MOVE,
        ]
        if action.getId() in navigation_actions:
            self.is_running = False
            xbmc.log("[plugin.video.wcs] MediaInfoDialog: Auto-close cancelled due to user navigation", level=xbmc.LOGINFO)
            return

        if action.getId() in (xbmcgui.ACTION_PREVIOUS_MENU, xbmcgui.ACTION_NAV_BACK):
            self.is_running = False
            self.close()

    def _focus_actions(self):
        """Přesune fokus na akční tlačítka dialogu (list 103 nebo pevná tlačítka)."""
        for control_id in (103, 112, 111, 110):
            try:
                self.setFocus(self.getControl(control_id))
                return
            except Exception:
                continue

    def _handle_info_action(self, action_id, prefix):
        """Provede akci akčního tlačítka (sdílené pro list 103 i XML tlačítka)."""
        if action_id == 'info':  # Toggle plot
            self.plot_visible = not self.plot_visible
            self.setProperty(f'{prefix}.ShowPlot', 'true' if self.plot_visible else 'false')
            xbmc.log(f"[plugin.video.wcs] MediaInfoDialog: Plot visibility toggled to {self.plot_visible}", level=xbmc.LOGINFO)
        elif action_id == 'play_game':  # the Millionaire game, as its own window over the playing video
            self._open_game()
        elif action_id == 'close':  # Zavřít
            self.is_running = False
            self.close()
        else:
            xbmc.log(f"[plugin.video.wcs] MediaInfoDialog: Unknown action id '{action_id}'", level=xbmc.LOGWARNING)

    def onClick(self, controlId):
        prefix = self._prefix()
        if controlId in (110, 111, 112):  # Premium styl - pevná tlačítka v XML
            action_ids = {110: 'info', 111: 'play_game', 112: 'close'}
            self._handle_info_action(action_ids[controlId], prefix)
        elif controlId == 103:  # Akční tlačítka (pill-shaped list)
            item = self.getControl(103).getSelectedItem()
            if not item:
                return
            self._handle_info_action(item.getProperty('action_id'), prefix)

        elif controlId == 501:  # Upravit příběh (future)
            title = "Upravit příběh"
            if self.media_type == 'movie':
                desc = (
                    "Tato funkce umožní upravovat původní příběhy filmů pomocí pokročilé AI.\n\n"
                    "Budete moci:\n"
                    "• Měnit děj podle vlastních představ\n"
                    "• Vytvářet alternativní zakončení\n"
                    "• Přidávat nové postavy a situace\n"
                    "• Upravovat dialogy a scény\n"
                    "• Měnit žánr nebo atmosféru\n\n"
                    "Funkce bude dostupná, až bude AI dostatečně pokročilá pro tvorbu kvalitních upravených filmů."
                )
            else:
                desc = (
                    "Tato funkce umožní upravovat původní příběhy seriálů a epizod pomocí pokročilé AI.\n\n"
                    "Budete moci:\n"
                    "• Měnit děj podle vlastních představ\n"
                    "• Vytvářet alternativní zakončení\n"
                    "• Přidávat nové postavy a situace\n"
                    "• Upravovat dialogy a scény\n\n"
                    "Funkce bude dostupná, až bude AI dostatečně pokročilá pro tvorbu kvalitních upravených seriálů."
                )
            self.show_future_feature_info(title, desc)

        elif controlId == 502:  # Uložené úpravy (future)
            title = "Uložené úpravy"
            if self.media_type == 'movie':
                desc = (
                    "Zde budete moci spravovat všechny své uložené úpravy příběhů filmů.\n\n"
                    "Funkce zahrnuje:\n"
                    "• Seznam všech upravených filmů\n"
                    "• Možnost obnovení původních verzí\n"
                    "• Sdílení úprav s jinými uživateli\n"
                    "• Export upravených příběhů\n"
                    "• Verzování a historie změn\n"
                    "• Kategorizace podle žánru\n\n"
                    "Tato funkce bude implementována společně s funkcí úprav příběhů."
                )
            else:
                desc = (
                    "Zde budete moci spravovat všechny své uložené úpravy příběhů.\n\n"
                    "Funkce zahrnuje:\n"
                    "• Seznam všech upravených seriálů a epizod\n"
                    "• Možnost obnovení původních verzí\n"
                    "• Sdílení úprav s jinými uživateli\n"
                    "• Export upravených příběhů\n"
                    "• Verzování a historie změn\n\n"
                    "Tato funkce bude implementována společně s funkcí úprav příběhů."
                )
            self.show_future_feature_info(title, desc)

        elif controlId == 503:  # Návrat
            if self.future_feature_mode:
                self.future_feature_mode = False
                full_info_text = (
                    self._create_full_info_text_movie()
                    if self.media_type == 'movie'
                    else self._create_full_info_text_episode()
                )
                self.setProperty(f'{prefix}.FullInfo', full_info_text)
                try:
                    self.setFocus(self.getControl(501))
                except Exception:
                    pass
            else:
                self.plot_visible = False
                self.setProperty(f'{prefix}.ShowPlot', 'false')
                self._focus_actions()

    # ---------- Game ----------
    def _open_game(self):
        """The notification closes and the Millionaire game opens through the plugin (the service, which shows this
        notification, keeps running); the video plays on underneath."""
        from wcs.games import millionaire
        if self.media_type == 'movie':
            subject = millionaire.Subject(
                title=self.movie_title, media_type='movie', plot=self.plot, genre=self.genre,
                poster=self._clean_image_url(self.movie_thumb), backdrop=self._clean_image_url(self.fanart),
                tmdb_id=str(self.tmdb_id or ''), year=self.movie_year or '')
        else:
            subject = millionaire.Subject(
                title=self.series_name, media_type='series', plot=self.plot, backdrop=self._clean_image_url(self.fanart),
                episode_title=self.episode_title or '', season_number=self._number(self.season_number),
                episode_number=self._number(self.episode_number), tmdb_id=str(self.tmdb_id or ''), year=self.year or '')
        self.is_running = False
        self.close()
        millionaire.start(subject)

    @staticmethod
    def _number(value):
        try:
            return int(value)
        except (TypeError, ValueError):
            return None

    # ---------- Info text ----------
    def _create_full_info_text_movie(self) -> str:
        info_parts = []
        info_parts.append("[COLOR FF87CEEB]INFO:[/COLOR]")
        try:
            import json
            json_request = {
                "jsonrpc": "2.0",
                "method": "Player.GetItem",
                "params": {
                    "playerid": 1,
                    "properties": [
                        "director",
                        "genre",
                        "studio",
                        "country",
                        "premiered",
                        "runtime",
                        "tagline",
                        "originaltitle",
                    ],
                },
                "id": 1,
            }
            json_response = xbmc.executeJSONRPC(json.dumps(json_request))
            response_data = json.loads(json_response)
            if "result" in response_data and "item" in response_data["result"]:
                item = response_data["result"]["item"]
                if item.get("director"):
                    directors = ", ".join(item["director"]) if isinstance(item["director"], list) else str(item["director"])
                    info_parts.append(f"Režie: {directors}")
                elif self.director:
                    info_parts.append(f"Režie: {self.director}")

                if item.get("genre"):
                    genres = ", ".join(item["genre"]) if isinstance(item["genre"], list) else str(item["genre"])
                    info_parts.append(f"Žánr: {genres}")
                elif self.genre:
                    info_parts.append(f"Žánr: {self.genre}")

                year_runtime = []
                if self.movie_year:
                    year_runtime.append(f"Rok: {self.movie_year}")
                if item.get("runtime"):
                    runtime_mins = item["runtime"] // 60
                    year_runtime.append(f"Délka: {runtime_mins} min")
                elif self.runtime:
                    year_runtime.append(f"Délka: {self.runtime}")
                if year_runtime:
                    info_parts.append(" • ".join(year_runtime))

                if item.get("studio"):
                    studios = ", ".join(item["studio"]) if isinstance(item["studio"], list) else str(item["studio"])
                    info_parts.append(f"Studio: {studios}")

                if item.get("country"):
                    countries = ", ".join(item["country"]) if isinstance(item["country"], list) else str(item["country"])
                    info_parts.append(f"Země původu: {countries}")

                if item.get("premiered"):
                    info_parts.append(f"Premiéra: {item['premiered']}")

                if item.get("tagline"):
                    info_parts.append(f"Slogan: {item['tagline']}")

                if self.rating:
                    info_parts.append(f"Hodnocení: {self.rating}/10")
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error getting movie metadata: {e}", level=xbmc.LOGWARNING)
            tech_info = []
            if self.director:
                tech_info.append(f"Režie: {self.director}")
            if self.genre:
                tech_info.append(f"Žánr: {self.genre}")
            if self.movie_year:
                tech_info.append(f"Rok: {self.movie_year}")
            if self.runtime:
                tech_info.append(f"Délka: {self.runtime}")
            if self.rating:
                tech_info.append(f"Hodnocení: {self.rating}/10")
            if tech_info:
                info_parts.extend(tech_info)
            else:
                info_parts.append("Technické informace nejsou dostupné.")

        info_parts.append("")
        info_parts.append("[COLOR FF87CEEB]DĚJ:[/COLOR]")
        if self.plot:
            info_parts.append(self.plot)
        else:
            info_parts.append("Popis filmu není dostupný.")
        return "\n".join(info_parts)

    def _create_full_info_text_episode(self) -> str:
        info_parts = []
        info_parts.append("[COLOR FF87CEEB]INFO:[/COLOR]")
        try:
            import json
            json_request = {
                "jsonrpc": "2.0",
                "method": "Player.GetItem",
                "params": {
                    "playerid": 1,
                    "properties": [
                        "director",
                        "genre",
                        "studio",
                        "country",
                        "premiered",
                        "runtime",
                        "showlink",
                        "originaltitle",
                    ],
                },
                "id": 1,
            }
            json_response = xbmc.executeJSONRPC(json.dumps(json_request))
            response_data = json.loads(json_response)
            if "result" in response_data and "item" in response_data["result"]:
                item = response_data["result"]["item"]
                if item.get("director"):
                    directors = ", ".join(item["director"]) if isinstance(item["director"], list) else str(item["director"])
                    info_parts.append(f"Režie: {directors}")
                if item.get("genre"):
                    genres = ", ".join(item["genre"]) if isinstance(item["genre"], list) else str(item["genre"])
                    info_parts.append(f"Žánr: {genres}")
                if item.get("runtime"):
                    runtime_mins = item["runtime"] // 60
                    info_parts.append(f"Délka epizody: {runtime_mins} min")
                elif self.year:
                    info_parts.append(f"Rok: {self.year}")
                if item.get("studio"):
                    studios = ", ".join(item["studio"]) if isinstance(item["studio"], list) else str(item["studio"])
                    info_parts.append(f"Síť/Studio: {studios}")
                if item.get("country"):
                    countries = ", ".join(item["country"]) if isinstance(item["country"], list) else str(item["country"])
                    info_parts.append(f"Země původu: {countries}")
                if item.get("premiered"):
                    info_parts.append(f"Premiéra epizody: {item['premiered']}")
                if self.rating:
                    info_parts.append(f"Hodnocení: {self.rating}/10")
                if self.season_number and self.episode_number:
                    info_parts.append(f"Sezóna {self.season_number}, Epizoda {self.episode_number}")
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error getting episode metadata: {e}", level=xbmc.LOGWARNING)
            tech_info = []
            if self.year:
                tech_info.append(f"Rok: {self.year}")
            if self.rating:
                tech_info.append(f"Hodnocení: {self.rating}/10")
            if self.season_number and self.episode_number:
                tech_info.append(f"Sezóna {self.season_number}, Epizoda {self.episode_number}")
            if tech_info:
                info_parts.extend(tech_info)
            else:
                info_parts.append("Technické informace nejsou dostupné.")

        info_parts.append("")
        info_parts.append("[COLOR FF87CEEB]DĚJ:[/COLOR]")
        if self.plot:
            info_parts.append(self.plot)
        else:
            info_parts.append("Popis epizody není dostupný.")
        return "\n".join(info_parts)

    # ---------- Future feature screen ----------
    def show_future_feature_info(self, title, description):
        try:
            prefix = self._prefix()
            if self.media_type == 'movie':
                info_text = f"[COLOR FFFF6B6B]{title.upper()}[/COLOR]\n\n{description}\n\n[COLOR FF87CEEB]Stiskni 'Návrat' pro pokračování...[/COLOR]"
            else:
                info_text = f"[COLOR FFFF6B6B]{title.upper()}[/COLOR]\n\n{description}\n\n[COLOR FF87CEEB]Stiskni 'Zavřít' pro pokračování...[/COLOR]"
            self.setProperty(f'{prefix}.FullInfo', info_text)

            if self.media_type == 'series':
                # Epizodní varianta mění též texty info tlačítek
                self.setProperty('WCS.Episode.InfoButton1', "")
                self.setProperty('WCS.Episode.InfoButton2', "")
                self.setProperty('WCS.Episode.InfoButton3', "Návrat")

            self.future_feature_mode = True
            try:
                self.setFocus(self.getControl(503))
            except Exception:
                pass
        except Exception as e:
            xbmc.log(f"[plugin.video.wcs] Error showing future feature info: {e}", level=xbmc.LOGERROR)
