# -*- coding: utf-8 -*-
"""
💎 RD Magnet Importer (unified-auth)
- Adds a single magnet to RD Cloud
- Optional mini UI to enter magnet or import from .txt
- CLOUD-ONLY: this module does NOT play video directly.
"""
import time
import requests
import xbmc
import xbmcgui
import xbmcvfs
from modules.rd_auth_unified import get_rd_headers

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


def add_magnet(magnet: str) -> bool:
    """
    Add magnet → wait for metadata → select all → start caching.
    Exactly what your v4 browsers expect: cloud-only behavior.
    """
    HEADERS = get_rd_headers()
    if not HEADERS:
        xbmcgui.Dialog().notification(
            "Real-Debrid",
            "RD API key missing.",
            xbmcgui.NOTIFICATION_ERROR,
            3000
        )
        return False

    try:
        # 1) Add magnet to RD
        r = requests.post(
            f"{BASE_URL}/torrents/addMagnet",
            data={"magnet": magnet},
            headers=HEADERS,
            timeout=20
        )
        r.raise_for_status()
        tid = (r.json() or {}).get("id")
        if not tid:
            xbmc.log("[RDMagnet] No torrent ID returned.", xbmc.LOGERROR)
            return False

        # 2) Wait for RD to fetch metadata (files list)
        for _ in range(20):
            info = requests.get(
                f"{BASE_URL}/torrents/info/{tid}",
                headers=HEADERS,
                timeout=15
            ).json()
            if info.get("files"):
                break
            time.sleep(1)

        # 3) Select all files in the torrent
        try:
            requests.post(
                f"{BASE_URL}/torrents/selectFiles/{tid}",
                data={"files": "all"},
                headers=HEADERS,
                timeout=15
            )
        except Exception as e:
            xbmc.log(f"[RDMagnet] selectFiles failed (non-fatal): {e}", xbmc.LOGWARNING)

        # 4) Start caching (best effort)
        try:
            requests.post(
                f"{BASE_URL}/torrents/start/{tid}",
                headers=HEADERS,
                timeout=10
            )
        except Exception:
            # Some RD setups don't require an explicit /start
            pass

        xbmcgui.Dialog().notification(
            "Real-Debrid",
            "✅ Magnet added & caching started!",
            xbmcgui.NOTIFICATION_INFO,
            3000
        )
        xbmc.log(f"[RDMagnet] Magnet {tid} added + caching.", xbmc.LOGINFO)
        return True

    except Exception as e:
        xbmc.log(f"[RDMagnet] add_magnet failed: {e}", xbmc.LOGERROR)
        xbmcgui.Dialog().notification(
            "Real-Debrid",
            "❌ Add failed",
            xbmcgui.NOTIFICATION_ERROR,
            3000
        )
        return False


def run():
    """
    Tiny helper UI for manual use:
      - Enter single magnet
      - Or import a .txt with multiple magnets
    All of them are sent to RD Cloud via add_magnet().
    """
    options = ["🧲 Enter Magnet Link", "📄 Import from Text File", "❌ Cancel"]
    choice = xbmcgui.Dialog().select("Real-Debrid Magnet Importer", options)
    if choice in (-1, 2):
        return

    # Single magnet
    if choice == 0:
        magnet = xbmcgui.Dialog().input("Enter Magnet Link")
        if magnet:
            ok = add_magnet(magnet)
            xbmcgui.Dialog().notification(
                "Real-Debrid",
                "Download started!" if ok else "Failed to add magnet",
                xbmcgui.NOTIFICATION_INFO if ok else xbmcgui.NOTIFICATION_ERROR,
                3000
            )
        return

    # Import from text file
    file_path = xbmcgui.Dialog().browse(
        1,
        "Select .txt with magnet links",
        "files",
        ".txt"
    )
    if not file_path:
        return

    try:
        with xbmcvfs.File(file_path) as f:
            content = f.read()
        magnets = [l.strip() for l in content.splitlines() if l.strip()]
    except Exception as e:
        xbmcgui.Dialog().ok("Error", f"Could not read file:\n{e}")
        return

    total = len(magnets)
    if not total:
        xbmcgui.Dialog().ok("Real-Debrid", "No magnet links found.")
        return

    dp = xbmcgui.DialogProgress()
    dp.create("Adding magnets...", f"Found {total} links")
    success = fail = 0

    for i, m in enumerate(magnets, 1):
        if dp.iscanceled():
            break
        dp.update(int((i / total) * 100), f"Adding {i}/{total}")
        if add_magnet(m):
            success += 1
        else:
            fail += 1
        time.sleep(0.3)

    dp.close()
    xbmcgui.Dialog().ok(
        "Real-Debrid",
        f"✅ {success} added\n❌ {fail} failed"
    )
