# -*- coding: utf-8 -*-
import os
import zipfile
import urllib.request
import xbmc
import xbmcgui
import xbmcaddon
import xbmcvfs

ADDON = xbmcaddon.Addon()
ADDON_PATH = ADDON.getAddonInfo("path")

DIALOG = xbmcgui.Dialog()

HOME = xbmcvfs.translatePath("special://home/")
TEMP = xbmcvfs.translatePath("special://temp/")

FLAG_FILE = os.path.join(TEMP, "iluvatar_postinstall.flag")
MEDIA = os.path.join(ADDON_PATH, "resources", "media")

# =========================
# BUILDS
# =========================

BUILDS = [
    {
        "name": "Kodiesparta",
        "desc": "Todos los dispositivos",
        "url": "https://kodifacil.com/kodiesparta/kodiesparta1/kodiesparta1.zip",
        "icon": os.path.join(MEDIA, "build1_icon.png"),
        "fanart": os.path.join(MEDIA, "build1_fanart.jpg")
    },
    {
        "name": "EspartaFlix",
        "desc": "Windows y Android.NO táctil.",
        "url": "https://kodifacil.com/kodiesparta/kodiesparta2/kodiesparta2.zip",
        "icon": os.path.join(MEDIA, "build2_icon.png"),
        "fanart": os.path.join(MEDIA, "build2_fanart.jpg")
    },
    {
        "name": "Espartajuegos",
        "desc": "Videojuegos Windows",
        "url": "https://kodifacil.com/kodiesparta/kodiesparta3/kodiesparta3.zip",
        "icon": os.path.join(MEDIA, "build3_icon.png"),
        "fanart": os.path.join(MEDIA, "build3_fanart.jpg")
    },
    {
        "name": "Espartir",
        "desc": "Palantir y Acestream Channels",
        "url": "https://kodifacil.com/kodiesparta/kodiesparta4/kodiesparta4.zip",
        "icon": os.path.join(MEDIA, "build4_icon.png"),
        "fanart": os.path.join(MEDIA, "build4_fanart.jpg")
    },
    {
        "name": "Prime Esparta",
        "desc": "Build completa. Para todos los dispositivos",
        "url": "https://kodifacil.com/kodiesparta/kodiesparta5/kodiesparta5.zip",
        "icon": os.path.join(MEDIA, "build5_icon.png"),
        "fanart": os.path.join(MEDIA, "build5_fanart.jpg")
    },
    {
        "name": "Cristal Esparta",
        "desc": "Construccion skin Cristal Touch",
        "url": "https://kodifacil.com/kodiesparta/kodiesparta6/kodiesparta6.zip",
        "icon": os.path.join(MEDIA, "build6_icon.png"),
        "fanart": os.path.join(MEDIA, "build6_fanart.jpg")
    },
    {
        "name": "iLu deluxe",
        "desc": "Build completa del canal.Windows.Skin Aeon iLuDeluxe",
        "url": "https://kodifacil.com/kodiesparta/kodiesparta7/kodiesparta7.zip",
        "icon": os.path.join(MEDIA, "build7_icon.png"),
        "fanart": os.path.join(MEDIA, "build7_fanart.jpg")
    },
    {
        "name": "KodiAtila",
        "desc": "Edición Nitri",
        "url": "https://kodifacil.com/kodiesparta/kodiesparta8/kodiesparta8.zip",
        "icon": os.path.join(MEDIA, "build8_icon.png"),
        "fanart": os.path.join(MEDIA, "build8_fanart.jpg")
    },
    {
        "name": "kodiesparta 9",
        "desc": "Nueva construcción 9",
        "url": "",
        "icon": os.path.join(MEDIA, "build9_icon.png"),
        "fanart": os.path.join(MEDIA, "build9_fanart.jpg")
    },
    {
        "name": "kodiesparta 10",
        "desc": "Nueva construcción 10",
        "url": "",
        "icon": os.path.join(MEDIA, "build10_icon.png"),
        "fanart": os.path.join(MEDIA, "build10_fanart.jpg")
    },
    {
        "name": "kodiesparta 11",
        "desc": "Nueva construcción 11",
        "url": "",
        "icon": os.path.join(MEDIA, "build11_icon.png"),
        "fanart": os.path.join(MEDIA, "build11_fanart.jpg")
    },
    {
        "name": "kodiesparta 12",
        "desc": "Nueva construcción 12",
        "url": "",
        "icon": os.path.join(MEDIA, "build12_icon.png"),
        "fanart": os.path.join(MEDIA, "build12_fanart.jpg")
    }
]

# =========================
# SELECTOR
# =========================

def select_build():
    items = []

    for b in BUILDS:
        li = xbmcgui.ListItem(label=b["name"], label2=b.get("desc", ""))
        li.setArt({
            "icon": b.get("icon", ""),
            "thumb": b.get("icon", ""),
            "fanart": b.get("fanart", "")
        })
        items.append(li)

    idx = DIALOG.select(
        "Selecciona una build – Wizards iLuvatar",
        items,
        useDetails=True
    )

    if idx == -1:
        return

    if not BUILDS[idx]["url"]:
        DIALOG.ok("Error", "Esta build aún no está disponible.")
        return

    install_build(BUILDS[idx])

# =========================
# LIMPIEZA SEGURA
# =========================

def safe_clean():
    folders = [
        "special://home/addons/packages",
        "special://temp"
    ]

    for folder in folders:
        path = xbmcvfs.translatePath(folder)
        if xbmcvfs.exists(path):
            try:
                dirs, files = xbmcvfs.listdir(path)
                for f in files:
                    xbmcvfs.delete(os.path.join(path, f))
            except:
                pass

# =========================
# INSTALACIÓN
# =========================

def install_build(build):

    progress = xbmcgui.DialogProgress()
    progress.create("Wizards iLuvatar", "Preparando instalación...")

    zip_path = os.path.join(TEMP, "iluvatar_build.zip")

    try:
        progress.update(10, "Limpiando temporales...")
        safe_clean()

        progress.update(30, "Descargando build...")

        req = urllib.request.Request(
            build["url"],
            headers={"User-Agent": "Kodi/21 (Wizards iLuvatar)"}
        )

        with urllib.request.urlopen(req) as response:
            with xbmcvfs.File(zip_path, "wb") as out_file:
                while True:
                    chunk = response.read(1024 * 1024)
                    if not chunk:
                        break
                    out_file.write(chunk)

        progress.update(70, "Extrayendo build...")

        with zipfile.ZipFile(zip_path, "r") as z:
            z.extractall(HOME)

        f = xbmcvfs.File(FLAG_FILE, "w")
        f.write("postinstall")
        f.close()

        progress.update(100, "Finalizando...")
        progress.close()

        DIALOG.ok(
            "Wizards iLuvatar",
            "Build instalada correctamente.\n\nKodi se cerrará para completar la instalación."
        )

        xbmc.sleep(1500)
        xbmc.executebuiltin("Quit")

    except Exception as e:
        progress.close()
        xbmc.log("Wizards iLuvatar ERROR: %s" % e, xbmc.LOGERROR)
        DIALOG.ok("Error", str(e))
