# -*- coding: utf-8 -*-
import sys
import os
import xbmc
import xbmcaddon
import xbmcgui
import xbmcvfs
import urllib.parse
import xbmcplugin

from resources.lib import wizard

ADDON = xbmcaddon.Addon()
ADDON_NAME = ADDON.getAddonInfo('name')
ADDON_ICON = ADDON.getAddonInfo('icon')
ADDON_FANART = ADDON.getAddonInfo('fanart')

HANDLE = int(sys.argv[1]) if len(sys.argv) > 1 else -1

# ----------------- UTIL -----------------

def notify(msg):
    xbmc.executebuiltin(f'Notification({ADDON_NAME},{msg},5000,{ADDON_ICON})')

# ----------------- LIMPIEZA -----------------

def get_dir_size(path):
    total = 0
    if not xbmcvfs.exists(path):
        return 0
    try:
        dirs, files = xbmcvfs.listdir(path)
        for f in files:
            try:
                stat = xbmcvfs.Stat(os.path.join(path, f))
                total += stat.st_size
            except:
                pass
        for d in dirs:
            total += get_dir_size(os.path.join(path, d))
    except:
        pass
    return total

def delete_tree(path):
    if not xbmcvfs.exists(path):
        return
    try:
        dirs, files = xbmcvfs.listdir(path)
        for f in files:
            try:
                xbmcvfs.delete(os.path.join(path, f))
            except:
                pass
        for d in dirs:
            delete_tree(os.path.join(path, d))
            try:
                xbmcvfs.rmdir(os.path.join(path, d))
            except:
                pass
    except:
        pass

def manual_clean():
    paths = [
        xbmcvfs.translatePath("special://temp"),
        xbmcvfs.translatePath("special://cache"),
        xbmcvfs.translatePath("special://home/addons/packages"),
        xbmcvfs.translatePath("special://userdata/Thumbnails"),
    ]

    size_before = sum(get_dir_size(p) for p in paths)

    for path in paths:
        delete_tree(path)

    size_after = sum(get_dir_size(p) for p in paths)
    freed_bytes = max(0, size_before - size_after)
    freed_kb = freed_bytes / 1024

    notify(f"Limpieza completada · {freed_kb:.0f} KB liberados")

# ----------------- BUFFER -----------------

def get_free_ram_gb():
    try:
        total = xbmc.getInfoLabel("System.Memory(total)") or "0"
        used = xbmc.getInfoLabel("System.Memory(used)") or "0"

        total = float(total.replace("MB", "").strip())
        used = float(used.replace("MB", "").strip())

        free_mb = max(0, total - used)
        return free_mb / 1024
    except:
        return 0.5

def calculate_buffer_mb(ram_gb):
    if ram_gb <= 1:
        return 50
    elif ram_gb <= 2:
        return 150
    elif ram_gb <= 4:
        return 300
    elif ram_gb <= 8:
        return 600
    elif ram_gb <= 16:
        return 1024
    else:
        return 2048

def configure_buffer():
    free_ram_gb = get_free_ram_gb()
    buffer_mb = calculate_buffer_mb(free_ram_gb)

    advancedsettings = f"""<advancedsettings>
    <cache>
        <buffermode>1</buffermode>
        <memorysize>{buffer_mb * 1024 * 1024}</memorysize>
        <readfactor>20</readfactor>
    </cache>
</advancedsettings>"""

    path = xbmcvfs.translatePath("special://userdata/advancedsettings.xml")

    try:
        f = xbmcvfs.File(path, "w")
        f.write(advancedsettings)
        f.close()
    except Exception as e:
        notify("Error escribiendo advancedsettings.xml")
        return

    notify(f"RAM libre: {free_ram_gb:.2f} GB · Buffer: {buffer_mb} MB")

    dialog = xbmcgui.Dialog()
    if dialog.yesno(
        ADDON_NAME,
        f"Buffer configurado a {buffer_mb} MB.\n\nEs necesario reiniciar Kodi.\n\n¿Reiniciar ahora?"
    ):
        xbmc.executebuiltin("RestartApp")

# ----------------- MENU -----------------

def add_item(label, action, description=""):
    url = f"{sys.argv[0]}?action={action}"

    li = xbmcgui.ListItem(label=label)
    li.setArt({
        "icon": ADDON_ICON,
        "thumb": ADDON_ICON,
        "fanart": ADDON_FANART
    })

    li.setInfo("video", {
        "title": label,
        "plot": description
    })

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

def build_menu():
    xbmcplugin.setPluginCategory(HANDLE, ADDON_NAME)
    xbmcplugin.setContent(HANDLE, "files")
    xbmcplugin.setPluginFanart(HANDLE, ADDON_FANART)

    add_item(
        "[B][COLOR lime]🧹 Limpieza Manual[/COLOR][/B]",
        "manual_clean",
        "Borra cache, packages y thumbnails de forma segura."
    )

    add_item(
        "[B][COLOR orange]🚀 Configuración Automática de Buffer[/COLOR][/B]",
        "configure_buffer",
        "Optimiza el buffer según la RAM disponible."
    )

    add_item(
        "[B][COLOR deepskyblue]📦 Instalar Build[/COLOR][/B]",
        "install",
        "Accede al instalador de builds."
    )

    xbmcplugin.endOfDirectory(HANDLE)

# ----------------- ROUTER -----------------

def router(paramstring):
    params = dict(urllib.parse.parse_qsl(paramstring[1:])) if paramstring else {}
    action = params.get("action")

    if action == "install":
        wizard.select_build()
    elif action == "manual_clean":
        manual_clean()
    elif action == "configure_buffer":
        configure_buffer()
    else:
        build_menu()

# ----------------- START -----------------

if __name__ == "__main__":
    paramstring = sys.argv[2] if len(sys.argv) > 2 else ""
    router(paramstring)
