# -*- coding: utf-8 -*-
"""
💎 Diamond Magnet Browser
Visual list (poster/fanart/plot/year) → click runs rdmagnet_actions.
"""
import sys, json, requests, urllib.parse
import xbmc, xbmcgui, xbmcplugin

ADDON_ID = "plugin.program.rdtools"
HANDLE = int(sys.argv[1])
URL_JSON = "https://uck.st/maglist/rd_movies.json"   # remote JSON list

def build_movie_directory():
    try:
        r = requests.get(URL_JSON, timeout=12)
        r.raise_for_status()
        data = r.json()
    except Exception as e:
        xbmcgui.Dialog().ok("Error", f"Failed to load JSON:\n{e}")
        return

    if not data:
        xbmcgui.Dialog().ok("Error", "No movies found in list.")
        return

    xbmcplugin.setContent(HANDLE, "movies")

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

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

        url = (
            f'RunScript(special://home/addons/{ADDON_ID}/modules/rdmagnet_actions.py,'
            f'mode=prompt,title={urllib.parse.quote(title)},magnet={urllib.parse.quote(magnet)})'
        )
        xbmcplugin.addDirectoryItem(HANDLE, url, li, isFolder=False)

    xbmcplugin.endOfDirectory(HANDLE)

def router():
    build_movie_directory()

if __name__ == "__main__":
    router()
