# -*- coding: utf-8 -*-
import re
import xbmc

class SeriesEnricher:
    """
    Handles TMDb metadata enrichment for series and episodes.
    """

    def __init__(self, addon=None):
        self.addon = addon

    def enrich_with_tmdb(self, series_data: dict, series_name: str):
        """
        Doplní detail seriálu (poster/backdrop/overview + show_runtime) a metadata epizod.
        """
        try:
            from resources.lib.tmdb import tmdb_utils as TM
        except Exception:
            TM = None

        # 1) Najdi/ověř show ID (přes search)
        if not series_data.get('tmdb') or not series_data['tmdb'].get('id'):
            tv_meta = None
            try:
                if TM and hasattr(TM, 'search_tmdb_tv'):
                    tv_meta = TM.search_tmdb_tv(series_name)
            except Exception:
                tv_meta = None
            if tv_meta:
                series_data.setdefault('tmdb', {})
                series_data['tmdb'].update({
                    "id": tv_meta.get("tmdb_id"),
                    "title": tv_meta.get("title"),
                    "original_title": tv_meta.get("original_title") or tv_meta.get("title"),
                    "year": tv_meta.get("year"),
                })
                series_data['name'] = tv_meta.get("title") or series_name

        tv_id = series_data.get('tmdb', {}).get('id')
        if not tv_id:
            return

        # 2) Detaily seriálu: get_tv_show_meta → show_runtime + poster/backdrop/overview
        show_meta = None
        if TM and hasattr(TM, 'get_tv_show_meta'):
            try:
                show_meta = TM.get_tv_show_meta(tv_id=int(tv_id), language='cs')
            except Exception:
                show_meta = None

        poster_path   = show_meta.get('poster_path')   if show_meta else None
        backdrop_path = show_meta.get('backdrop_path') if show_meta else None
        overview      = show_meta.get('overview')      if show_meta else None
        rt            = show_meta.get('episode_run_time') if show_meta else None
        show_title    = ((show_meta or {}).get('title') or (show_meta or {}).get('name') or '').strip()
        original_name = ((show_meta or {}).get('original_title') or (show_meta or {}).get('original_name') or '').strip()

        if isinstance(rt, list) and rt:
            show_runtime = int(rt[0]) if isinstance(rt[0], (int, float)) else None
        elif isinstance(rt, int):
            show_runtime = rt
        else:
            show_runtime = None
        
        # Zjišťujeme celkový počet sezón
        num_seasons = show_meta.get('number_of_seasons') if show_meta else None
        tmdb_seasons_data = {}
        
        if num_seasons and int(num_seasons) >= 1:
            for s_num in range(1, int(num_seasons) + 1):
                s_num_str = str(s_num)
                try:
                    season_meta = TM.get_tv_season_meta(int(tv_id), s_num, language='cs') or {}
                    episode_count = season_meta.get('episode_count')
                    if episode_count and int(episode_count) > 0:
                        tmdb_seasons_data[s_num_str] = {'episode_count': episode_count}
                except Exception:
                    continue

        # Získání IMDb ID
        imdb_id = None
        if TM and hasattr(TM, 'get_tv_external_ids'):
            try:
                ext_ids = TM.get_tv_external_ids(tv_id=int(tv_id))
                imdb_id = ext_ids.get('imdb_id')
            except Exception:
                imdb_id = None

        img_base_poster = "https://image.tmdb.org/t/p/w500"
        img_base_fanart = "https://image.tmdb.org/t/p/original"

        series_tm = series_data.setdefault('tmdb', {})
        series_tm.update({
            "title": show_title or series_tm.get("title"),
            "original_title": original_name or show_title or series_tm.get("original_title"),
            "poster": poster_path,
            "backdrop": backdrop_path,
            "poster_url": (img_base_poster + poster_path) if poster_path else None,
            "backdrop_url": (img_base_fanart + backdrop_path) if backdrop_path else None,
            "overview": overview,
            "show_runtime": show_runtime,
            "imdb_id": imdb_id
        })
        current_name = (series_data.get('name') or '').strip()
        if show_title and (not current_name or re.match(r'^tmdb_\d+$', current_name, re.IGNORECASE)):
            series_data['name'] = show_title
        if tmdb_seasons_data:
            series_tm['seasons'] = tmdb_seasons_data

        # 3) Epizody – title/overview/still_url/air_date/vote/runtime (+name)
        for s in list(series_data['seasons'].keys()):
            for e in list(series_data['seasons'][s].keys()):
                ep = series_data['seasons'][s][e]
                if ep.get('locked'):
                    continue
                ep.setdefault('tmdb', {})
                ep_meta = None
                if TM and hasattr(TM, 'get_tv_episode_meta'):
                    try:
                        ep_meta = TM.get_tv_episode_meta(tv_id=int(tv_id), season=int(s), episode=int(e), language='cs')
                    except Exception:
                        ep_meta = None
                if ep_meta:
                    ep_title   = ep_meta.get('title')
                    ep_overview= ep_meta.get('overview')
                    ep_still   = ep_meta.get('still_url') or None
                    ep_air     = ep_meta.get('air_date')
                    ep_vote    = ep_meta.get('vote')
                    ep_runtime = ep_meta.get('runtime')
                    if (ep_runtime is None or (isinstance(ep_runtime, int) and ep_runtime <= 0)) and isinstance(show_runtime, int) and show_runtime > 0:
                        ep_runtime = show_runtime
                    ep['tmdb'] = {
                        "episode_id": ep_meta.get("episode_id"),
                        "title": ep_title,
                        "overview": ep_overview,
                        "still_path": ep_meta.get('still_path'),
                        "still_url": ep_still,
                        "air_date": ep_air,
                        "vote": ep_vote,
                        "runtime": ep_runtime
                    }
                    if ep_title:
                        ep['title'] = ep_title
                        ep['name']  = ep_title
                    else:
                        if not ep.get('name'):
                            ep['name'] = ep.get('source_name') or ep.get('title') or ''
                else:
                    if not ep.get('name'):
                        ep['name'] = ep.get('title') or ep.get('source_name') or ''

    def populate_tmdb_placeholders(self, series_data: dict, tv_id: int, language: str = 'cs', recalc_callback=None):
        """
        Vytvoří (nebo doplní) placeholdery epizod podle TMDb pro všechny sezóny.
        """
        try:
            from resources.lib.tmdb import tmdb_utils as TM
        except Exception:
            return

        if not tv_id:
            return

        show_meta = TM.get_tv_show_meta(tv_id=int(tv_id), language=language)
        if not show_meta:
            return

        num_seasons = show_meta.get('number_of_seasons') or 0
        if num_seasons <= 0:
            return

        series_data.setdefault('seasons', {})

        for s_idx in range(1, num_seasons + 1):
            s_key = str(s_idx)
            season_meta = TM.get_tv_season_meta(tv_id, s_idx, language=language)
            if not season_meta or not season_meta.get('episodes'):
                continue

            series_data['seasons'].setdefault(s_key, {})
            
            for ep_meta in season_meta['episodes']:
                e_num = ep_meta.get('episode_number')
                if not e_num:
                    continue
                e_key = str(e_num)
                
                ep_entry = series_data['seasons'][s_key].setdefault(e_key, {
                    'season': s_idx,
                    'episode': e_num,
                    'watched': False,
                    'streams': []
                })

                if ep_entry.get('locked'):
                    continue

                ep_title = ep_meta.get('name')
                ep_entry['tmdb'] = {
                    "episode_id": ep_meta.get("id"),
                    "title": ep_title,
                    "overview": ep_meta.get('overview'),
                    "still_path": ep_meta.get('still_path'),
                    "air_date": ep_meta.get('air_date'),
                    "vote": ep_meta.get('vote_average'),
                    "runtime": ep_meta.get('runtime')
                }
                if ep_title:
                    ep_entry['title'] = ep_title
                    ep_entry['name'] = ep_title

            # Přepočet stavu sezóny
            if recalc_callback:
                recalc_callback(series_data, s_key)
