# -*- coding: utf-8 -*-
import xbmc
import xbmcgui
import xbmcplugin
import xbmcaddon
import sys
import urllib.parse

from resources.lib.tmdb.tmdb_module import TMDb, API_URL, IMAGE_BASE_URL_POSTER
from resources.lib.utils.log_utils import get_logger
from resources.lib.utils.context_builder import style_context_menu
from resources.lib.cache.menu_cache_server import get_menu_cache_server
from resources.lib.cache.menu_cache_config import is_cache_enabled, get_cache_ttl, log_cache_event

log = get_logger()


# Univerzální get_url z Trakt modulu (funguje všude v pluginu)
from resources.lib.trakt.trakt_module import get_url

addon_handle = int(sys.argv[1])
addon = xbmcaddon.Addon('plugin.video.mmirousek_v3')
base_url = sys.argv[0]


def _apply_video_info(li, info_labels: dict):
    """Nastaví základní video metadata přes InfoTagVideo pro Kodi Omega."""
    if not isinstance(info_labels, dict):
        return
    tag = li.getVideoInfoTag()

    title = info_labels.get('title')
    plot = info_labels.get('plot')
    aired = info_labels.get('aired')
    mediatype = info_labels.get('mediatype')
    season = info_labels.get('season')
    episode = info_labels.get('episode')

    if title:
        tag.setTitle(str(title))
    if plot:
        tag.setPlot(str(plot))
    if aired:
        try:
            tag.setFirstAired(str(aired))
        except Exception:
            pass
    if mediatype:
        try:
            tag.setMediaType(str(mediatype))
        except Exception:
            pass
    if season is not None:
        try:
            tag.setSeason(int(season))
        except Exception:
            pass
    if episode is not None:
        try:
            tag.setEpisode(int(episode))
        except Exception:
            pass

def build_url(query):
    """
    urlencode(None) by vytvořilo literál „None“ v query stringu — router pak dostane řetězec 'None'.
    """
    parts = {}
    for k, v in (query or {}).items():
        if v is None:
            continue
        if isinstance(v, str):
            s = v.strip()
            if s.lower() in ('none', 'null'):
                continue
            parts[k] = s
        else:
            parts[k] = v
    return base_url + '?' + urllib.parse.urlencode(parts, encoding='utf-8')


