# wcs/streamcinema/SCBrowser.py
"""
Stream Cinema katalog browser.
Prohlizeni obsahu SC API -- filmy, serialy, koncerty, dokumenty, anime, sport.
Pouziva SCClient._api_get() pro komunikaci s API.
"""

import xbmc
import xbmcgui
import xbmcplugin

from wcs.streamcinema.SCClient import _api_get


def _log(msg, level=xbmc.LOGINFO):
    """Logovani s prefixem."""
    xbmc.log(f"[plugin.video.milionar] SCBrowser: {msg}", level=level)


# --- API browsing ---

def browse_root(addon):
    """
    Nacte hlavni menu SC API (root /).
    
    Returns:
        list polozek menu nebo prazdny list
    """
    token = addon.getSetting('sc_auth_token')
    if not token:
        _log("Browse root failed: no auth token", level=xbmc.LOGWARNING)
        return []
    
    response = _api_get('/', params={}, auth_token=token)
    if response and 'menu' in response:
        items = response['menu']
        _log(f"Root menu: {len(items)} items")
        return items
    
    return []


def browse_path(path, addon):
    """
    Nacte obsah libovolne SC cesty.
    
    Args:
        path: SC API cesta (napr. '/FMovies/latest')
        addon: xbmcaddon instance
    
    Returns:
        dict s 'menu' a 'system' klicy, nebo None
    """
    token = addon.getSetting('sc_auth_token')
    if not token:
        _log("Browse path failed: no auth token", level=xbmc.LOGWARNING)
        return None
    
    _log(f"Browsing: {path}")
    response = _api_get(path, params={}, auth_token=token)
    
    if response and 'menu' in response:
        _log(f"Path {path}: {len(response['menu'])} items")
        return response
    
    _log(f"No menu in response for {path}", level=xbmc.LOGWARNING)
    return None


# --- Parsovani SC polozek ---

def _get_i18n(item, field, key, lang='cs'):
    """
    Ziska lokalizovanou hodnotu z i18n_info nebo i18n_art.
    Preferuje CS, fallback EN.
    
    Args:
        item: SC API polozka
        field: 'i18n_info' nebo 'i18n_art'
        key: klic (napr. 'title', 'plot', 'poster')
        lang: preferovany jazyk
    """
    i18n = item.get(field, {})
    
    # Preferovany jazyk
    value = i18n.get(lang, {}).get(key)
    if value:
        return value
    
    # Fallback na EN
    value = i18n.get('en', {}).get(key)
    if value:
        return value
    
    # Fallback na SK
    value = i18n.get('sk', {}).get(key)
    return value


