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

import xbmc
import xbmcgui
import xbmcplugin
import xbmcaddon
import xbmcvfs

# ------------------------------------------------------------
# ADDON CONFIG
# ------------------------------------------------------------
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"

SAVE_PATH  = (
    f"special://profile/addon_data/{ADDON_ID}/last_search_combo.json"
)


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


# ------------------------------------------------------------
# REMOVE DUPLICATE MAGNET ENTRIES
# ------------------------------------------------------------
def _dedupe_movies(movies):
    seen = set()
    out = []
    for mv in movies:
        mag = mv.get("magnet", "").strip()
        if not mag:
            continue
        if mag in seen:
            continue
        seen.add(mag)
        out.append(mv)
    return out


# ------------------------------------------------------------
# PARSE YEAR, GENRES, RUNTIME, RATING FROM PLOT LINE
# ------------------------------------------------------------
def _get_movie_meta(mv):
    """
    Diamond compatibility metadata resolver
    Supports REAL Diamond JSON schema
    """

    # -------------------------------
    # YEAR
    # -------------------------------
    year = 0
    try:
        year = int(mv.get("year", 0))
    except:
        pass

    # -------------------------------
    # GENRES (REAL FIELD IS "genre")
    # -------------------------------
    genres = []
    raw_genre = mv.get("genres") or mv.get("genre") or ""
    if isinstance(raw_genre, str):
        genres = [
            g.strip().lower()
            for g in raw_genre.replace("/", ",").split(",")
            if g.strip()
        ]
    elif isinstance(raw_genre, list):
        genres = [str(g).strip().lower() for g in raw_genre if str(g).strip()]

    # -------------------------------
    # RUNTIME (REAL FIELD IS "duration")
    # -------------------------------
    runtime = 0
    try:
        runtime = int(mv.get("runtime") or mv.get("duration") or 0)
    except:
        pass

    # -------------------------------
    # RATING (STRING → FLOAT)
    # -------------------------------
    rating = 0.0
    try:
        rating = float(mv.get("rating", 0))
    except:
        pass

    # If we have structured data, return it immediately
    if year or genres or runtime or rating:
        return {
            "year": year,
            "genres": genres,
            "runtime": runtime,
            "rating": rating
        }

    # -------------------------------
    # LAST RESORT: PARSE PLOT (legacy)
    # -------------------------------
    plot = mv.get("plot", "") or ""
    if not plot:
        return {"year": 0, "genres": [], "runtime": 0, "rating": 0.0}

    parts = plot.split("␚") if "␚" in plot else plot.split("\u001a")

    try:
        year = int(re.search(r"\d{4}", parts[1]).group())
    except:
        year = 0

    try:
        genres = [
            g.strip().lower()
            for g in parts[3].replace("/", ",").split(",")
            if g.strip()
        ]
    except:
        genres = []

    try:
        runtime = int(re.search(r"\d+", parts[6]).group())
    except:
        runtime = 0

    try:
        rating = float(re.search(r"([0-9]+(?:\.[0-9])?)", parts[7]).group())
    except:
        rating = 0.0

    return {
        "year": year,
        "genres": genres,
        "runtime": runtime,
        "rating": rating
    }


# ------------------------------------------------------------
# GENRE MATCH
# ------------------------------------------------------------
def _movie_matches_genre(meta, selected_genres):
    if not selected_genres:
        return True
    if not meta["genres"]:
        return False
    for g in selected_genres:
        if g.lower() in meta["genres"]:
            return True
    return False


