# -*- coding: utf-8 -*-
"""
💎 Diamond Magnet Browser (direct-call build)
Displays posters & fanart and sends magnet directly to Real-Debrid Cloud.
"""

import sys, json, requests, xbmc, xbmcgui, xbmcplugin
from modules import rdmagnet_importer  # <— use the same proven module
# (you already confirmed this one adds to cloud successfully)

from modules.rd_auth_shared import get_rd_headers

BASE_URL = "https://api.real-debrid.com/rest/1.0"
HEADERS  = get_rd_headers()

HANDLE = int(sys.argv[1]) if len(sys.argv) > 1 else -1
URL_JSON = "https://uck.st/maglist/rd_movies.json"


def show_browser():
    """Display list of movies and handle click → add to cloud."""
    try:
        r = requests.get(URL_JSON, timeout=10)
        r.raise_for_status()
        data = r.json()
    except Exception as e:
        xbmcgui.Dialog().ok("Diamond RD", f"Failed to load list:\n{e}")
        return

    if not data:
        xbmcgui.Dialog().ok("Diamond RD", "No movies found.")
        return

    xbmcplugin.setContent(HANDLE, "movies")

    for movie in data:
        title  = movie.get("title", "Untitled")
        magnet = movie.get("magnet", "")
        plot   = movie.get("plot", "")
        year   = movie.get("year", "")
        poster = movie.get("poster", "")
        fanart = movie.get("fanart", "")

        li = xbmcgui.ListItem(label=title)
        li.setInfo("video", {"title": title, "plot": plot, "year": year})
        li.setArt({"poster": poster, "thumb": poster, "fanart": fanart})
        li.setProperty("IsPlayable", "false")

        # Each click calls this same file again with ?add=<magnet>
        url = f"plugin://plugin.program.rdtplayer/?add={magnet}&title={title}"
        xbmcplugin.addDirectoryItem(HANDLE, url, li, isFolder=False)

    xbmcplugin.endOfDirectory(HANDLE)


def router(paramstring):
    """Handles clicks when user selects a movie."""
    import urllib.parse
    params = dict(urllib.parse.parse_qsl(paramstring.lstrip("?")))
    magnet = params.get("add")
    title  = params.get("title", "Unknown")

    if magnet:
        try:
            xbmcgui.Dialog().notification("Real-Debrid", f"Adding {title}...", xbmcgui.NOTIFICATION_INFO, 2000)
            ok = rdmagnet_importer.add_magnet(magnet)
            if ok:
                xbmcgui.Dialog().notification("Real-Debrid", f"✅ {title} added to Cloud", xbmcgui.NOTIFICATION_INFO, 3000)
            else:
                xbmcgui.Dialog().notification("Real-Debrid", f"❌ Failed to add {title}", xbmcgui.NOTIFICATION_ERROR, 3000)
        except Exception as e:
            xbmcgui.Dialog().ok("Diamond RD", f"Error adding magnet:\n{e}")
        return

    show_browser()

if __name__ == "__main__":
    router(sys.argv[2] if len(sys.argv) > 2 else "")