def parse_sc_item(item):
    """
    Extrahuje vsechna metadata z SC API polozky do jednotneho slovniku.
    
    Args:
        item: dict z SC API (polozka z 'menu' listu)
    
    Returns:
        dict s normalizovanymi metadaty
    """
    parsed = {
        'type': item.get('type', ''),
        'id': item.get('id', ''),
        'url': item.get('url', ''),
        'select': item.get('select', False),
    }
    
    # i18n_info -- title, plot, genre, country, otitle, epname
    parsed['title'] = _get_i18n(item, 'i18n_info', 'title') or ''
    parsed['plot'] = _get_i18n(item, 'i18n_info', 'plot') or ''
    parsed['genre'] = _get_i18n(item, 'i18n_info', 'genre') or []
    parsed['country'] = _get_i18n(item, 'i18n_info', 'country') or []
    parsed['otitle'] = _get_i18n(item, 'i18n_info', 'otitle') or ''
    parsed['sorttitle'] = _get_i18n(item, 'i18n_info', 'sorttitle') or ''
    parsed['epname'] = _get_i18n(item, 'i18n_info', 'epname') or ''
    
    # i18n_art -- poster, fanart
    parsed['poster'] = _get_i18n(item, 'i18n_art', 'poster') or ''
    parsed['fanart'] = _get_i18n(item, 'i18n_art', 'fanart') or ''
    
    # art (non-i18n, napr. icon)
    art = item.get('art', {})
    parsed['icon'] = art.get('icon', '')
    
    # info -- year, rating, duration, cast, director, mpaa, studio, dateadded, mediatype
    info = item.get('info', {})
    parsed['year'] = info.get('year')
    parsed['rating'] = info.get('rating')
    parsed['duration'] = info.get('duration')
    parsed['mpaa'] = info.get('mpaa', '')
    parsed['studio'] = info.get('studio', [])
    parsed['dateadded'] = info.get('dateadded', '')
    parsed['mediatype'] = info.get('mediatype', '')
    parsed['director'] = info.get('director', [])
    
    # Serialove info
    parsed['season'] = info.get('season')
    parsed['episode'] = info.get('episode')
    parsed['tvshowtitle'] = info.get('tvshowtitle', '')
    parsed['originaltitle'] = info.get('originaltitle', '')
    
    # cast -- kompletni s thumbnaily
    parsed['cast'] = item.get('cast', [])
    
    # unique_ids -- tmdb, imdb, csfd, trakt, tvdb
    parsed['unique_ids'] = item.get('unique_ids', {})
    
    # stream_info
    stream_info = item.get('stream_info', {})
    parsed['stream_info'] = stream_info
    
    # Jazyky ze stream_info
    langs = stream_info.get('langs', {})
    parsed['langs'] = list(langs.keys()) if langs else []
    
    # Video info
    video = stream_info.get('video', {})
    if isinstance(video, dict):
        parsed['video_codec'] = video.get('codec', '')
        parsed['video_width'] = video.get('width', 0)
        parsed['video_height'] = video.get('height', 0)
        parsed['video_aspect'] = video.get('aspect', '')
    else:
        parsed['video_codec'] = ''
        parsed['video_width'] = 0
        parsed['video_height'] = 0
        parsed['video_aspect'] = ''
    
    # Audio info
    audio = stream_info.get('audio', {})
    if isinstance(audio, dict):
        parsed['audio_codec'] = audio.get('codec', '')
        parsed['audio_channels'] = audio.get('channels', 0)
    else:
        parsed['audio_codec'] = ''
        parsed['audio_channels'] = 0
    
    # Extra flags
    parsed['faudio'] = stream_info.get('faudio', '')  # napr. ATMOS
    parsed['fvideo'] = stream_info.get('fvideo', '')  # napr. 10bit
    parsed['src'] = stream_info.get('src', '')  # napr. WEB, BLURAY
    
    # Titulky
    parsed['subs'] = item.get('subs', '') or stream_info.get('subs', '')
    
    # lid (pro SC interni pouziti)
    parsed['lid'] = item.get('lid', '')
    
    return parsed


def _build_quality_label(parsed):
    """
    Vytvori kratky popis kvality z parsovane polozky.
    Napr. '1080p | CZ, EN | ATMOS'
    """
    parts = []
    
    # Rozliseni
    h = parsed.get('video_height', 0)
    if h >= 2160:
        parts.append('4K')
    elif h >= 1080:
        parts.append('1080p')
    elif h >= 720:
        parts.append('720p')
    elif h > 0:
        parts.append(f'{h}p')
    
    # Jazyky
    langs = parsed.get('langs', [])
    if langs:
        parts.append(', '.join(langs))
    
    # Extra (ATMOS, HDR, 10bit)
    extras = []
    if parsed.get('faudio'):
        extras.append(parsed['faudio'])
    if parsed.get('fvideo'):
        extras.append(parsed['fvideo'])
    if extras:
        parts.append(', '.join(extras))
    
    return ' | '.join(parts) if parts else ''


