# 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.dialogs.base_game_dialog import GameDialogMixin
from wcs.playback.metadata import MediaMetadata

# Sdílené menu stavy, ve kterých má tlačítko Zavřít (index 3) ukončit herní panel
CLOSE_DIALOG_STATES = [
    "game_selection",
    "ended",
    "quiz_transition",
    "quiz_welcome",
    "quiz_instructions",
    "millionaire_welcome",
    "millionaire_rules",
    "adventure_welcome",
    "adventure_instructions",
    "error",
    "game_finished",
    "game_over",
    "placeholder",
]


class MediaInfoDialog(GameDialogMixin, xbmcgui.WindowXMLDialog):
    """
    Jednotný dialog pro zobrazení informací o filmu nebo epizodě včetně textové hry.

    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.init_game_state()  # GameDialogMixin
        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',
                ]
            else:
                style_files = [
                    'notifications/classic/DialogEpisodeInfoWithGame.xml',
                    'notifications/modern/DialogEpisodeInfoWithGame.xml',
                    'notifications/minimal/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')
        self.setProperty(f'{self._prefix()}.ShowGame', 'false')

        # Herní properties
        self.setProperty('WCS.Game.Title', '')
        self.setProperty('WCS.Game.Text', '')
        self.setProperty('WCS.Game.Button1', '')
        self.setProperty('WCS.Game.Button2', '')
        self.setProperty('WCS.Game.Button3', '')
        self.setProperty('WCS.Game.Button4', '')

        # 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)."""
        try:
            action_list = self.getControl(103)
            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:
            # BUG 4 FIX: Použití self.close() místo globálního Action(Back).
            # Action(Back) je globální Kodi akce která by mohla zavřít
            # nesprávné okno pokud dialog byl mezitím zavřen jinak.
            self.is_running = False
            self.close()

    # ---------- 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

    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ý.")

        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)

        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ý.")

        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 onClick(self, controlId):
        prefix = self._prefix()
        if controlId == 103:  # Akční tlačítka (pill-shaped list)
            item = self.getControl(103).getSelectedItem()
            if not item:
                return
            action_id = item.getProperty('action_id')
            if action_id == 'info':  # Toggle plot
                if self.game_visible:
                    self.game_visible = False
                    self.setProperty(f'{prefix}.ShowGame', 'false')
                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':  # Toggle game
                if self.plot_visible:
                    self.plot_visible = False
                    self.setProperty(f'{prefix}.ShowPlot', 'false')
                self.game_visible = not self.game_visible
                self.setProperty(f'{prefix}.ShowGame', 'true' if self.game_visible else 'false')
                if self.game_visible and not self.game_controller:
                    self.start_game()
                    try:
                        self.setFocus(self.getControl(301))
                    except Exception:
                        pass
                elif not self.game_visible and self.game_controller:
                    self.game_controller = None
                xbmc.log(f"[plugin.video.wcs] MediaInfoDialog: Game visibility toggled to {self.game_visible}", level=xbmc.LOGINFO)
            elif action_id == 'close':  # Zavřít
                self.is_running = False
                self.close()

        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')
                try:
                    self.setFocus(self.getControl(103))
                except Exception:
                    pass

        elif controlId in [301, 302, 303, 304] and self.game_controller:
            choice_index = controlId - 301
            current_state = self.game_controller.current_game_state
            xbmc.log(
                f"[plugin.video.wcs] MediaInfoDialog button {choice_index} pressed, game_state: {current_state}",
                level=xbmc.LOGINFO,
            )

            if choice_index == 3 and current_state in CLOSE_DIALOG_STATES:
                xbmc.log(
                    f"[plugin.video.wcs] MediaInfoDialog: Closing game dialog (button 3 in menu state {current_state})",
                    level=xbmc.LOGINFO,
                )
                self.game_visible = False
                self.setProperty(f'{prefix}.ShowGame', 'false')
                self.game_controller = None
                try:
                    self.setFocus(self.getControl(103))
                except Exception:
                    pass
            else:
                xbmc.log(
                    f"[plugin.video.wcs] MediaInfoDialog: Delegating choice {choice_index} to game_controller (state: {current_state})",
                    level=xbmc.LOGINFO,
                )
                self.game_controller.make_choice(choice_index)

    # ---------- Game ----------
    # --- GameDialogMixin bridge metody ---

    def _game_prefix(self):
        return 'WCS.Game'

    def _game_title_for_controller(self):
        return self.movie_title if self.media_type == 'movie' else self.series_name

    def _game_plot_for_controller(self):
        return self.plot

    def _game_genre_for_controller(self):
        return self.genre if self.media_type == 'movie' else ''

    def _game_media_type_for_controller(self):
        return self.media_type

    def _game_episode_title(self):
        return self.episode_title

    def _game_season_number(self):
        return self.season_number

    def _game_episode_number(self):
        return self.episode_number

    # ---------- 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)