def show_seasons(tmdb_id, title, trakt_id=None, slug=None, fallback_title=""): # ⬅️ NOVÝ PARAMETR
    """Zobrazí sezóny seriálu + Trakt kontextové menu"""
    # log.info(f"[TMDbDetail DEBUG] show_seasons received fallback: '{fallback_title}'") # ⬅️ PŘIDAT TOTO


    # ...
    api_key = addon.getSetting('tmdb_api_key')
    if not api_key:
        xbmcgui.Dialog().ok('TMDb', 'Není nastaven TMDb API klíč v nastavení doplňku.')
        xbmcplugin.endOfDirectory(addon_handle, succeeded=False)
        return

    cache_key = f"tmdb_seasons_v1_{tmdb_id}"
    cache_server = get_menu_cache_server()

    if is_cache_enabled('tmdb_seasons'):
        cached = cache_server.get_cached_menu(cache_key)
        if cached:
            log_cache_event('HIT', 'tmdb_seasons', f"tmdb_id={tmdb_id}, {cached.get('count', 0)} items")
            directory_items = []
            for item in cached.get('items', []):
                li = xbmcgui.ListItem(item.get('label', ''))
                art = item.get('art') or {}
                info = item.get('info') or {}
                props = item.get('properties') or {}
                cm = item.get('context') or []

                if art:
                    li.setArt(art)
                if info:
                    _apply_video_info(li, info)
                for k, v in props.items():
                    li.setProperty(str(k), str(v))
                if cm:
                    cm_norm = []
                    for c in cm:
                        if isinstance(c, (list, tuple)) and len(c) >= 2:
                            cm_norm.append((str(c[0]), str(c[1])))
                    if cm_norm:
                        cm_norm = style_context_menu(cm_norm)
                        li.addContextMenuItems(cm_norm, replaceItems=True)

                directory_items.append((item.get('url', ''), li, bool(item.get('isFolder', True))))

            xbmcplugin.addDirectoryItems(addon_handle, directory_items)
            xbmcplugin.endOfDirectory(addon_handle)
            return
        else:
            log_cache_event('MISS', 'tmdb_seasons', f"tmdb_id={tmdb_id}")

    try:
        tmdb = TMDb(api_key)
        data = tmdb._call_api_raw(f"{API_URL}/tv/{tmdb_id}").json()
    except Exception as e:
        log.error(f"[TMDb] Chyba při načítání seriálu: " + str(e))
        xbmcgui.Dialog().notification('TMDb', 'Chyba při načítání seriálu', xbmcgui.NOTIFICATION_ERROR)
        xbmcplugin.endOfDirectory(addon_handle, succeeded=False)
        return

    directory_items = []
    serializable_items = []

    for season in data.get('seasons', []):
        sn = season.get('season_number')
        if sn == 0 or sn is None:
            continue

        label = f"S{sn:02d} – {season.get('name', 'Sezóna ' + str(sn))} ({season.get('episode_count', 0)} epizod)"

        url = build_url({
            'action': 'tmdb_episodes',
            'tmdb_id': tmdb_id,
            'season_num': sn,
            'title': title,
            'trakt_id': trakt_id or '',
            'slug': slug or '',
            'fallback_title': fallback_title # ⬅️ PŘEDÁNÍ DÁL
        })

        li = xbmcgui.ListItem(label)
        if season.get('poster_path'):
            poster = IMAGE_BASE_URL_POSTER + season['poster_path']
            li.setArt({'thumb': poster, 'icon': poster, 'poster': poster})

        _apply_video_info(li, {
            'plot': season.get('overview') or '',
            'season': sn,
            'mediatype': 'season',
            'title': season.get('name')
        })

        # KONEXT MENU – pro celý seriál
        from resources.lib.utils.context_builder import build_context_menu
        item_data = {
            'series_name': title,
            'tmdb_id': int(tmdb_id),
            'trakt_id': int(trakt_id) if trakt_id else None,
            'slug': slug
        }
        context = build_context_menu(get_url, item_data, contexts=['trakt_shows_progress'])
        
        if context:
            li.addContextMenuItems(context, replaceItems=True)

        li.setProperty('IsPlayable', 'false')
        directory_items.append((url, li, True))
        serializable_items.append((
            url,
            label,
            True,
            {
                'plot': season.get('overview') or '',
                'season': sn,
                'mediatype': 'season',
                'title': season.get('name')
            },
            {
                'thumb': (IMAGE_BASE_URL_POSTER + season['poster_path']) if season.get('poster_path') else '',
                'icon': (IMAGE_BASE_URL_POSTER + season['poster_path']) if season.get('poster_path') else '',
                'poster': (IMAGE_BASE_URL_POSTER + season['poster_path']) if season.get('poster_path') else ''
            },
            {'IsPlayable': 'false'},
            context if context else [],
            False,
        ))

    if is_cache_enabled('tmdb_seasons') and serializable_items:
        cache_server.cache_menu(cache_key, serializable_items, get_cache_ttl('tmdb_seasons'))

    xbmcplugin.addDirectoryItems(addon_handle, directory_items)

    xbmcplugin.endOfDirectory(addon_handle)


