# -*- coding: utf-8 -*-
"""
💎 RD Magnet Actions
- mode=add: add to cloud
- mode=play: play via default.play_unrestricted (unrestrict first)
- mode=prompt: ask Add or Play
"""
import sys
import urllib.parse
import xbmc
import xbmcgui
from modules import rdmagnet_importer
from default import play_unrestricted  # uses your resolver flow

params = dict(urllib.parse.parse_qsl(sys.argv[1])) if len(sys.argv) > 1 else {}
mode   = params.get("mode")
magnet = params.get("magnet", "")
title  = params.get("title", "Unknown")

if not magnet:
    xbmcgui.Dialog().notification("Real-Debrid", "No magnet link found", xbmcgui.NOTIFICATION_ERROR, 2500)
    sys.exit()

try:
    if mode == "prompt":
        choice = xbmcgui.Dialog().select(f"Select Action for {title}",
                                         ["☁️ Add to Cloud", "▶️ Play Now", "Cancel"])
        if choice == 0:
            xbmc.executebuiltin(
                f'RunScript(special://home/addons/plugin.program.rdtplayer/modules/rdmagnet_actions.py,mode=add,title={urllib.parse.quote(title)},magnet={urllib.parse.quote(magnet)})'
            )
        elif choice == 1:
            xbmc.executebuiltin(
                f'RunScript(special://home/addons/plugin.program.rdtplayer/modules/rdmagnet_actions.py,mode=play,title={urllib.parse.quote(title)},magnet={urllib.parse.quote(magnet)})'
            )

    elif mode == "add":
        xbmcgui.Dialog().notification("Real-Debrid", f"☁️ Adding {title}", xbmcgui.NOTIFICATION_INFO, 1500)
        ok = rdmagnet_importer.add_magnet(magnet)
        xbmcgui.Dialog().notification("Real-Debrid",
                                      f"✅ {title} added to Cloud" if ok else f"❌ Failed to add {title}",
                                      xbmcgui.NOTIFICATION_INFO if ok else xbmcgui.NOTIFICATION_ERROR, 2500)

    elif mode == "play":
        xbmcgui.Dialog().notification("Real-Debrid", f"▶️ Playing {title}", xbmcgui.NOTIFICATION_INFO, 1500)
        play_unrestricted(magnet)

except Exception as e:
    xbmcgui.Dialog().ok("Error", f"Real-Debrid action failed:\n{e}")
