# -*- coding: utf-8 -*-
"""
💎 RD Cloud Manager Menu (unified-auth)
1) Play from Cloud Files (calls default.list_cloud)
2) Add Magnet Links (loads remote JSON/TXT and calls importer)
"""
import json, requests, xbmc, xbmcgui, xbmcaddon, xbmcvfs
from modules import rdmagnet_importer
from default import play_unrestricted

ADDON = xbmcaddon.Addon()
ICON  = xbmcvfs.translatePath("special://home/addons/plugin.program.rdtplayer/icon.png")
FANART = xbmcvfs.translatePath("special://home/addons/plugin.program.rdtplayer/fanart.jpg")

URL_TXT  = "https://uck.st/mags/magnetlist.txt.txt"
URL_JSON = "https://uck.st/maglist/rd_movies.json"

def menu():
    opts = ["☁️  Play from Cloud Files", "🧲  Add Magnet Links", "🔙  Back"]
    while True:
        sel = xbmcgui.Dialog().select("💎  Real-Debrid Cloud Manager", opts)
        if sel in (-1, 2):
            break
        elif sel == 0:
            xbmc.executebuiltin('Dialog.Close(all,true)')
            xbmc.sleep(200)
            try:
                from default import list_cloud
                list_cloud()
            except Exception as e:
                xbmcgui.Dialog().ok("Real-Debrid", f"Could not open Cloud:\n{e}")
        elif sel == 1:
            xbmc.executebuiltin('Dialog.Close(all,true)')
            xbmc.sleep(200)
            _add_from_remote()

def _add_from_remote():
    xbmcgui.Dialog().notification("Real-Debrid", "Loading magnet list...", xbmcgui.NOTIFICATION_INFO, 1500)
    text = None
    for url in (URL_JSON, URL_TXT):
        try:
            r = requests.get(url, timeout=12)
            if r.status_code == 200:
                text = r.text.strip()
                break
        except Exception:
            pass
    if not text:
        xbmcgui.Dialog().ok("Error", "Could not load list from server.")
        return

    # Parse → pairs(title, magnet)
    pairs = []
    try:
        data = json.loads(text)
        pairs = [(d.get("title", "Untitled"), d.get("magnet", "")) for d in data]
    except Exception:
        lines = [l.strip() for l in text.splitlines() if l.strip()]
        pairs = [(f"Item {i+1}", l) for i, l in enumerate(lines)]

    names = [t for t, _ in pairs]
    choice = xbmcgui.Dialog().multiselect("Select items to add", names)
    if not choice:
        xbmcgui.Dialog().notification("Real-Debrid", "No items selected.", xbmcgui.NOTIFICATION_INFO, 1500)
        return

    added = failed = 0
    for i in choice:
        _, magnet = pairs[i]
        if magnet.startswith("magnet:") and rdmagnet_importer.add_magnet(magnet):
            added += 1
        else:
            failed += 1

    xbmcgui.Dialog().notification("Real-Debrid", f"✅ {added} added, ❌ {failed} failed", xbmcgui.NOTIFICATION_INFO, 3500)