def show_episodes(tmdb_id, season_num, title, trakt_id=None, slug=None, fallback_title=""): # ⬅️ NOVÝ PARAMETR
    """Zobrazí epizody sezóny + plné Trakt kontextové menu včetně označení epizody"""
    # log.info(f"[TMDbDetail DEBUG] show_episodes received fallback: '{fallback_title}'")
    
    cache_server = get_menu_cache_server()
    cache_key = f"tmdb_episodes_v2_{tmdb_id}_{season_num}_{fallback_title or title or ''}"
    
    if is_cache_enabled('tmdb_episodes'):
        cached = cache_server.get_cached_menu(cache_key)
        if cached:
            log_cache_event('HIT', 'tmdb_episodes', f"S{season_num}, {cached['count']} items")
            directory_items = []
            for item in cached.get('items', []):
                li = xbmcgui.ListItem(item.get('label', ''))
                art = item.get('art') or {}
                info = item.get('info') or {}
                props = item.get('properties') or {}
                cm = item.get('context') or []

                if art:
                    li.setArt(art)
                if info:
                    _apply_video_info(li, info)
                for k, v in props.items():
                    li.setProperty(str(k), str(v))
                if cm:
                    cm_norm = []
                    for c in cm:
                        if isinstance(c, (list, tuple)) and len(c) >= 2:
                            cm_norm.append((str(c[0]), str(c[1])))
                    if cm_norm:
                        cm_norm = style_context_menu(cm_norm)
                        li.addContextMenuItems(cm_norm, replaceItems=True)

                directory_items.append((item.get('url', ''), li, bool(item.get('isFolder', True))))

            xbmcplugin.addDirectoryItems(addon_handle, directory_items)
            xbmcplugin.endOfDirectory(addon_handle)
            return
        else:
            log_cache_event('MISS', 'tmdb_episodes', f"S{season_num}")

    api_key = addon.getSetting('tmdb_api_key')
    try:
        tmdb = TMDb(api_key)
        data = tmdb._call_api_raw(f"{API_URL}/tv/{tmdb_id}/season/{season_num}").json()
    except Exception as e:
        log.error(f"[TMDb] Chyba při načítání sezóny {season_num}: {e}")
        xbmcgui.Dialog().notification('TMDb', 'Chyba při načítání epizod', xbmcgui.NOTIFICATION_ERROR)
        xbmcplugin.endOfDirectory(addon_handle, succeeded=False)
        return


    # Bezpečné přetypování vstupu z URL parametrů
    try:
        season_num_int = int(season_num)
    except (ValueError, TypeError):
        season_num_int = 0

    # === Collect items for caching ===
    directory_items = []
    serializable_items = []
    
    for ep in data.get('episodes', []):
        try:
            en = int(ep.get('episode_number', 0))
        except (ValueError, TypeError):
            en = 0
            
        name = ep.get('name') or f"Epizoda {en}"
        air_date = ep.get('air_date', '')

        label = f"S{season_num_int:02d}E{en:02d} – {name}"
        if air_date:
            label += f"  •  {air_date.split('-')[0] if '-' in air_date else air_date}"

        # Primární název seriálu je v proměnné 'title'
        primary_title = title 
        # 2. Sestavení URL
        url_params = {'action': 'series_search', 'what': primary_title, 'tmdb_id': tmdb_id}

        # 🎯 OPRAVENÁ LOGIKA: Povolíme fallback i tehdy, když se shoduje s primárním názvem.
        # Důvod: Primární název (title) se v series_ui.py zkoriguje na špatnou transliteraci ('cinaehaneun X'),
        # proto potřebujeme 'Dear X' jako zálohu.
        ft = str(fallback_title or '').strip()
        if ft and ft.lower() not in ('none', 'null'):
            url_params['fallback_series_name'] = ft
            
        url = build_url(url_params)

        li = xbmcgui.ListItem(label)

        if ep.get('still_path'):
            still = IMAGE_BASE_URL_POSTER + ep['still_path']
            li.setArt({'thumb': still, 'icon': still})

        _apply_video_info(li, {
            'title': name,
            'plot': ep.get('overview') or '',
            'aired': air_date,
            'season': season_num_int,
            'episode': en,
            'mediatype': 'episode'
        })

        # RYCHLÉ OZNAČENÍ EPIZODY a Plný Trakt kontext (watchlist, related, mazání progressu…)
        from resources.lib.utils.context_builder import build_context_menu
        item_data = {
            'series_name': title,
            'tmdb_id': int(tmdb_id),
            'trakt_id': int(trakt_id) if trakt_id else None,
            'season': season_num_int,
            'episode': en,
            'slug': slug
        }
        context_items = build_context_menu(get_url, item_data, contexts=['trakt_episode_progress'])

        if context_items:
            li.addContextMenuItems(context_items, replaceItems=True)

        li.setProperty('IsPlayable', 'false')
        directory_items.append((url, li, True))
        serializable_items.append((
            url,
            label,
            True,
            {
                'title': name,
                'plot': ep.get('overview') or '',
                'aired': air_date,
                'season': season_num_int,
                'episode': en,
                'mediatype': 'episode'
            },
            {
                'thumb': (IMAGE_BASE_URL_POSTER + ep['still_path']) if ep.get('still_path') else '',
                'icon': (IMAGE_BASE_URL_POSTER + ep['still_path']) if ep.get('still_path') else ''
            },
            {'IsPlayable': 'false'},
            context_items if context_items else [],
            False,
        ))

    # === MENU CACHE: Save to cache and render ===
    if is_cache_enabled('tmdb_episodes') and serializable_items:
        cache_server.cache_menu(cache_key, serializable_items, get_cache_ttl('tmdb_episodes'))
    
    xbmcplugin.addDirectoryItems(addon_handle, directory_items)
    xbmcplugin.endOfDirectory(addon_handle)
