# -*- coding: utf-8 -*-
"""
Central Real-Debrid Cloud handler used by all v4 variants.
Extracted from rdmagnet_browser_v4 so each module (A, B, C, or base)
can call add_to_cloud() without importing one another.
"""

import requests, xbmc, xbmcgui
from modules.rd_auth_unified import get_rd_headers
from default import play_unrestricted

BASE_URL = "https://api.real-debrid.com/rest/1.0"


def add_to_cloud(title: str, magnet: str):
    """Send a magnet to RD Cloud and play the first link when ready."""
    if not magnet:
        xbmcgui.Dialog().notification("Real-Debrid", "No magnet link found.",
                                      xbmcgui.NOTIFICATION_ERROR, 2500)
        return

    headers = get_rd_headers()
    if not headers:
        xbmcgui.Dialog().notification("Real-Debrid",
                                      "Authorization missing or expired.",
                                      xbmcgui.NOTIFICATION_ERROR, 3000)
        return

    try:
        xbmcgui.Dialog().notification("Real-Debrid",
                                      f"☁️ Sending {title} to Cloud…",
                                      xbmcgui.NOTIFICATION_INFO, 2000)

        r = requests.post(f"{BASE_URL}/torrents/addMagnet",
                          headers=headers, data={"magnet": magnet}, timeout=20)
        if not r.ok:
            xbmcgui.Dialog().notification("Real-Debrid",
                                          "Failed to add magnet.",
                                          xbmcgui.NOTIFICATION_ERROR, 3000)
            return

        tid = (r.json() or {}).get("id")
        if not tid:
            xbmcgui.Dialog().ok("Real-Debrid", "Unexpected RD response (no ID).")
            return

        # Select all files in the torrent
        requests.post(f"{BASE_URL}/torrents/selectFiles/{tid}",
                      headers=headers, data={"files": "all"})

        info = requests.get(f"{BASE_URL}/torrents/info/{tid}",
                            headers=headers).json()
        links = info.get("links", [])
        if not links:
            xbmcgui.Dialog().notification("Real-Debrid",
                                          f"{title} added (no stream yet).",
                                          xbmcgui.NOTIFICATION_INFO, 3500)
            return

        xbmcgui.Dialog().notification("Real-Debrid",
                                      f"🎬 Playing {title}",
                                      xbmcgui.NOTIFICATION_INFO, 2000)
        play_unrestricted(links[0])

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