# -*- 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 []
        data = r.json()
        return data
    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+year fallback.
    """
    seen = set()
    out = []
    for mv in movies:
        mag = mv.get("magnet", "").strip()
        if mag:
            key = f"M:{mag}"
        else:
            key = f"T:{mv.get('title','').strip()}|Y:{mv.get('year','').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 Custom Search", "No results found for your filters.")
        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", "")

        year   = mv.get("year", "")
        year  = mv.get("year", "")
        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,
            "year":  year,
            "year": year,
            "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_year():
    """
    Simple custom search:
    - user picks 1+ years
    - addon loads/merges JSON files from Bunny
    - de-dupes, saves to last_search.json
    - shows results as normal playable list
    """
    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 Custom Search", "Failed to load index.json from server.")
        return

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

    if not years:
        dlg.ok("Diamond Custom Search", "No year data found in index.json.")
        return

    # ---------- STEP 1: pick years ONLY ----------
    year_labels = [g.get("label", "") for g in years]
    selected_idx = dlg.multiselect("Select year(s)", year_labels)

    # user cancelled or picked nothing
    if not selected_idx:
        return

    selected_year_labels = [year_labels[i] for i in selected_idx]

    # ---------- STEP 2: LOAD MOVIES FROM SELECTED GENRES ----------
    combined = []
    year_map = {g.get("label", ""): g.get("file", "") for g in years}

    for glabel in selected_year_labels:
        url = year_map.get(glabel)
        if not url:
            continue
        movies = _load_json_url(url, f"year {glabel}")
        if isinstance(movies, list):
            combined.extend(movies)

    if not combined:
        dlg.ok("Diamond Custom Search", "No movies found.")
        return

    # ---------- STEP 3: DE-DUPE ----------
    movies = _dedupe_movies(combined)

    # ---------- STEP 3.5: SAVE FOR WIDGET ----------
    try:
        save_path = xbmcvfs.translatePath(
            f"special://profile/addon_data/{ADDON_ID}/last_search_year.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 list for widget: {save_path}", xbmc.LOGINFO)
    except Exception as e:
        xbmc.log(f"[DiamondCustom] Failed to save widget list: {e}", xbmc.LOGERROR)

    # ---------- STEP 4: SHOW RESULTS ----------
    _render_movie_list(movies)