def create_list_item(parsed, addon):
    """
    Vytvori xbmcgui.ListItem s kompletnimi metadaty z parsovane SC polozky.
    
    Args:
        parsed: dict z parse_sc_item()
        addon: xbmcaddon instance
    
    Returns:
        xbmcgui.ListItem
    """
    from wcs import utils
    
    title = parsed['title']
    
    # Pokud neni title, pouzij otitle nebo originaltitle
    if not title:
        title = parsed.get('otitle') or parsed.get('originaltitle') or 'Bez názvu'
    
    listitem = xbmcgui.ListItem(label=title)
    
    # Art -- poster, fanart, icon
    art = {}
    if parsed['poster']:
        art['poster'] = parsed['poster']
        art['thumb'] = parsed['poster']
    if parsed['fanart']:
        art['fanart'] = parsed['fanart']
    if parsed['icon']:
        art['icon'] = parsed['icon']
    if art:
        listitem.setArt(art)
    
    # Video info tag
    info_dict = {
        'title': title,
        'plot': parsed['plot'],
        'mediatype': parsed['mediatype'] or 'video',
    }
    
    if parsed['year']:
        info_dict['year'] = parsed['year']
    if parsed['rating']:
        info_dict['rating'] = parsed['rating']
    if parsed['duration']:
        info_dict['duration'] = parsed['duration']
    if parsed['mpaa']:
        info_dict['mpaa'] = parsed['mpaa']
    if parsed['genre']:
        info_dict['genre'] = parsed['genre']
    if parsed['country']:
        info_dict['country'] = parsed['country']
    if parsed['director']:
        info_dict['director'] = parsed['director']
    if parsed['studio']:
        info_dict['studio'] = parsed['studio']
    if parsed['otitle']:
        info_dict['originaltitle'] = parsed['otitle']
    if parsed['sorttitle']:
        info_dict['sorttitle'] = parsed['sorttitle']
    if parsed['dateadded']:
        info_dict['dateadded'] = parsed['dateadded']
    if parsed['season'] is not None:
        info_dict['season'] = parsed['season']
    if parsed['episode'] is not None:
        info_dict['episode'] = parsed['episode']
    if parsed['tvshowtitle']:
        info_dict['tvshowtitle'] = parsed['tvshowtitle']
    
    utils.set_video_info_tag(listitem, info_dict)
    
    # Cast s thumbnaily
    if parsed['cast']:
        cast_list = []
        for c in parsed['cast']:
            actor = xbmc.Actor(
                c.get('name', ''),
                c.get('role', ''),
                c.get('order', 0),
                c.get('thumbnail', '')
            )
            cast_list.append(actor)
        if cast_list:
            video_tag = listitem.getVideoInfoTag()
            video_tag.setCast(cast_list)
    
    # Unique IDs
    if parsed['unique_ids']:
        video_tag = listitem.getVideoInfoTag()
        uid = parsed['unique_ids']
        if 'imdb' in uid:
            video_tag.setIMDBNumber(uid['imdb'])
        unique_ids = {}
        for key, val in uid.items():
            if val:
                unique_ids[key] = str(val)
        if unique_ids:
            video_tag.setUniqueIDs(unique_ids)
    
    return listitem


def enrich_with_tmdb(parsed, addon):
    """
    Obohatí parsovanou polozku o metadata z TMDb (poster, fanart, plot).
    Vola se pouze pokud mame TMDb API klic a polozka ma tmdb ID.
    
    Args:
        parsed: dict z parse_sc_item() -- modifikuje se in-place
        addon: xbmcaddon instance
    
    Returns:
        True pokud se podarilo obohatit, False jinak
    """
    tmdb_id = parsed.get('unique_ids', {}).get('tmdb')
    if not tmdb_id:
        return False
    
    # Kontrola TMDb API klice
    try:
        from wcs.metadata.TMDbClient import get_tmdb_api_key
        get_tmdb_api_key(addon)
    except (ValueError, Exception):
        return False
    
    mediatype = parsed.get('mediatype', '')
    
    try:
        if mediatype == 'movie':
            from wcs.metadata.TMDbClient import get_movie_detailed_info
            tmdb_data = get_movie_detailed_info(tmdb_id)
        elif mediatype in ('tvshow', 'episode'):
            from wcs.metadata.TMDbClient import get_series_detailed_info
            tmdb_data = get_series_detailed_info(tmdb_id)
        else:
            return False
        
        if not tmdb_data:
            return False
        
        # Doplnit chybejici poster
        if not parsed['poster'] and tmdb_data.get('poster_path'):
            parsed['poster'] = f"https://image.tmdb.org/t/p/w500{tmdb_data['poster_path']}"
        
        # Doplnit chybejici fanart
        if not parsed['fanart'] and tmdb_data.get('backdrop_path'):
            parsed['fanart'] = f"https://image.tmdb.org/t/p/original{tmdb_data['backdrop_path']}"
        
        # Doplnit chybejici plot
        if not parsed['plot'] and tmdb_data.get('overview'):
            parsed['plot'] = tmdb_data['overview']
        
        # Doplnit chybejici rating
        if not parsed['rating'] and tmdb_data.get('vote_average'):
            parsed['rating'] = tmdb_data['vote_average']
        
        _log(f"TMDb enriched: {parsed.get('title', '')[:30]} (tmdb_id={tmdb_id})")
        return True
        
    except Exception as e:
        _log(f"TMDb enrich error: {e}", level=xbmc.LOGWARNING)
        return False
