import xbmc
import xbmcgui
import xbmcaddon
import requests

from wcs.metadata import TMDbClient as tmdb_handler
from wcs.ui import UI as ui


class SeriesCreatorsDialog(xbmcgui.WindowXMLDialog):
    def __init__(self, xmlFilename, addonPath, skin="Default", theme="Default", tmdb_id=None, title=None):
        super(SeriesCreatorsDialog, self).__init__()
        self.tmdb_id = tmdb_id
        self.title = title or ''
        self.addon = xbmcaddon.Addon()

    def onInit(self):
        if not self.tmdb_id:
            ui.popinfo("Chyba: TMDb ID nebylo předáno do dialogu tvůrců.", self.addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_ERROR)
            self.close()
            return
        api_params = {
            'api_key': tmdb_handler.get_tmdb_api_key(self.addon),
            'language': 'cs-CZ'
        }
        url = f'https://api.themoviedb.org/3/tv/{self.tmdb_id}'
        try:
            response = requests.get(url, params=api_params, timeout=10)
            response.raise_for_status()
            data = response.json()
            creators = data.get('created_by', [])
        except Exception as e:
            from wcs.metadata.TMDbClient import handle_tmdb_api_error
            handle_tmdb_api_error(e, self.addon)
            self.close()
            return

        if not creators:
            ui.popinfo(f"Seriál '{self.title}' nemá v databázi TMDb uvedeny žádné tvůrce.", self.addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_INFO)
            self.close()
            return

        self.setProperty('WCS.Actor.Title', f"Tvůrci seriálu: {self.title}")
        self.setProperty('WCS.Actor.Name', f"Tvůrci seriálu: {self.title}")
        self.setProperty('WCS.Actor.Character', f"Počet tvůrců: {len(creators)}")
        self.setProperty('WCS.Actor.MediaType', 'tv')

        if creators:
            first_creator = creators[0]
            profile_path = first_creator.get('profile_path')
            if profile_path:
                photo_url = f"https://image.tmdb.org/t/p/w500{profile_path}"
                self.setProperty('WCS.Actor.Photo', photo_url)
            else:
                self.setProperty('WCS.Actor.Photo', '')
            creator_id = first_creator.get('id')
            if creator_id:
                try:
                    person_url = f'https://api.themoviedb.org/3/person/{creator_id}'
                    person_response = requests.get(person_url, params=api_params, timeout=10)
                    person_response.raise_for_status()
                    person_data = person_response.json()
                    biography = person_data.get('biography', '') or f"Tvůrce seriálu '{self.title}'. Další informace o této osobě nejsou v databázi TMDb dostupné."
                    self.setProperty('WCS.Actor.Biography', biography)
                    self.setProperty('WCS.Actor.Bio', biography)
                except Exception:
                    fallback_bio = f"Tvůrce seriálu '{self.title}'. Další informace o této osobě nejsou v databázi TMDb dostupné."
                    self.setProperty('WCS.Actor.Biography', fallback_bio)
                    self.setProperty('WCS.Actor.Bio', fallback_bio)
            else:
                fallback_bio = f"Tvůrce seriálu '{self.title}'. Další informace o této osobě nejsou v databázi TMDb dostupné."
                self.setProperty('WCS.Actor.Biography', fallback_bio)
                self.setProperty('WCS.Actor.Bio', fallback_bio)

        panel = self.getControl(5000)
        if not panel:
            xbmc.log(f"{self.addon.getAddonInfo('id')}: Panel s ID 5000 nebyl nalezen v DialogActorDetails.xml", xbmc.LOGERROR)
            self.close()
            return
        panel.reset()
        list_items = []

        if creators:
            first_creator = creators[0]
            creator_photo = ''
            profile_path = first_creator.get('profile_path')
            if profile_path:
                creator_photo = f"https://image.tmdb.org/t/p/w185{profile_path}"
            game_item = xbmcgui.ListItem(label="Hrát hru s tvůrci")
            game_item.setArt({'thumb': creator_photo or 'DefaultActor.png', 'icon': creator_photo or 'DefaultActor.png', 'poster': creator_photo or 'DefaultActor.png'})
            game_item.setProperty('is_start_creator_game', '1')
            game_item.setProperty('tmdb_id', str(first_creator['id']))
            list_items.append(game_item)

        for creator in creators:
            if not creator.get('id') or not creator.get('name'):
                continue
            li_label = creator['name']
            li = xbmcgui.ListItem(li_label)
            profile_path = creator.get('profile_path')
            thumb_url = f"https://image.tmdb.org/t/p/w185{profile_path}" if profile_path else "DefaultActor.png"
            poster_url = f"https://image.tmdb.org/t/p/w500{profile_path}" if profile_path else "DefaultActor.png"
            li.setArt({'thumb': thumb_url, 'icon': thumb_url, 'poster': poster_url})
            li.setLabel2("Tvůrce")
            li.setProperty('tmdb_id', str(creator['id']))
            li.setProperty('known_for_department', creator.get('known_for_department', ''))
            list_items.append(li)

        if list_items:
            panel.addItems(list_items)
            self.setFocus(panel)
            try:
                panel.selectItem(0)
            except Exception as e:
                xbmc.log(f"[WCS - SeriesCreatorsDialog] Error selecting item 0: {e}", xbmc.LOGERROR)

    def onClick(self, controlID):
        if controlID == 5000:
            panel_ctrl = self.getControl(5000)
            if not panel_ctrl:
                return
            selected_item = panel_ctrl.getSelectedItem()
            if selected_item:
                if selected_item.getProperty('is_start_creator_game') == '1':
                    from wcs.games.DialogWcsTextGame import TextGameWindow
                    api_params = {
                        'api_key': tmdb_handler.get_tmdb_api_key(self.addon),
                        'language': 'cs-CZ'
                    }
                    url = f'https://api.themoviedb.org/3/tv/{self.tmdb_id}'
                    try:
                        response = requests.get(url, params=api_params, timeout=10)
                        response.raise_for_status()
                        data = response.json()
                        creators = data.get('created_by', [])
                    except Exception:
                        ui.popinfo("Nepodařilo se načíst detaily tvůrců.", self.addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_ERROR)
                        return
                    if not creators:
                        ui.popinfo("Žádní tvůrci nejsou dostupní.", self.addon.getAddonInfo('name'), icon=xbmcgui.NOTIFICATION_ERROR)
                        return
                    creator_names = [creator.get('name', '') for creator in creators if creator.get('name')]
                    if len(creator_names) == 1:
                        game_title = f"{creator_names[0]} (tvůrce: {self.title})"
                    else:
                        game_title = f"{', '.join(creator_names)} (tvůrci: {self.title})"
                    first_creator = creators[0]
                    profile_path = first_creator.get('profile_path')
                    fanart_url = f"https://image.tmdb.org/t/p/w780{profile_path}" if profile_path else ''
                    combined_bio = ""
                    for creator in creators:
                        creator_name = creator.get('name', '')
                        if creator_name:
                            creator_id = creator.get('id')
                            if creator_id:
                                try:
                                    creator_data = tmdb_handler.get_actor_details(creator_id)
                                    if creator_data and creator_data.get('biography'):
                                        bio = creator_data.get('biography', '')
                                        if bio:
                                            combined_bio += f"{creator_name}: {bio[:200]}{'...' if len(bio) > 200 else ''}\n\n"
                                except Exception:
                                    pass
                    if not combined_bio:
                        combined_bio = f"Tvůrci seriálu '{self.title}': {', '.join(creator_names)}"
                    window = TextGameWindow(
                        "games/DialogWcsTextGame.xml",
                        self.addon.getAddonInfo('path'),
                        "Default",
                        title=game_title,
                        fanart=fanart_url,
                        plot=combined_bio[:500],
                        genre='',
                        media_type='creator',
                        actor_data={'name': ', '.join(creator_names), 'biography': combined_bio},
                        banner_fanart=fanart_url,
                        episode_title="",
                        season_number=None,
                        episode_number=None
                    )
                    window.doModal()
                    del window
                    return
                creator_id = selected_item.getProperty('tmdb_id')
                creator_name = selected_item.getLabel()
                if creator_id and creator_name:
                    creator_url = f"plugin://{self.addon.getAddonInfo('id')}?action=display_actor_dialog&actor_id={creator_id}&actor_name={creator_name}&person_type=creator&media_type=tv"
                    xbmc.executebuiltin(f"RunPlugin({creator_url})")
        elif controlID == 5001:
            self.close()

    def onAction(self, action):
        if action.getId() == xbmcgui.ACTION_NAV_BACK or action.getId() == xbmcgui.ACTION_PREVIOUS_MENU:
            self.close()


