# wcs/playback/metadata.py

"""Jednotný metadata model pro filmy i epizody.

Normalizuje data ze všech zdrojů (TMDb addon, Kodi knihovna)
do společné struktury. Dekóduje Kodi image:// URL automaticky.
"""

from urllib.parse import unquote


class MediaMetadata:
    """Jednotný metadata model pro info a countdown dialogy.

    Podporované zdroje:
      - TMDb addon (HTTP URL pro obrázky)
      - Kodi knihovna (image:// encoded URL pro obrázky)

    Atributy se normalizují při vytvoření -- image:// URL se dekódují,
    rating se převádí na string, None hodnoty na prázdné stringy.
    """

    def __init__(
        self,
        media_type,
        title,
        thumb='',
        fanart='',
        rating='',
        plot='',
        year='',
        tmdb_id='',
        # Movie specific
        genre='',
        director='',
        runtime='',
        # Episode specific
        series_name='',
        episode_title='',
        season_number=None,
        episode_number=None,
    ):
        self.media_type = media_type  # 'movie' | 'series'
        self.title = title or ''
        self.thumb = self._clean_url(thumb)
        self.fanart = self._clean_url(fanart)
        self.rating = self._clean_rating(rating)
        self.plot = plot or ''
        self.year = str(year) if year else ''
        self.tmdb_id = str(tmdb_id) if tmdb_id else ''
        # Movie
        self.genre = genre or ''
        self.director = director or ''
        self.runtime = runtime or ''
        # Episode
        self.series_name = series_name or ''
        self.episode_title = episode_title or ''
        self.season_number = season_number
        self.episode_number = episode_number

    # ------------------------------------------------------------------
    # Normalizace
    # ------------------------------------------------------------------

    @staticmethod
    def _clean_url(url):
        """Dekóduje Kodi image:// URL na čistou HTTP URL."""
        if url and url.startswith('image://'):
            return unquote(url[8:].rstrip('/'))
        return url or ''

    @staticmethod
    def _clean_rating(rating):
        """Normalizuje rating na čistou číselnou hodnotu (string).

        Vstup může být float, int, string s jednotkami ('8.1/10'),
        string s čárkou ('8,1') apod.
        """
        if rating is None or rating == '' or rating == 0:
            return ''
        import re
        rating_text = str(rating)
        match = re.search(r'\d+(?:[.,]\d+)?', rating_text)
        if match:
            return match.group(0).replace(',', '.')
        return ''

    # ------------------------------------------------------------------
    # Factory metody -- TMDb addon (HTTP URL, žádná konverze obrázků)
    # ------------------------------------------------------------------

    @classmethod
    def from_tmdb_movie(cls, data):
        """Vytvoří metadata z TMDb dat filmu (addon play_movie_from_addon).

        Očekávané klíče: title, year, plot, poster, fanart, rating,
        genre, director, runtime, tmdb_id.
        """
        return cls(
            media_type='movie',
            title=data.get('title', ''),
            thumb=data.get('poster', ''),
            fanart=data.get('fanart', ''),
            rating=data.get('rating', ''),
            plot=data.get('plot', ''),
            year=data.get('year', ''),
            tmdb_id=data.get('tmdb_id', ''),
            genre=data.get('genre', ''),
            director=data.get('director', ''),
            runtime=data.get('runtime', ''),
        )

    @classmethod
    def from_tmdb_episode(cls, data):
        """Vytvoří metadata z TMDb dat epizody (addon search_and_play_episode).

        Očekávané klíče: series_name, episode_title, season_number,
        episode_number, poster, fanart, rating, year, plot, tmdb_id.
        """
        return cls(
            media_type='series',
            title=data.get('series_name', ''),
            thumb=data.get('episode_thumb', '') or data.get('poster', ''),
            fanart=data.get('fanart', ''),
            rating=data.get('rating', ''),
            plot=data.get('plot', ''),
            year=data.get('year', ''),
            tmdb_id=data.get('tmdb_id', ''),
            series_name=data.get('series_name', ''),
            episode_title=data.get('episode_title', ''),
            season_number=data.get('season_number'),
            episode_number=data.get('episode_number'),
        )

    # ------------------------------------------------------------------
    # Factory metody -- Kodi knihovna (image:// URL, _clean_url je dekóduje)
    # ------------------------------------------------------------------

    @classmethod
    def from_kodi_library_movie(cls, data):
        """Vytvoří metadata z get_movie_metadata_from_library().

        Očekávané klíče: title, year, rating, plot, poster, fanart,
        genre, director, runtime, tmdb_id.
        Obrázky jsou image:// URL -- dekóduje _clean_url.
        """
        return cls(
            media_type='movie',
            title=data.get('title', ''),
            thumb=data.get('poster', ''),
            fanart=data.get('fanart', ''),
            rating=data.get('rating', ''),
            plot=data.get('plot', ''),
            year=data.get('year', ''),
            tmdb_id=data.get('tmdb_id', ''),
            genre=data.get('genre', ''),
            director=data.get('director', ''),
            runtime=data.get('runtime', ''),
        )

    @classmethod
    def from_kodi_library_episode(cls, data):
        """Vytvoří metadata z get_episode_metadata_from_library().

        Očekávané klíče: series_title, episode_title, season_number,
        episode_number, episode_thumb, series_fanart, episode_rating,
        episode_year, episode_plot.
        Obrázky jsou image:// URL -- dekóduje _clean_url.
        """
        return cls(
            media_type='series',
            title=data.get('series_title', ''),
            thumb=data.get('episode_thumb', ''),
            fanart=data.get('series_fanart', ''),
            rating=data.get('episode_rating', ''),
            plot=data.get('episode_plot', ''),
            year=data.get('episode_year', ''),
            series_name=data.get('series_title', ''),
            episode_title=data.get('episode_title', ''),
            season_number=data.get('season_number'),
            episode_number=data.get('episode_number'),
        )
