import xbmc
import xbmcgui
import xbmcaddon
import requests

from wcs.metadata import TMDbClient as tmdb_handler
from wcs import utils


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

    def onInit(self):
        if not self.tmdb_id:
            utils.popinfo("Chyba: TMDb ID nebylo předáno do dialogu podobných seriálů.", 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',
            'page': 1
        }
        url = f'https://api.themoviedb.org/3/tv/{self.tmdb_id}/similar'
        try:
            response = requests.get(url, params=api_params, timeout=10)
            response.raise_for_status()
            data = response.json()
            results = data.get('results', [])

            def get_year(series):
                date = series.get('first_air_date', '')
                try:
                    return int(date[:4]) if date else 0
                except Exception:
                    return 0

            results.sort(key=get_year, reverse=True)
        except Exception as e:
            from wcs.metadata.TMDbClient import handle_tmdb_api_error
            handle_tmdb_api_error(e, self.addon)
            self.close()
            return

        self.setProperty('WCS.Similar.Title', self.original_title)
        self.setProperty('WCS.Similar.MediaType', 'tv')

        if results:
            first = results[0]
            poster_path = first.get('poster_path')
            poster_url = f"https://image.tmdb.org/t/p/w342{poster_path}" if poster_path else ''
            plot = first.get('overview', '')
        else:
            poster_url = ''
            plot = ''
        self.setProperty('WCS.Similar.Poster', poster_url)
        self.setProperty('WCS.Similar.Plot', plot)

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

        list_items = []
        for series in results:
            if not series.get('id') or not series.get('name'):
                continue
            li_label = series['name']
            li = xbmcgui.ListItem(li_label)
            poster_path = series.get('poster_path')
            thumb_url = f"https://image.tmdb.org/t/p/w92{poster_path}" if poster_path else ""
            poster_url = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else ""
            art_data = {'thumb': thumb_url, 'icon': thumb_url, 'poster': poster_url}
            art_data = {k: v for k, v in art_data.items() if v}
            if art_data:
                li.setArt(art_data)
            year_str = str(series.get('first_air_date', ''))[:4] if series.get('first_air_date') else ''
            plot = series.get('overview', '')
            vote_average = series.get('vote_average')
            rating_str = f"{vote_average:.1f}" if isinstance(vote_average, (float, int)) and vote_average > 0 else ""
            info_video = {
                'plot': plot, 'plotoutline': plot, 'title': li_label,
                'originaltitle': series.get('original_name', li_label),
                'year': int(year_str) if year_str else 0,
                'rating': float(vote_average) if isinstance(vote_average, (float, int)) and vote_average > 0 else 0.0,
                'mediatype': 'tvshow'
            }
            utils.set_video_info_tag(li, info_video)
            li.setProperty('year', year_str)
            li.setProperty('tmdb_id', str(series['id']))
            if rating_str:
                li.setProperty('rating_text', rating_str)
            list_items.append(li)
        if list_items:
            panel.addItems(list_items)
            self.setFocus(panel)
            if len(list_items) > 0:
                try:
                    panel.selectItem(0)
                except Exception as e:
                    xbmc.log(f"[WCS - SimilarSeriesDialog] Error selecting item 0: {e}", xbmc.LOGERROR)
        else:
            xbmc.log(f"[WCS - SimilarSeriesDialog] No items to add to panel after processing results.", xbmc.LOGINFO)

    def onClick(self, controlID):
        if controlID == 5010 or controlID == 5000:
            panel_ctrl = self.getControl(5000)
            if not panel_ctrl:
                xbmc.log(f"[WCS - SimilarSeriesDialog] Panel control 5000 not found in onClick!", xbmc.LOGERROR)
                return
            selected_item = panel_ctrl.getSelectedItem()
            if selected_item:
                tmdb_id = selected_item.getProperty('tmdb_id')
                item_label = selected_item.getLabel()
                if tmdb_id:
                    try:
                        api_params = {
                            'api_key': tmdb_handler.get_tmdb_api_key(self.addon),
                            'language': 'cs-CZ'
                        }
                        url = f'https://api.themoviedb.org/3/tv/{tmdb_id}'
                        response = requests.get(url, params=api_params, timeout=10)
                        response.raise_for_status()
                        series_details = response.json()
                        title = series_details.get('name', item_label)
                    except:
                        title = item_label

                    dialog = xbmcgui.Dialog()
                    options = [
                        "Přidat do Moje seriály",
                        "Přidat do knihovny Kodi", 
                        "Zobrazit detaily",
                        "Zrušit"
                    ]
                    dialog_title = f"Akce: {title}"
                    choice = dialog.select(dialog_title, options)
                    if choice == 0:
                        from wcs.ui.UI import add_series_item_to_list
                        add_series_item_to_list(self.addon, tmdb_id, title)
                    elif choice == 1:
                        from wcs.library import LibraryManager as library
                        library.check_settings_and_add_item({'media_type': 'series', 'series_id': tmdb_id}, self.addon)
                    elif choice == 2:
                        detail_url = f"plugin://{self.addon.getAddonInfo('id')}?action=show_wcs_details&media_type=tv&tmdb_id={tmdb_id}"
                        xbmc.executebuiltin(f"RunPlugin({detail_url})")
                        self.close()
                    return
        elif controlID == 5001:
            pass
        else:
            xbmc.log(f"[WCS - SimilarSeriesDialog] Click on unhandled controlID: {controlID}", xbmc.LOGINFO)

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


