# -*- coding: utf-8 -*-
import sys
import json
import requests
import urllib.parse

import xbmc
import xbmcgui
import xbmcplugin
import xbmcaddon
import xbmcvfs

ADDON      = xbmcaddon.Addon()
ADDON_ID   = ADDON.getAddonInfo("id")
HANDLE     = int(sys.argv[1]) if len(sys.argv) > 1 else -1

INDEX_URL  = "https://uck.st/splite_movies/list_sorted/index.json"


# ------------------ helpers ------------------

def _load_json_url(url, what="file"):
    xbmc.log(f"[DiamondCustom] Loading {what}: {url}", xbmc.LOGINFO)
    try:
        r = requests.get(url, timeout=10)
        if not r.ok:
            xbmc.log(f"[DiamondCustom] HTTP {r.status_code} for {url}", xbmc.LOGERROR)
            return []
        return r.json()
    except Exception as e:
        xbmc.log(f"[DiamondCustom] Failed to load {what} from {url}: {e}", xbmc.LOGERROR)
        return []


def _dedupe_movies(movies):
    """
    De-duplicate by magnet (primary) or title fallback.
    """
    seen = set()
    out = []
    for mv in movies:
        mag = mv.get("magnet", "").strip()
        key = f"M:{mag}" if mag else f"T:{mv.get('title','').strip()}"
        if not key or key in seen:
            continue
        seen.add(key)
        out.append(mv)
    return out


def _render_movie_list(movies):
    if not movies:
        xbmcgui.Dialog().ok("Diamond A–Z Browser", "No movies found.")
        return

    xbmcplugin.setContent(HANDLE, "movies")

    for mv in movies:
        title  = mv.get("title", "Untitled")
        magnet = mv.get("magnet", "").strip()
        if not magnet:
            continue

        plot   = mv.get("plot", "")
        poster = mv.get("poster", "")
        fanart = mv.get("fanart", "")

        runtime = mv.get("duration") or mv.get("runtime") or ""
        rating  = mv.get("rating") or mv.get("imdb_rating") or ""
        mpaa    = mv.get("mpaa") or mv.get("rated") or mv.get("certification") or ""

        display_title = f"[COLOR white]{title}[/COLOR]"
        li = xbmcgui.ListItem(label=display_title)

        li.setInfo("video", {
            "title": display_title,
            "plot":  plot,
            "duration": runtime,
            "mpaa": mpaa,
            "rating": rating,
            "mediatype": "movie"
        })

        li.setArt({
            "thumb": poster,
            "poster": poster,
            "icon": poster,
            "fanart": fanart,
            "clearlogo": mv.get("clearlogo", ""),
            "banner": mv.get("banner", "")
        })

        li.setProperty("IsPlayable", "true")

        url = (
            f"plugin://{ADDON_ID}/?action=add_to_cloud"
            f"&title={urllib.parse.quote(title)}"
            f"&magnet={urllib.parse.quote(magnet)}"
        )

        xbmcplugin.addDirectoryItem(HANDLE, url, li, isFolder=False)

    xbmcplugin.endOfDirectory(HANDLE)


# ------------------ main entry ------------------

def run_custom_search_letters():
    """
    Browse A–Z:
    - user picks 1+ letters
    - addon loads letter JSON files
    - de-dupes, saves last_search_letters.json
    - shows results
    """
    dlg = xbmcgui.Dialog()

    # ---------- LOAD index.json ----------
    index = _load_json_url(INDEX_URL, "index.json")
    if not index or not isinstance(index, dict):
        dlg.ok("Diamond A–Z Browser", "Failed to load index.json.")
        return

    letters = index.get("letters", [])   # [{label,file},...]

    if not letters:
        dlg.ok("Diamond A–Z Browser", "No A–Z data found.")
        return

    # ---------- PICK LETTER(S) ----------
    letter_labels = [l.get("label", "") for l in letters]
    selected_idx = dlg.multiselect("Select letter(s)", letter_labels)

    if not selected_idx:
        return

    selected_letters = [letter_labels[i] for i in selected_idx]
    letter_map = {l.get("label", ""): l.get("file", "") for l in letters}

    # ---------- LOAD MOVIES ----------
    combined = []
    for letter in selected_letters:
        url = letter_map.get(letter)
        if not url:
            continue
        movies = _load_json_url(url, f"letter {letter}")
        if isinstance(movies, list):
            combined.extend(movies)

    if not combined:
        dlg.ok("Diamond A–Z Browser", "No movies found.")
        return

    # ---------- DE-DUPE ----------
    movies = _dedupe_movies(combined)

    # ---------- SAVE FOR WIDGET ----------
    try:
        save_path = xbmcvfs.translatePath(
            f"special://profile/addon_data/{ADDON_ID}/last_search_letters.json"
        )
        with open(save_path, "w", encoding="utf-8") as f:
            json.dump(movies, f, ensure_ascii=False, indent=2)

        xbmc.log(f"[DiamondCustom] Saved A–Z widget list: {save_path}", xbmc.LOGINFO)
    except Exception as e:
        xbmc.log(f"[DiamondCustom] Failed to save widget list: {e}", xbmc.LOGERROR)

    # ---------- SHOW RESULTS ----------
    _render_movie_list(movies)
