# -*- coding: utf-8 -*-
"""
Modul pro dynamickou tvorbu sjednocených kontextových menu (Context Menus).
Vyřešeno roztříštění definic do jediného místa, snadné mixování 'sad' tlačítek
a očištění názvů (bez 'mm ' prefixů).
"""

from typing import Callable, List, Dict, Any, Tuple


def style_context_label(label: Any) -> str:
    """Vizuálně odliší položky kontextového menu doplňku od systémových."""
    text = str(label or '')
    if text.startswith('[B][I]') and text.endswith('[/I][/B]'):
        return text
    return f'[B][I]{text}[/I][/B]'


def style_context_menu(items: List[Tuple[str, str]]) -> List[Tuple[str, str]]:
    """Aplikuje jednotný Kodi label markup na celé context menu."""
    styled = []
    for item in items or []:
        if isinstance(item, (list, tuple)) and len(item) >= 2:
            styled.append((style_context_label(item[0]), str(item[1])))
    return styled

def build_context_menu(get_url_fn: Callable, item_data: Dict[str, Any], contexts: List[str]) -> List[Tuple[str, str]]:
    """
    Sestaví seznam kontextových akcí na základě požadovaných kontextů (sad tlačítek).
    
    Args:
        get_url_fn: Callback funkce pro generování URL (např. trakt_module.get_url)
        item_data: Záznam s daty k položce (např. {'title': '...', 'tmdb_id': 123, ...})
        contexts: Seznam požadovaných sad tlačítek (např. ['trakt_base', 'series_manager'])
        
    Returns:
        List[Tuple[str, str]]: Vygenerovaný seznam dvojic (Label, Akce) pro xbmcgui.ListItem.addContextMenuItems
    """
    cm = []
    
    # Rozseknutí dat (univerzální bezpečné čtení z item_data)
    tmdb_id = item_data.get('tmdb_id')
    trakt_id = item_data.get('trakt_id')
    slug = item_data.get('slug')
    title = item_data.get('title') or ''
    series_name = item_data.get('series_name') or title
    season_num = item_data.get('season')
    ident = slug or (str(trakt_id) if trakt_id else '')
    media_type = item_data.get('media_type', 'movies') # default movies
    
    # ==========================================
    # 1. Sada: Trakt Base (Doplňkové Info)
    # ==========================================
    if 'trakt_base' in contexts:
        if ident or tmdb_id:
            ppl_url = get_url_fn(
                action='trakt_people',
                media_type=media_type,
                id=ident if ident else tmdb_id,
                title=title
            )
            cm.append(('Obsazení a štáb', f'Container.Update({ppl_url})'))

        if ident or tmdb_id:
            rel_url = get_url_fn(
                action='trakt_related',
                media_type=media_type,
                id=ident if ident else tmdb_id,
                page=1,
                limit=20
            )
            cm.append(('Podobné (Related)', f'Container.Update({rel_url})'))

    # ==========================================
    # 2. Sada: Trakt Watched (Označování)
    # ==========================================
    if 'trakt_watched' in contexts:
        if tmdb_id:
            mark_action = 'trakt_mark_movie' if media_type == 'movies' else 'trakt_mark_show'
            mark_url = get_url_fn(action=mark_action, tmdb_id=tmdb_id)
            cm.append(('Označit jako zhlédnuté (Trakt)', f'RunPlugin({mark_url})'))
            
        # Prmopty (Seriály)
        if tmdb_id and media_type == 'shows':
            cm.append(('Označit SERIÁL jako zhlédnutý...',
                        f'RunPlugin({get_url_fn(action="series_trakt_mark_show_prompt", tmdb_id=int(tmdb_id))})'))
            cm.append(('Označit SEZÓNU jako zhlédnutou...',
                        f'RunPlugin({get_url_fn(action="series_trakt_mark_season_prompt", tmdb_id=int(tmdb_id))})'))
            cm.append(('Označit EPIZODU jako zhlédnutou...',
                        f'RunPlugin({get_url_fn(action="series_trakt_mark_episode_prompt", tmdb_id=int(tmdb_id))})'))

        # Mazaní progressu (Historie seriálů)
        if trakt_id and media_type == 'shows':
            cm.append(('Smazat progress seriálu z Traktu',
                       f'RunPlugin({get_url_fn(action="trakt_delete_history", kind="show", trakt_id=trakt_id)})'))
            cm.append(('Smazat progress sezóny z Traktu...',
                       f'RunPlugin({get_url_fn(action="trakt_delete_history", kind="season", trakt_id=trakt_id)})'))

    # ==========================================
    # 3. Sada: Trakt Lists (Watchlisty)
    # ==========================================
    if 'trakt_watchlist_add' in contexts:
        if tmdb_id:
            add_url = get_url_fn(action='trakt_watchlist_add', tmdb_id=tmdb_id)
            cm.append(('Přidat do Watchlistu (Trakt)', f'RunPlugin({add_url})'))

    if 'trakt_watchlist_remove' in contexts:
        if tmdb_id:
            remove_url = get_url_fn(action='trakt_watchlist_remove', tmdb_id=tmdb_id)
            cm.append(('Odebrat z Watchlistu (Trakt)', f'RunPlugin({remove_url})'))

    # ==========================================
    # 4. Sada: Správce Seriálů (Series Manager)
    # ==========================================
    if 'series_manager' in contexts:
        library_enabled = False
        try:
            import xbmcaddon
            addon = xbmcaddon.Addon('plugin.video.mmirousek_v3')
            library_enabled = addon.getSettingBool('library_enabled')
        except Exception:
            library_enabled = False

        if series_name:
            # ČSFD hledá podle lidského názvu; series_name je často úložný klíč (tmdb_*).
            csfd_query = (
                (item_data.get("title") or item_data.get("show_title") or item_data.get("name") or "")
                .strip()
                or series_name
            )
            cm.append(("Aktualizovat seriál", f"RunPlugin({get_url_fn(action='series_refresh_smart', series_name=series_name)})"))
            cm.append(("Odebrat seriál", f"RunPlugin({get_url_fn(action='series_remove', series_name=series_name, tmdb_id=tmdb_id or '')})"))
            if library_enabled:
                cm.append(("Exportovat seriál do Kodi knihovny", f"RunPlugin({get_url_fn(action='series_export_selected_library', series_name=series_name)})"))
                if season_num is not None and str(season_num) != '':
                    cm.append(("Exportovat tuto sezónu do Kodi knihovny", f"RunPlugin({get_url_fn(action='series_export_season_library', series_name=series_name, season=season_num)})"))
            cm.append(("[B][I]ČSFD detail (rozšířený)[/I][/B]", f"RunPlugin({get_url_fn(action='csfd_lookup_enhanced', series_name=csfd_query, tmdb_id=tmdb_id or '', media_type='shows')})"))
            cm.append(("Stáhnout všechny sezóny", f"RunPlugin({get_url_fn(action='series_download_show', series_name=series_name)})"))
        if tmdb_id:
            cm.append(("Odeslat celý seriál na Trakt...",
                       f"RunPlugin({get_url_fn(action='series_trakt_mark_show_prompt', tmdb_id=int(tmdb_id))})"))

    # ==========================================
    # 5. Sada: Webshare hledání (WS Integrace)
    # ==========================================
    if 'webshare_search_add_queue' in contexts:
        target_path = item_data.get('target_path', '')
        file_ident = item_data.get('file_ident', '')
        file_size = item_data.get('file_size', '0')
        file_name = item_data.get('file_name', '')
        if file_ident:
            add_url = get_url_fn(action='queue_add', ident=file_ident, name=file_name,
                                 size=file_size, target_path=target_path)
            cm.append(("Přidat do fronty (Webshare)", f"RunPlugin({add_url})"))
            
            import xbmc
            if xbmc.getCondVisibility("System.Platform.Android") or xbmc.getCondVisibility("System.Platform.Windows"):
                detect_url = get_url_fn(action='webshare_detect_cz', ident=file_ident, name=file_name)
                cm.append(("Detekuj CZ (Audio/Titulky)", f"RunPlugin({detect_url})"))
            
    # Zástupný prvek pro WS Watchlist z ui_utils (ponechán odděleně nebo re-implementován)
    if 'webshare_watchlist_toggle' in contexts:
        if tmdb_id and media_type == 'movies':
            ws_add_url = get_url_fn(action='toggle_watchlist', tmdb_id=tmdb_id)
            cm.append(("Přidat do Sledovat později", f'RunPlugin({ws_add_url})'))

    # ==========================================
    # 6. Sada: TMDb Výpisy (Shows & Movies Defaults)
    # ==========================================
    if 'trakt_shows_default' in contexts:
        if tmdb_id:
            cm.append(('Označit jako zhlédnuté (Trakt)', f'RunPlugin({get_url_fn(action="trakt_mark_show", tmdb_id=tmdb_id)})'))
            cm.append(('Přidat do Watchlistu (Trakt)', f'RunPlugin({get_url_fn(action="trakt_watchlist_add", tmdb_id=tmdb_id)})'))
            cm.append(('Podobné seriály (Trakt)', f'Container.Update({get_url_fn(action="trakt_related", media_type="shows", id=tmdb_id, page=1, limit=20)})'))
            cm.append(('Obsazení a štáb', f'Container.Update({get_url_fn(action="trakt_people", media_type="shows", id=tmdb_id, title=title)})'))

    if 'trakt_movies_default' in contexts:
        if tmdb_id:
            cm.append(('Označit jako zhlédnuté (Trakt)', f'RunPlugin({get_url_fn(action="trakt_mark_movie", tmdb_id=tmdb_id)})'))
            cm.append(('Přidat do Watchlistu (Trakt)', f'RunPlugin({get_url_fn(action="trakt_watchlist_add", tmdb_id=tmdb_id)})'))
            cm.append(('Podobné filmy (Trakt)', f'Container.Update({get_url_fn(action="trakt_related", media_type="movies", id=tmdb_id, page=1, limit=20)})'))
            cm.append(('Obsazení a štáb', f'Container.Update({get_url_fn(action="trakt_people", media_type="movies", id=tmdb_id, title=title)})'))
            cm.append(("Přidat do Sledovat později", f"RunPlugin({get_url_fn(action='toggle_watchlist', tmdb_id=tmdb_id)})"))

    if 'tmdb_csfd' in contexts:
        name_for_csfd = item_data.get('movie_name') or item_data.get('series_name') or title
        if name_for_csfd:
            cm.append(("ČSFD detail (rozšířený)", f"RunPlugin({get_url_fn(action='csfd_lookup_enhanced', series_name=name_for_csfd, tmdb_id=tmdb_id or '', media_type=media_type)})"))

    # ==========================================
    # 7. Sada: System defaults & oblíbené
    # ==========================================
    if 'system_favorites_add' in contexts:
        cm.append(("Přidat do Kodi oblíbených", "Action(AddToFavorites)"))

    if 'search_history_remove' in contexts:
        search_query = item_data.get('search_query')
        if search_query:
            cm.append(("Odebrat výraz z historie", f"Container.Update({get_url_fn(action='search', remove=search_query)})"))

    # ==========================================
    # 8. Sada: Lokální historie (Local History)
    # ==========================================
    if 'local_history_item' in contexts:
        cm.append(("Smazat z historie", f"RunPlugin({get_url_fn(action='delete_history_item', tmdb_id=tmdb_id, media_type=item_data.get('media_type', 'movie'))})"))
        cm.append(("Opravit název a odeslat na Trakt", f"RunPlugin({get_url_fn(action='fix_and_scrobble_item', index=item_data.get('index', 0), media_type=item_data.get('media_type', 'movie'))})"))

    # ==========================================
    # 9. Sada: Stažené (Offline) filmy
    # ==========================================
    if 'offline_movie_item' in contexts:
        file_path = item_data.get('file_path')
        folder_path = item_data.get('folder_path')
        if file_path:
            cm.append(("Smazat soubor", f"RunPlugin({get_url_fn(action='delete_downloaded_file', path=file_path)});Container.Refresh"))
        if folder_path:
            cm.append(("Otevřít složku", f"RunPlugin({get_url_fn(action='show_folder', path=folder_path)})"))

    # ==========================================
    # 10. Sada: Sledovat později (Webshare Watchlist odebrání)
    # ==========================================
    if 'webshare_watchlist_remove' in contexts:
        if tmdb_id:
            cm.append(("Odebrat z Sledovat později", f"RunPlugin({get_url_fn(action='toggle_watchlist', tmdb_id=tmdb_id)})"))

    # ==========================================
    # 11. Sada: Fronta stahování (Download Queue)
    # ==========================================
    if 'download_queue_item' in contexts:
        queue_ident = item_data.get('queue_ident')
        if queue_ident:
            cm.append(("Spustit stahování", f"RunPlugin({get_url_fn(action='queue_start', ident=queue_ident)});Container.Refresh"))
            cm.append(("Odebrat z fronty", f"RunPlugin({get_url_fn(action='queue_remove', ident=queue_ident)});Container.Refresh"))

    # ==========================================
    # 12. Sada: Epizody v Seriálech (series/series_manager.py)
    # ==========================================
    if 'series_episode_item' in contexts:
        series_name = item_data.get('series_name')
        season_num = item_data.get('season')
        episode_num = item_data.get('episode')
        
        cm.append(("Označit jako zhlédnuté", f"RunPlugin({get_url_fn(action='series_mark_episode', series_name=series_name, season=season_num, episode=episode_num, progress=100)})"))
        cm.append(("Označit jako rozkoukané", f"RunPlugin({get_url_fn(action='series_mark_episode', series_name=series_name, season=season_num, episode=episode_num, progress=75)})"))
        cm.append(("Vymazat stav", f"RunPlugin({get_url_fn(action='series_mark_episode', series_name=series_name, season=season_num, episode=episode_num, progress=0)})"))
        cm.append(("Aktualizovat tuto epizodu (smart)", f"RunPlugin({get_url_fn(action='series_refresh_episode_smart', series_name=series_name, season=season_num, episode=episode_num)})"))
        cm.append(("Detekovat CZdab/CZtit (epizoda)", f"RunPlugin({get_url_fn(action='series_detect_cz_episode', series_name=series_name, season=season_num, episode=episode_num)})"))
        cm.append(("Smazat epizodu", f"RunPlugin({get_url_fn(action='series_remove_episode', series_name=series_name, season=season_num, episode=episode_num)})"))
        cm.append(("Přidat do fronty", f"RunPlugin({get_url_fn(action='series_download_episode', series_name=series_name, season=season_num, episode=episode_num)});Container.Refresh"))
        cm.append(("Spustit frontu", f"RunPlugin({get_url_fn(action='queue_start_all')})"))
        
        if tmdb_id:
            cm.append(("Odeslat na Trakt…", f"RunPlugin({get_url_fn(action='series_trakt_mark_episode_prompt', tmdb_id=int(tmdb_id), season=int(season_num), episode=int(episode_num))})"))

    # ==========================================
    # 13. Sada: Uložené streamy seriálu
    # ==========================================
    if 'series_saved_stream_item' in contexts:
        cm.append(("Spustit frontu", f"RunPlugin({get_url_fn(action='queue_start_all')})"))

    # ==========================================
    # 14. Sada: Stažené epizody správce
    # ==========================================
    if 'series_downloaded_manager_item' in contexts:
        path = item_data.get('path')
        sk = item_data.get('series_key')
        if sk:
            cm.append(
                (
                    "Smazat tuto epizodu",
                    f"RunPlugin({get_url_fn(action='series_offline_delete', path=path, series_key=sk)})",
                )
            )
        else:
            cm.append(
                (
                    "Smazat tuto epizodu",
                    f"RunPlugin({get_url_fn(action='series_offline_delete', path=path)})",
                )
            )

    # ==========================================
    # 14b. Sada: Manager stažených — řádek seriálu (hromadné mazání)
    # ==========================================
    if 'series_downloaded_manager_series' in contexts:
        series_key = item_data.get('series_key')
        if series_key:
            cm.append(
                (
                    "Smazat celý seriál (disk + cache)…",
                    f"RunPlugin({get_url_fn(action='series_offline_delete_series', series_key=series_key)})",
                )
            )

    # ==========================================
    # 15. Sada: Titulky.com
    # ==========================================
    def _titulky_enabled():
        try:
            import xbmcaddon

            return xbmcaddon.Addon("plugin.video.mmirousek_v3").getSettingBool(
                "titulky_enabled"
            )
        except Exception:
            try:
                import xbmcaddon

                return (
                    xbmcaddon.Addon("plugin.video.mmirousek_v3").getSetting(
                        "titulky_enabled"
                    )
                    == "true"
                )
            except Exception:
                return False

    if "titulky_episode" in contexts and _titulky_enabled():
        show = (
            item_data.get("show_title")
            or item_data.get("series_name")
            or ""
        )
        sn = item_data.get("season")
        en = item_data.get("episode")
        tid = item_data.get("tmdb_id")
        if show and sn is not None and en is not None:
            cm.append(
                (
                    "Titulky.com (tato epizoda)",
                    f"RunPlugin({get_url_fn(action='titulky_prompt', source='context', tlk_mediatype='episode', tlk_tvshow=show, tlk_season=sn, tlk_episode=en, tlk_tmdb_id=tid or '')})",
                )
            )

    if "titulky_movie" in contexts and _titulky_enabled():
        mtitle = item_data.get("movie_name") or item_data.get("title") or ""
        myear = item_data.get("year")
        tid = item_data.get("tmdb_id")
        if mtitle:
            cm.append(
                (
                    "Titulky.com (film)",
                    f"RunPlugin({get_url_fn(action='titulky_prompt', source='context', tlk_mediatype='movie', tlk_title=mtitle, tlk_year=myear or '', tlk_tmdb_id=tid or '')})",
                )
            )

    if "titulky_ws_file" in contexts and _titulky_enabled():
        fname = item_data.get("file_name") or item_data.get("fallback_title") or ""
        tid = item_data.get("tmdb_id")
        mt = item_data.get("ws_mediatype") or "movie"
        if fname:
            cm.append(
                (
                    "Titulky.com (podle názvu souboru)",
                    f"RunPlugin({get_url_fn(action='titulky_prompt', source='context', tlk_mediatype=mt, tlk_fallback=fname, tlk_tmdb_id=tid or '')})",
                )
            )

    return style_context_menu(cm)
