import xbmc
import xbmcgui
import xbmcaddon
import requests

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


class SimilarMoviesDialog(xbmcgui.WindowXMLDialog):
    def __init__(self, xmlFilename, addonPath, skin="Default", theme="Default", tmdb_id=None, original_title=None):
        super(SimilarMoviesDialog, 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:
            ui.popinfo("Chyba: TMDb ID nebylo předáno do dialogu podobných filmů.", 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/movie/{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(movie):
                date = movie.get('release_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', 'movie')

        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 movie in results:
            if not movie.get('id') or not movie.get('title'):
                continue
            li_label = movie['title']
            li = xbmcgui.ListItem(li_label)
            poster_path = movie.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(movie.get('release_date', ''))[:4] if movie.get('release_date') else ''
            plot = movie.get('overview', '')
            vote_average = movie.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': movie.get('original_title', 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,
            }
            utils.set_video_info_tag(li, info_video)
            li.setProperty('year', year_str)
            li.setProperty('tmdb_id', str(movie['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 - SimilarMoviesDialog] Error selecting item 0: {e}", xbmc.LOGERROR)
        else:
            xbmc.log(f"[WCS - SimilarMoviesDialog] 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 - SimilarMoviesDialog] 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:
                    movie_details = tmdb_handler.get_movie_detailed_info(tmdb_id)
                    title = movie_details.get('title', item_label)
                    dialog = xbmcgui.Dialog()
                    options = [
                        "Přidat do Moje filmy",
                        "Přidat do knihovny Kodi",
                        "Zobrazit detaily",
                        "Přehrát",
                        "Zrušit"
                    ]
                    dialog_title = f"Akce: {title}"
                    choice = dialog.select(dialog_title, options)
                    if choice == 0:
                        from wcs.ui.UI import add_movie_item_to_list
                        add_movie_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': 'movie', 'movie_id': tmdb_id}, self.addon)
                    elif choice == 2:
                        detail_url = f"plugin://{self.addon.getAddonInfo('id')}?action=show_wcs_details&media_type=movie&tmdb_id={tmdb_id}"
                        xbmc.executebuiltin(f"RunPlugin({detail_url})")
                        self.close()
                    elif choice == 3:
                        title = item_label or ''
                        year = selected_item.getProperty('year') or ''
                        poster = selected_item.getArt('poster') or ''
                        fanart = ''
                        rating = selected_item.getProperty('rating_text') or ''
                        genre = ''
                        director = ''
                        runtime = ''
                        plot = selected_item.getProperty('plot') or ''
                        search_and_play_movie(title, year, plot, poster, fanart, rating, genre, director, runtime, self.addon)
                    return
        elif controlID == 5001:
            pass
        else:
            xbmc.log(f"[WCS - SimilarMoviesDialog] 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()


