import json
import os
import time

import xbmc
import xbmcgui
import xbmcvfs

from tools import debug_log
from analytics import track

JET_GUIDE_IMPORTED_PATH = xbmcvfs.translatePath(
    "special://userdata/addon_data/plugin.video.jet_guide/jet_guide_imported.json"
)


def play_saved_jet_guide_link(link):
    """Play a saved JetGuide link"""
    if isinstance(link, str) and (link.startswith("http") or link.endswith(".m3u8") or link.startswith("plugin://")):
        track(event="play", url=link, source="saved_link")
        xbmc.Player().play(link)
    else:
        debug_log(f"JetGuide DEBUG: Not playable. Link: {link}", xbmc.LOGERROR)
        xbmcgui.Dialog().ok("Error", f"This link is not a direct playable stream.\n\nLink: {link}")


def save_link_to_jet_guide(link_obj):
    # Base folder for custom folders
    folders_base_path = "special://userdata/addon_data/plugin.video.jet_guide/jet_guide_folders"

    dialog = xbmcgui.Dialog()
    choices = ["Create new folder", "Add to existing folder", "Add to jet_guide_imported"]
    choice = dialog.select("Save link - Choose destination", choices)

    if choice == 0:  # Create new folder
        suggested_name = link_obj.get("title", "New Folder")
        folder_name = dialog.input("Enter folder name", defaultt=suggested_name)
        if not folder_name:
            return
        folder_path = xbmcvfs.translatePath(folders_base_path + "/" + folder_name)
        if not xbmcvfs.exists(folder_path):
            xbmcvfs.mkdirs(folder_path)
        links_file = folder_path + "/links.json"
        try:
            if xbmcvfs.exists(links_file):
                with xbmcvfs.File(links_file, "r") as f:
                    links = json.loads(f.read())
            else:
                links = []
        except Exception:
            links = []
        links = [l for l in links if isinstance(l, dict) and "title" in l and "link" in l]
        if isinstance(link_obj, dict) and not any(l.get("link") == link_obj["link"] for l in links):
            links.append(link_obj)
            with xbmcvfs.File(links_file, "w") as f:
                f.write(json.dumps(links, indent=2))
        return

    elif choice == 1:  # Add to existing folder
        debug_log(f"DEBUG: FOLDERS_BASE_PATH={folders_base_path}", level=xbmc.LOGINFO)
        folder_base = xbmcvfs.translatePath(folders_base_path)
        debug_log(f"DEBUG: Translated folder_base={folder_base}", level=xbmc.LOGINFO)
        exists = xbmcvfs.exists(folder_base)
        debug_log(f"DEBUG: xbmcvfs.exists(folder_base)={exists}", level=xbmc.LOGINFO)
        if not exists:
            debug_log(f"DEBUG: Folders base does not exist, attempting to create: {folder_base}", level=xbmc.LOGINFO)
            try:
                xbmcvfs.mkdirs(folder_base)
                debug_log(f"DEBUG: mkdirs called for {folder_base}", level=xbmc.LOGINFO)
            except Exception as e:
                debug_log(f"DEBUG: mkdirs failed for {folder_base}: {e}", level=xbmc.LOGERROR)
            exists = xbmcvfs.exists(folder_base)
            debug_log(f"DEBUG: xbmcvfs.exists(folder_base) after mkdirs={exists}", level=xbmc.LOGINFO)
        debug_folders = []
        debug_log(f"DEBUG: Entering os.listdir block for {folder_base}", level=xbmc.LOGINFO)
        try:
            for f in os.listdir(folder_base):
                full_path = os.path.join(folder_base, f)
                isdir = os.path.isdir(full_path)
                debug_log(f"DEBUG: OS Folder candidate: {full_path} isdir={isdir}", level=xbmc.LOGINFO)
                if isdir:
                    debug_folders.append(f)
        except Exception as e:
            debug_log(f"DEBUG: os.listdir failed for {folder_base}: {e}", level=xbmc.LOGERROR)
        debug_log(f"DEBUG: Exiting os.listdir block for {folder_base}", level=xbmc.LOGINFO)
        folders = debug_folders
        debug_log(f"DEBUG: Folders detected by os.listdir: {folders}", level=xbmc.LOGINFO)
        if not folders:
            debug_log("DEBUG: No folders found after filtering", level=xbmc.LOGINFO)
            dialog.notification("No folders found", "Create a folder first", xbmcgui.NOTIFICATION_INFO)
            return

        filtered_folders = folders
        while True:
            search_term = dialog.input("Search folders (leave blank to show all)")
            if search_term:
                filtered_folders = [f for f in folders if search_term.lower() in f.lower()]
                if not filtered_folders:
                    dialog.notification("No matching folders", "Try another search", xbmcgui.NOTIFICATION_INFO)
                    continue
            selected = dialog.select("Select folder", filtered_folders)
            if selected == -1:
                exit_choice = dialog.yesno("Cancel", "Do you want to exit folder selection?", "No = Search again", "Yes = Exit")
                if exit_choice:
                    return
                continue

            folder_path = folder_base + "/" + filtered_folders[selected]
            links_file = folder_path + "/links.json"
            try:
                if xbmcvfs.exists(links_file):
                    # Keep mode value as-is from existing behavior
                    with xbmcvfs.File(links_file, "öd") as f:
                        links = json.loads(f.read())
                else:
                    links = []
            except Exception:
                links = []
            links = [l for l in links if isinstance(l, dict) and "title" in l and "link" in l]
            if isinstance(link_obj, dict) and not any(l.get("link") == link_obj["link"] for l in links):
                links.append(link_obj)
                with xbmcvfs.File(links_file, "w") as f:
                    f.write(json.dumps(links, indent=2))
            return

    # Default: Add to jet_guide_imported
    try:
        if xbmcvfs.exists(JET_GUIDE_IMPORTED_PATH):
            with xbmcvfs.File(JET_GUIDE_IMPORTED_PATH, "r") as f:
                links = json.loads(f.read())
        else:
            links = []
    except Exception:
        links = []

    links = [l for l in links if isinstance(l, dict) and "title" in l and "link" in l]
    if isinstance(link_obj, dict) and not any(l.get("link") == link_obj["link"] for l in links):
        links.append(link_obj)
        with xbmcvfs.File(JET_GUIDE_IMPORTED_PATH, "w") as f:
            f.write(json.dumps(links, indent=2))


class TickerDialog(xbmcgui.WindowXMLDialog):
    def __init__(self, xmlFilename, scriptPath, messages, display_time=10):
        self.messages = messages if isinstance(messages, list) else [messages]
        self.display_time = display_time
        self.current_message = 0
        super().__init__(xmlFilename, scriptPath)

    def onInit(self):
        try:
            self.setProperty('ticker_text', self.messages[self.current_message])
            start_time = time.time()
            while time.time() - start_time < self.display_time and not xbmc.Monitor().abortRequested():
                if self.current_message < len(self.messages) - 1:
                    if not self.getControl(1000).isScrolling():
                        self.current_message += 1
                        self.setProperty('ticker_text', self.messages[self.current_message])
                xbmc.sleep(100)
            self.close()
        except Exception as e:
            debug_log(f"TickerDialog error: {str(e)}", level=xbmc.LOGERROR)
            self.close()