# ------------------------------------------------------------
# RENDER RESULTS — MATCHES W5 EXACTLY
# ------------------------------------------------------------
def _render_movie_list(movies):
    if not movies:
        xbmcgui.Dialog().ok("Diamond Combo Search", "No results 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", "")
        clearlogo = mv.get("clearlogo", "")
        banner    = mv.get("banner", "")

        li = xbmcgui.ListItem(label=f"[COLOR white]{title}[/COLOR]")
        li.setInfo("video", {
            "title": title,
            "plot": plot,
            "mediatype": "movie"
        })

        # 💎 MATCH W5 EXACTLY
        li.setArt({
            "thumb": poster,
            "poster": poster,
            "icon": poster,
            "fanart": fanart,
            "clearlogo": clearlogo,
            "banner": 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, False)

    xbmcplugin.endOfDirectory(HANDLE)


# ------------------------------------------------------------
# MAIN COMBO SEARCH ENTRY
# ------------------------------------------------------------
def run_custom_search_combo():
    dlg = xbmcgui.Dialog()

    index = _load_json_url(INDEX_URL, "index.json")
    if not index or not isinstance(index, dict):
        dlg.ok("Diamond Combo Search", "Failed to load index.json.")
        return

    genres  = index.get("genres", [])
    years   = index.get("years", [])
    decades = index.get("decades", [])

    # ========================================================
    # GENRE SELECTION
    # ========================================================
    genre_labels = ["No Genre Filter"] + [g.get("label", "") for g in genres]
    sel = dlg.multiselect("Select Genre(s)", genre_labels)
    if sel is None:
        return

    selected_genres = []
    use_genre = True

    for i in sel:
        if i == 0:
            use_genre = False
            selected_genres = []
            break
        selected_genres.append(genre_labels[i])

    # ========================================================
    # TIME MODE SELECTION (YEAR OR DECADE — NEVER BOTH)
    # ========================================================
    mode = dlg.select(
        "Select Time Filter",
        ["No Time Filter", "By Year", "By Decade"]
    )
    if mode == -1:
        return

    selected_years = []
    selected_decades = []

    # ---------------- YEAR MODE ----------------
    if mode == 1:
        start_year = dlg.numeric(0, "Start Year (Cancel = None)")
        if start_year:
            try:
                start_year = int(start_year)
            except:
                start_year = 0

            end_year = dlg.numeric(0, f"End Year (>= {start_year})")
            try:
                end_year = int(end_year)
            except:
                end_year = start_year

            if end_year < start_year:
                end_year = start_year

            selected_years = list(range(start_year, end_year + 1))

    # ---------------- DECADE MODE ----------------
    elif mode == 2:
        decade_labels = [d.get("label", "") for d in decades]
        sel = dlg.multiselect("Select Decade(s)", decade_labels)
        if sel is None:
            return

        for i in sel:
            label = decade_labels[i]
            m = re.search(r"(\d{4})", label)
            if m:
                start = int(m.group(1))
                selected_decades.append((start, start + 9))

    # ========================================================
    # RATING FILTER
    # ========================================================
    rating_labels = [
        "No Minimum Rating",
        "5.0+", "5.5+", "6.0+", "6.5+", "7.0+", "7.5+", "8.0+"
    ]
    rating_values = [0.0, 5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0]

    r = dlg.select("Select Minimum Rating", rating_labels)
    if r == -1:
        return

    min_rating = rating_values[r]
    
    # ========================================================
    # RESOLUTION FILTER
    # ========================================================
    res_labels = [
        "No Resolution Filter",
        "2160p / 4K",
        "1080p",
        "720p",
        "480p / SD"
    ]
    
    res_values = [
        None,
        ["2160p", "4k"],
        ["1080p"],
        ["720p"],
        ["480p", "576p"]
    ]

    r = dlg.select("Filter by Resolution", res_labels)
    if r == -1:
        return
    
    selected_resolution = res_values[r]
    
    # ========================================================
    # SOURCE / QUALITY FILTER
    # ========================================================
    source_labels = [
        "No Source Filter",
        "REMUX only",
        "BluRay only (non-REMUX)",
        "BluRay + REMUX"
    ]
    
    source_modes = [
        None,
        "remux",
        "bluray_only",
        "bluray_any"
    ]
    
    s = dlg.select("Filter by Source / Quality", source_labels)
    if s == -1:
        return
    
    source_mode = source_modes[s]
        
    # ========================================================
    # LOAD BASE DATASET (SMALLEST FIRST)
    # ========================================================
    movies = None

    # ---- TIME FILTER FIRST ----
    if selected_years:
        year_map = {y.get("label", ""): y.get("file", "") for y in years}
        movies = []

        for yr in selected_years:
            url = year_map.get(str(yr))
            if url:
                data = _load_json_url(url, f"year {yr}")
                if isinstance(data, list):
                    movies.extend(data)

    elif selected_decades:
        movies = []
        for d in decades:
            label = d.get("label", "")
            url   = d.get("file", "")
            if not url:
                continue

            m = re.search(r"(\d{4})", label)
            if not m:
                continue

            start = int(m.group(1))
            for (s, e) in selected_decades:
                if start == s:
                    data = _load_json_url(url, f"decade {label}")
                    if isinstance(data, list):
                        movies.extend(data)

    # ---- NO TIME FILTER ----
    if movies is None:
        dlg.ok("Diamond Combo Search", "You must select a Year or Decade.")
        return

    if not movies:
        dlg.ok("Diamond Combo Search", "No movies found in selected time range.")
        return

    # ========================================================
    # DEDUPE EARLY
    # ========================================================
    movies = _dedupe_movies(movies)

    # ========================================================
    # APPLY GENRE + RATING FILTERS
    # ========================================================
    final = []

    for mv in movies:
        meta = _get_movie_meta(mv)
        title = mv.get("title", "").lower()
    
        # ---------------- GENRE ----------------
        if use_genre and not _movie_matches_genre(meta, selected_genres):
            continue
    
        # ---------------- RATING ----------------
        if min_rating and meta["rating"] < min_rating:
            continue
    
        # ---------------- RESOLUTION ----------------
        if selected_resolution:
            if not any(res in title for res in selected_resolution):
                continue
    
        # ---------------- SOURCE / QUALITY ----------------
        if source_mode == "remux":
            if "remux" not in title:
                continue
    
        elif source_mode == "bluray_only":
            if "bluray" not in title and "blu-ray" not in title:
                continue
            if "remux" in title:
                continue
    
        elif source_mode == "bluray_any":
            if (
                "bluray" not in title
                and "blu-ray" not in title
                and "remux" not in title
            ):
                continue
    
        final.append(mv)


    if not final:
        dlg.ok("Diamond Combo Search", "No movies matched filters.")
        return

    # ========================================================
    # SAVE RESULT
    # ========================================================
    try:
        path = xbmcvfs.translatePath(SAVE_PATH)
        with open(path, "w", encoding="utf-8") as f:
            json.dump(final, f, ensure_ascii=False, indent=2)
    except Exception as e:
        xbmc.log(f"[Combo] Save failed: {e}", xbmc.LOGERROR)

#    _render_movie_list(final)
    from modules.rdmagnet_browser_v4_w5 import render_movie_list
    render_movie_list(final, "Multi Combo Results")

