import xbmc
import xbmcgui
import xbmcaddon
import xbmcvfs
import os
import json

ADDON = xbmcaddon.Addon()

CHANGELOG_VERSION_PATH = xbmcvfs.translatePath("special://userdata/addon_data/plugin.video.jet_guide/changelog_version.json")
CHANGELOG_URL = "https://magnetic.website/MAD_TITAN_SPORTS/Message/update_guide.txt"

class ChangelogWindow(xbmcgui.WindowXML):
    def __init__(self, xml_file, addon_path):
        xbmc.log(f"[jet_guide] ChangelogWindow init with xml={xml_file}, path={addon_path}", xbmc.LOGINFO)
        super().__init__(xml_file, addon_path)
        self.dont_show_again = False
    
    def onInit(self):
        try:
            xbmc.log("[jet_guide] Changelog onInit started", xbmc.LOGINFO)
            current_version = ADDON.getAddonInfo('version')
            self.setProperty('version', current_version)
            # Fetch changelog text from URL
            import urllib.request
            changelog_text = ""
            headers = {'User-Agent': 'Mozilla/5.0'}
            req = urllib.request.Request(CHANGELOG_URL, headers=headers)
            changelog_cache_path = xbmcvfs.translatePath("special://userdata/addon_data/plugin.video.jet_guide/changelog_cache.txt")
            try:
                with urllib.request.urlopen(req) as response:
                    changelog_text = response.read().decode('utf-8')
                with xbmcvfs.File(changelog_cache_path, "w") as cache_file:
                    cache_file.write(changelog_text)
            except Exception as e:
                xbmc.log(f"[jet_guide] Failed to fetch changelog: {str(e)}", xbmc.LOGERROR)
                # Try to load from cache
                if xbmcvfs.exists(changelog_cache_path):
                    with xbmcvfs.File(changelog_cache_path, "r") as cache_file:
                        changelog_text = cache_file.read()
                else:
                    changelog_text = "Failed to load changelog."
            self.setProperty('changelog_text', changelog_text)
            xbmc.log("[jet_guide] Changelog onInit completed", xbmc.LOGINFO)
            self.setFocusId(9000)
            # Allow closing with ESC or BACK
            self.setAllowClose(True)
        except Exception as e:
            xbmc.log(f"[jet_guide] Error initializing changelog: {str(e)}", xbmc.LOGERROR)
    
    def onAction(self, action):
        action_id = action.getId()
        xbmc.log(f"[jet_guide] ChangelogWindow onAction: {action_id}", xbmc.LOGINFO)
        if action_id in [xbmcgui.ACTION_PREVIOUS_MENU, xbmcgui.ACTION_NAV_BACK, 92]:
            xbmc.log("[jet_guide] ChangelogWindow closing on back", xbmc.LOGINFO)
            save_dont_show_again()
            self.close()
        elif action_id in [xbmcgui.ACTION_SELECT_ITEM, xbmcgui.ACTION_MOUSE_LEFT_CLICK]:
            focused = self.getFocusId()
            if focused == 9000:
                xbmc.log("[jet_guide] ChangelogWindow close button pressed", xbmc.LOGINFO)
                save_dont_show_again()
                self.close()
            elif focused == 8000:
                # Toggle between main and other text
                if not hasattr(self, '_showing_other'):
                    self._showing_other = False
                if not self._showing_other:
                    xbmc.log("[jet_guide] Show Other Text button pressed", xbmc.LOGINFO)
                    import urllib.request
                    other_url = "https://magnetic.website/MAD_TITAN_SPORTS/Message/update_guide2.txt"
                    other_cache_path = xbmcvfs.translatePath("special://userdata/addon_data/plugin.video.jet_guide/changelog_cache2.txt")
                    other_text = ""
                    headers = {'User-Agent': 'Mozilla/5.0'}
                    req = urllib.request.Request(other_url, headers=headers)
                    try:
                        with urllib.request.urlopen(req) as response:
                            other_text = response.read().decode('utf-8')
                        with xbmcvfs.File(other_cache_path, "w") as cache_file:
                            cache_file.write(other_text)
                    except Exception as e:
                        xbmc.log(f"[jet_guide] Failed to fetch other text: {str(e)}", xbmc.LOGERROR)
                        if xbmcvfs.exists(other_cache_path):
                            with xbmcvfs.File(other_cache_path, "r") as cache_file:
                                other_text = cache_file.read()
                        else:
                            other_text = "Failed to load other text."
                    self.setProperty('changelog_text', other_text)
                    self._showing_other = True
                else:
                    xbmc.log("[jet_guide] Show Main Text button pressed", xbmc.LOGINFO)
                    # Reload main changelog text from cache or URL
                    import urllib.request
                    main_url = CHANGELOG_URL
                    main_cache_path = xbmcvfs.translatePath("special://userdata/addon_data/plugin.video.jet_guide/changelog_cache.txt")
                    main_text = ""
                    headers = {'User-Agent': 'Mozilla/5.0'}
                    req = urllib.request.Request(main_url, headers=headers)
                    try:
                        with urllib.request.urlopen(req) as response:
                            main_text = response.read().decode('utf-8')
                        with xbmcvfs.File(main_cache_path, "w") as cache_file:
                            cache_file.write(main_text)
                    except Exception as e:
                        xbmc.log(f"[jet_guide] Failed to fetch main text: {str(e)}", xbmc.LOGERROR)
                        if xbmcvfs.exists(main_cache_path):
                            with xbmcvfs.File(main_cache_path, "r") as cache_file:
                                main_text = cache_file.read()
                        else:
                            main_text = "Failed to load changelog."
                    self.setProperty('changelog_text', main_text)
                    self._showing_other = False


