# wcs/ai/PlaylistBuilder.py
"""
Centrální modul pro sestavování playlist URL a ListItem pro MyTV/MyCinema.
Eliminuje duplicitní kód v DialogMyTV.py (dříve 5 míst se stejnou logikou).
"""

import xbmcgui
from urllib.parse import quote_plus


def build_playlist_url(addon_id, item_data, channel_id=''):
    """Sestaví plugin URL pro playlist item.
    
    Args:
        addon_id: ID addonu (z addon.getAddonInfo('id'))
        item_data: Dict s metadaty epizody (standardizovaný formát)
        channel_id: ID kanálu pro progress tracking (prázdné = bez trackingu)
    
    Returns:
        str: Plugin URL pro playlist
    """
    return (
        f"plugin://{addon_id}?action=play_episode_from_addon_playlist"
        f"&series_name={quote_plus(str(item_data.get('series_name', '')))}"
        f"&season_number={item_data.get('season', '')}"
        f"&episode_number={item_data.get('episode', '')}"
        f"&tmdb_id={item_data.get('tmdb_id', '')}"
        f"&episode_title={quote_plus(str(item_data.get('episode_title', '')))}"
        f"&plot={quote_plus(str(item_data.get('plot', '')))}"
        f"&rating={quote_plus(str(item_data.get('rating', '')))}"
        f"&poster={quote_plus(str(item_data.get('poster', '')))}"
        f"&fanart={quote_plus(str(item_data.get('fanart', '')))}"
        f"&genre={quote_plus(str(item_data.get('genre', '')))}"
        f"&year={quote_plus(str(item_data.get('year', '')))}"
        f"&episode_thumb={quote_plus(str(item_data.get('episode_thumb', '')))}"
        f"&mytv_channel_id={quote_plus(str(channel_id))}"
    )


def build_playlist_listitem(item_data):
    """Vytvoří xbmcgui.ListItem pro playlist z item_data dict.
    
    Args:
        item_data: Dict s metadaty epizody
    
    Returns:
        xbmcgui.ListItem: Připravený pro playlist
    """
    series_name = item_data.get('series_name', '')
    season = item_data.get('season', 0)
    episode = item_data.get('episode', 0)
    year = item_data.get('year', '')
    episode_title = item_data.get('episode_title', '')
    
    li = xbmcgui.ListItem(label=series_name)
    
    # Bezpečná konverze na int
    try:
        year_int = int(year) if year else 0
    except (ValueError, TypeError):
        year_int = 0
    try:
        season_int = int(season) if season else 0
    except (ValueError, TypeError):
        season_int = 0
    try:
        episode_int = int(episode) if episode else 0
    except (ValueError, TypeError):
        episode_int = 0
    
    li.setInfo('video', {
        'title': episode_title,
        'plot': item_data.get('plot', ''),
        'year': year_int,
        'premiered': str(year),
        'mediatype': 'episode',
        'season': season_int,
        'episode': episode_int,
        'tvshowtitle': series_name
    })
    
    poster = item_data.get('poster', '')
    fanart = item_data.get('fanart', '')
    thumb = item_data.get('episode_thumb', '') or poster
    
    li.setArt({
        'poster': poster,
        'fanart': fanart,
        'thumb': thumb
    })
    
    return li


def extract_item_data(list_item):
    """Extrahuje standardizovaný item_data dict z xbmcgui.ListItem.
    
    Args:
        list_item: Existující xbmcgui.ListItem s nastavenými properties
    
    Returns:
        dict: Standardizovaný item_data dict
    """
    return {
        'series_name': list_item.getProperty('series_name') or '',
        'season': list_item.getProperty('season') or '',
        'episode': list_item.getProperty('episode') or '',
        'tmdb_id': list_item.getProperty('tmdb_id') or '',
        'episode_title': list_item.getProperty('episode_title') or '',
        'plot': list_item.getProperty('plot') or '',
        'rating': list_item.getProperty('rating') or '',
        'poster': list_item.getProperty('poster') or '',
        'fanart': list_item.getProperty('fanart') or '',
        'genre': list_item.getProperty('genre') or '',
        'year': list_item.getProperty('year') or '',
        'episode_thumb': list_item.getArt('thumb') or '',
    }


def extract_from_tmdb_meta(next_meta, series_name='', series_id=''):
    """Extrahuje standardizovaný item_data dict z TMDb next_meta.
    
    Args:
        next_meta: Dict z TMDbClient.get_next_episode_from_tmdb()
        series_name: Název seriálu
        series_id: TMDb ID seriálu
    
    Returns:
        dict: Standardizovaný item_data dict
    """
    return {
        'series_name': series_name,
        'season': next_meta.get('season', ''),
        'episode': next_meta.get('episode', ''),
        'tmdb_id': str(series_id),
        'episode_title': next_meta.get('episode_title', ''),
        'plot': next_meta.get('plot', ''),
        'rating': str(next_meta.get('rating', '')),
        'poster': next_meta.get('poster', ''),
        'fanart': next_meta.get('fanart', ''),
        'genre': next_meta.get('genre', ''),
        'year': str(next_meta.get('year', '')),
        'episode_thumb': next_meta.get('still', next_meta.get('episode_thumb', '')),
    }
