# -*- coding: utf-8 -*-
"""
💎 RD Unrestrict Importer (unified-auth)
- Unrestricts a single URL (hoster / file link)
- Optional mini UI to enter URL or import from .txt
- DOES NOT add to RD Cloud
- Returns unrestricted links for playback or list usage
"""

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 unrestrict_link(url: str) -> str | None:
    """
    Unrestrict a single link.
    Returns the unrestricted download URL or None on failure.
    """
    HEADERS = get_rd_headers()
    if not HEADERS:
        xbmcgui.Dialog().notification(
            "Real-Debrid",
            "RD API key missing.",
            xbmcgui.NOTIFICATION_ERROR,
            3000
        )
        return None

    try:
        r = requests.post(
            f"{BASE_URL}/unrestrict/link",
            data={"link": url},
            headers=HEADERS,
            timeout=20
        )
        r.raise_for_status()

        data = r.json() or {}
        unrestricted = data.get("download")

        if not unrestricted:
            xbmc.log("[RDUnrestrict] No unrestricted link returned.", xbmc.LOGERROR)
            return None

        xbmc.log("[RDUnrestrict] Link unrestricted successfully.", xbmc.LOGINFO)
        return unrestricted

    except Exception as e:
        xbmc.log(f"[RDUnrestrict] unrestrict_link failed: {e}", xbmc.LOGERROR)
        return None


def run():
    """
    Tiny helper UI:
      - Enter single URL
      - Or import a .txt with multiple URLs
    """
    options = ["🔓 Enter Link", "📄 Import from Text File", "❌ Cancel"]
    choice = xbmcgui.Dialog().select("Real-Debrid Unrestrict Links", options)
    if choice in (-1, 2):
        return

    # Single URL
    if choice == 0:
        url = xbmcgui.Dialog().input("Enter Link to Unrestrict")
        if not url:
            return

        link = unrestrict_link(url)
        if link:
            xbmcgui.Dialog().ok("Unrestricted Link", link)
        else:
            xbmcgui.Dialog().notification(
                "Real-Debrid",
                "❌ Failed to unrestrict",
                xbmcgui.NOTIFICATION_ERROR,
                3000
            )
        return

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

    try:
        with xbmcvfs.File(file_path) as f:
            content = f.read()
        urls = [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(urls)
    if not total:
        xbmcgui.Dialog().ok("Real-Debrid", "No links found.")
        return

    dp = xbmcgui.DialogProgress()
    dp.create("Unrestricting links...", f"Found {total} links")

    unrestricted_links = []
    fail = 0

    for i, u in enumerate(urls, 1):
        if dp.iscanceled():
            break

        dp.update(int((i / total) * 100), f"Processing {i}/{total}")
        link = unrestrict_link(u)
        if link:
            unrestricted_links.append(link)
        else:
            fail += 1

        time.sleep(0.3)

    dp.close()

    if unrestricted_links:
        xbmcgui.Dialog().textviewer(
            "Unrestricted Links",
            "\n".join(unrestricted_links)
        )

    xbmcgui.Dialog().ok(
        "Real-Debrid",
        f"✅ {len(unrestricted_links)} unrestricted\n❌ {fail} failed"
    )