def get_saved_version():
    try:
        if xbmcvfs.exists(CHANGELOG_VERSION_PATH):
            with xbmcvfs.File(CHANGELOG_VERSION_PATH, "r") as f:
                data = json.loads(f.read())
                return data.get('version')
    except Exception:
        pass
    return None


def save_saved_version(version):
    try:
        with xbmcvfs.File(CHANGELOG_VERSION_PATH, "w") as f:
            json.dump({'version': version, 'dont_show': False}, f)
    except Exception as e:
        xbmc.log(f"[jet_guide] Error saving version: {str(e)}", xbmc.LOGERROR)


def save_dont_show_again():
    try:
        current_version = ADDON.getAddonInfo('version')
        with xbmcvfs.File(CHANGELOG_VERSION_PATH, "w") as f:
            json.dump({'version': current_version, 'dont_show': True}, f)
    except Exception as e:
        xbmc.log(f"[jet_guide] Error saving dont_show: {str(e)}", xbmc.LOGERROR)


def check_and_show_changelog(addon_path):
    try:
        xbmc.log("[jet_guide] check_and_show_changelog called", xbmc.LOGINFO)
        current_version = ADDON.getAddonInfo('version')
        saved = None
        if xbmcvfs.exists(CHANGELOG_VERSION_PATH):
            with xbmcvfs.File(CHANGELOG_VERSION_PATH, "r") as f:
                try:
                    saved = json.loads(f.read())
                except Exception:
                    saved = None
        show = True
        if saved and saved.get('version') == current_version and saved.get('dont_show'):
            show = False
        if show:
            xbmc.log("[jet_guide] Showing changelog window", xbmc.LOGINFO)
            win = ChangelogWindow("changelog.xml", addon_path)
            win.doModal()
            del win
            save_saved_version(current_version)
        else:
            xbmc.log("[jet_guide] Not showing changelog window (already seen)", xbmc.LOGINFO)
    except Exception as e:
        xbmc.log(f"[jet_guide] Error showing changelog: {str(e)}", xbmc.LOGERROR)


def show_changelog_from_tools(addon_path):
    try:
        xbmc.log("[jet_guide] show_changelog_from_tools called", xbmc.LOGINFO)
        win = ChangelogWindow("changelog.xml", addon_path)
        win.doModal()
        del win
    except Exception as e:
        xbmc.log(f"[jet_guide] Error showing changelog: {str(e)}", xbmc.LOGERROR)
        xbmcgui.Dialog().ok("Error", f"Failed to show changelog: {str(e)}")