# -*- coding: utf-8 -*-
import os, json, requests, xbmc, xbmcgui, xbmcplugin, sys, urllib.parse
from modules.rd_auth_unified import get_rd_headers   # your unified token system
from modules import rd_cloud_cache

ADDON_ID = "plugin.program.rdtplayer"
HANDLE = int(sys.argv[1])
API_URL = "https://api.real-debrid.com/rest/1.0/torrents"

# ===============================
# UTILITY
# ===============================
def build_url(query):
    return sys.argv[0] + '?' + urllib.parse.urlencode(query)

# ===============================
# FETCH / PLAY / DELETE
# ===============================
def play_torrent(torrent_id):
    headers = get_rd_headers()
    r = requests.get(f"{API_URL}/info/{torrent_id}", headers=headers)
    if r.status_code != 200:
        xbmcgui.Dialog().notification("RD Cloud", "Failed to get torrent info", xbmcgui.NOTIFICATION_ERROR, 3000)
        return
    data = r.json()
    links = data.get("links", [])
    if not links:
        xbmcgui.Dialog().notification("RD Cloud", "No playable links found", xbmcgui.NOTIFICATION_WARNING, 3000)
        return
    # If multiple files exist, let user pick
    if len(links) > 1:
        choices = [os.path.basename(l) for l in links]
        sel = xbmcgui.Dialog().select("Choose file to play", choices)
        if sel == -1: return
        play_url = links[sel]
    else:
        play_url = links[0]
    xbmc.Player().play(play_url)

def delete_torrent(torrent_id):
    headers = get_rd_headers()
    r = requests.delete(f"{API_URL}/delete/{torrent_id}", headers=headers)
    if r.status_code == 204:
        xbmcgui.Dialog().notification("RD Cloud", "Deleted successfully ✅", xbmcgui.NOTIFICATION_INFO, 2500)
        rd_cloud_cache.update_cache()
        return True
    xbmcgui.Dialog().notification("RD Cloud", "Delete failed ❌", xbmcgui.NOTIFICATION_ERROR, 3000)
    return False

# ===============================
# MAIN LIST VIEW
# ===============================
def show_cloud(page=1):
    import xbmcvfs
    per_page = 100

    # Ensure cache file exists
    from modules import rd_cloud_cache
    cache_path = xbmcvfs.translatePath(
        "special://profile/addon_data/plugin.program.rdtplayer/rd_cloud_cache.json"
    )
    if not xbmcvfs.exists(cache_path):
        xbmcgui.Dialog().notification("RD Cloud", "First run — syncing cache...", xbmcgui.NOTIFICATION_INFO, 2000)
        rd_cloud_cache.update_cache()

    # Load and check data
    data, total = rd_cloud_cache.get_page(page, per_page)

    # Auto-sync if file exists but cache is empty
    if not data:
        xbmcgui.Dialog().notification("RD Cloud", "Cache empty — syncing...", xbmcgui.NOTIFICATION_INFO, 2000)
        rd_cloud_cache.update_cache()
        data, total = rd_cloud_cache.get_page(page, per_page)

    pages = (total // per_page) + (1 if total % per_page else 0)
    xbmcplugin.setPluginCategory(HANDLE, f"RD Cloud (Page {page}/{pages})")
    xbmcplugin.setContent(HANDLE, "files")

    if data:
        for t in data:
            title = t.get("filename", "Untitled")
            tid = t.get("id", "")
            status = t.get("status", "")
            label = f"{title}  [COLOR gray]({status})[/COLOR]"

            li = xbmcgui.ListItem(label=label)
            li.addContextMenuItems([
                ("🎬 Play", f'RunPlugin({build_url({"action":"play_torrent","id":tid})})'),
                ("❌ Delete", f'RunPlugin({build_url({"action":"delete_torrent","id":tid})})'),
                ("ℹ️ Info", f'RunPlugin({build_url({"action":"info_torrent","id":tid})})'),
            ])
            li.setInfo("video", {"title": title, "mediatype": "video"})
            xbmcplugin.addDirectoryItem(
                handle=HANDLE,
                url=build_url({"action": "play_torrent", "id": tid}),
                listitem=li,
                isFolder=False
            )

        # Next Page button
        if page < pages:
            li = xbmcgui.ListItem(label=f"▶️ Next Page ({page+1}/{pages})")
            xbmcplugin.addDirectoryItem(
                handle=HANDLE,
                url=build_url({"action": "show_cloud", "page": page + 1}),
                listitem=li,
                isFolder=True
            )
    else:
        li = xbmcgui.ListItem(label="ℹ️ No cached data found")
        xbmcplugin.addDirectoryItem(handle=HANDLE, url="", listitem=li, isFolder=False)

    # Always show sync option
    li = xbmcgui.ListItem(label="🌀 Sync Cloud Cache")
    xbmcplugin.addDirectoryItem(
        handle=HANDLE,
        url=build_url({"action": "sync_cloud"}),
        listitem=li,
        isFolder=False
    )

    xbmcplugin.endOfDirectory(HANDLE)

# ===============================
# INFO
# ===============================
def info_torrent(torrent_id):
    headers = get_rd_headers()
    r = requests.get(f"{API_URL}/info/{torrent_id}", headers=headers)
    if r.status_code != 200:
        xbmcgui.Dialog().notification("RD Cloud", "Failed to load info", xbmcgui.NOTIFICATION_ERROR, 3000)
        return
    info = r.json()
    msg = f"[B]Filename:[/B] {info.get('filename')}\n\n"
    msg += f"[B]Status:[/B] {info.get('status')}\n"
    msg += f"[B]Added:[/B] {info.get('added')}\n"
    msg += f"[B]Links:[/B] {len(info.get('links', []))}"
    xbmcgui.Dialog().textviewer("Torrent Info", msg)

# ===============================
# SYNC
# ===============================
def sync_cloud():
    xbmcgui.Dialog().notification("RD Cloud", "Syncing latest 100...", xbmcgui.NOTIFICATION_INFO, 1500)
    rd_cloud_cache.update_cache()
    xbmcgui.Dialog().notification("RD Cloud", "Sync complete ✅", xbmcgui.NOTIFICATION_INFO, 2500)
    xbmc.executebuiltin("Container.Refresh")
