# -*- coding: utf-8 -*-
"""
☁️ RD Cloud helpers (unified-auth)
"""
import xbmc
import xbmcgui
import requests
from urllib.parse import quote
from modules.rd_auth_unified import get_rd_headers

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

def is_cached(hash_id: str) -> bool:
    """Check if a torrent hash is cached on RD."""
    HEADERS = get_rd_headers()
    if not HEADERS:
        return False
    try:
        r = requests.get(f"{BASE_URL}/torrents/instantAvailability/{hash_id}", headers=HEADERS, timeout=12)
        if r.status_code == 200:
            data = r.json() or {}
            key = hash_id.lower()
            return bool(data and key in data and data[key])
        return False
    except Exception as e:
        xbmc.log(f"[rd_cloud_tools] Cache check failed: {e}", xbmc.LOGERROR)
        return False

def add_torrent(magnet: str) -> bool:
    """Add a torrent magnet to RD cloud."""
    HEADERS = get_rd_headers()
    if not HEADERS:
        return False
    try:
        r = requests.post(f"{BASE_URL}/torrents/addMagnet", headers=HEADERS, data={"magnet": magnet}, timeout=15)
        if r.status_code in (200, 201):
            xbmcgui.Dialog().notification("Real-Debrid", "✅ Added to Cloud", xbmcgui.NOTIFICATION_INFO, 3000)
            return True
        xbmcgui.Dialog().notification("Real-Debrid", f"❌ Add failed: {r.status_code}", xbmcgui.NOTIFICATION_ERROR, 3000)
        return False
    except Exception as e:
        xbmcgui.Dialog().ok("Error", f"Failed to add magnet:\n{e}")
        return False

def get_stream_url(hash_id: str):
    """Return a direct stream URL for first file in torrent, if any."""
    HEADERS = get_rd_headers()
    if not HEADERS:
        return None
    try:
        r = requests.get(f"{BASE_URL}/torrents", headers=HEADERS, timeout=12)
        if r.status_code != 200:
            return None
        for t in r.json():
            if t.get("hash", "").upper() == hash_id.upper():
                tid = t["id"]
                info = requests.get(f"{BASE_URL}/torrents/info/{tid}", headers=HEADERS, timeout=12).json()
                links = info.get("links", [])
                if links:
                    u = requests.post(f"{BASE_URL}/unrestrict/link", headers=HEADERS, data={"link": links[0]}, timeout=12)
                    if u.status_code == 200:
                        return (u.json() or {}).get("download")
        return None
    except Exception as e:
        xbmc.log(f"[rd_cloud_tools] Stream fetch failed: {e}", xbmc.LOGERROR)
        return None

def handle_magnet_action(title: str, magnet: str):
    """If cached → play; else prompt to add."""
    try:
        hash_id = magnet.split("btih:")[1].split("&")[0].upper()
    except Exception:
        xbmcgui.Dialog().ok("Error", "Invalid magnet link.")
        return

    xbmcgui.Dialog().notification("Real-Debrid", "🔍 Checking cache...", xbmcgui.NOTIFICATION_INFO, 2000)
    if is_cached(hash_id):
        xbmcgui.Dialog().notification("Real-Debrid", "✅ Cached — Playing...", xbmcgui.NOTIFICATION_INFO, 2000)
        url = get_stream_url(hash_id)
        if url:
            xbmc.Player().play(url)
        else:
            xbmcgui.Dialog().ok("Real-Debrid", "Cached, but stream could not be retrieved.")
        return

    if xbmcgui.Dialog().yesno("Real-Debrid", f"'{title}' is not cached.\nAdd to Cloud?"):
        add_torrent(magnet)
    else:
        xbmcgui.Dialog().notification("Real-Debrid", "Cancelled.", xbmcgui.NOTIFICATION_INFO, 2000)
