# -*- coding: utf-8 -*-
"""
Diamond Real-Debrid API Wrapper
Simplified REST functions used by RD Tools and related add-ons.
Relies on rd_auth_unified for auth + silent refresh.
"""

import requests
import xbmc
from modules import rd_auth_unified

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

# ---------------------------------------------------------------------------
# Helper
# ---------------------------------------------------------------------------
def _req(method, endpoint, **kwargs):
    headers = rd_auth_unified.get_rd_headers()
    if not headers:
        xbmc.log("[RD_API] No headers available (auth failed)", xbmc.LOGERROR)
        return None
    url = f"{API_RD}/{endpoint.lstrip('/')}"
    try:
        r = requests.request(method, url, headers=headers, timeout=15, **kwargs)
        if r.status_code == 401:
            xbmc.log("[RD_API] 401 Unauthorized, trying refresh", xbmc.LOGWARNING)
            headers = rd_auth_unified.get_rd_headers()  # triggers refresh
            r = requests.request(method, url, headers=headers, timeout=15, **kwargs)
        r.raise_for_status()
        return r.json() if "application/json" in r.headers.get("Content-Type", "") else r.text
    except Exception as e:
        xbmc.log(f"[RD_API] {method.upper()} {endpoint} failed: {e}", xbmc.LOGERROR)
        return None

# ---------------------------------------------------------------------------
# Basic RD Endpoints
# ---------------------------------------------------------------------------
def get_user_info():
    return _req("GET", "user")

def get_torrents():
    """Return list of all torrents in RD cloud."""
    return _req("GET", "torrents")

def add_magnet(magnet):
    """Add a magnet link to RD cloud."""
    return _req("POST", "torrents/addMagnet", data={"magnet": magnet})

def delete_torrent(torrent_id):
    return _req("DELETE", f"torrents/delete/{torrent_id}")

def get_torrent_info(torrent_id):
    return _req("GET", f"torrents/info/{torrent_id}")

def unrestrict_link(url):
    """Unrestrict a streaming URL (direct RD link)."""
    return _req("POST", "unrestrict/link", data={"link": url})
