# -*- coding: utf-8 -*-
import os
import datetime
import xbmc
import xbmcaddon
import xbmcvfs

# ----------------------------------------------------
# INFO ADDON
# ----------------------------------------------------

ADDON = xbmcaddon.Addon()
ADDON_NAME = ADDON.getAddonInfo('name')
ADDON_ID = ADDON.getAddonInfo('id')
ADDON_ICON = ADDON.getAddonInfo('icon')

DATA_PATH = xbmcvfs.translatePath(f"special://profile/addon_data/{ADDON_ID}")
TEMP_PATH = xbmcvfs.translatePath("special://temp/")
PROFILE_PATH = xbmcvfs.translatePath("special://profile/")

POST_FLAG = os.path.join(TEMP_PATH, "iluvatar_postinstall.flag")
MARKER_FILE = os.path.join(DATA_PATH, "last_clean.txt")

SKIN_ID = "skin.stuary"

monitor = xbmc.Monitor()

# ----------------------------------------------------
# UTILIDADES
# ----------------------------------------------------

def log(msg):
    xbmc.log(f"[{ADDON_NAME}] {msg}", xbmc.LOGINFO)

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

def today():
    return datetime.date.today().isoformat()

# ----------------------------------------------------
# CONTROL LIMPIEZA DIARIA
# ----------------------------------------------------

def already_cleaned_today():
    if not xbmcvfs.exists(MARKER_FILE):
        return False
    try:
        f = xbmcvfs.File(MARKER_FILE)
        saved = f.read().strip()
        f.close()
        return saved == today()
    except:
        return False

def mark_clean_today():
    try:
        if not xbmcvfs.exists(DATA_PATH):
            xbmcvfs.mkdirs(DATA_PATH)
        f = xbmcvfs.File(MARKER_FILE, "w")
        f.write(today())
        f.close()
    except:
        pass

# ----------------------------------------------------
# LIMPIEZA AGRESIVA PERO SEGURA
# ----------------------------------------------------

def aggressive_clean():
    if already_cleaned_today():
        return

    log("Iniciando limpieza automática avanzada")

    # Carpetas seguras para limpiar
    folders = [
        "special://temp",
        "special://home/addons/packages",
        "special://profile/Thumbnails"
    ]

    for folder in folders:
        path = xbmcvfs.translatePath(folder)
        if xbmcvfs.exists(path):
            try:
                dirs, files = xbmcvfs.listdir(path)

                # Borrar archivos
                for f in files:
                    xbmcvfs.delete(os.path.join(path, f))

                # Borrar subcarpetas (solo thumbnails)
                for d in dirs:
                    xbmcvfs.rmdir(os.path.join(path, d), True)

            except Exception as e:
                log(f"Error limpiando {folder}: {e}")

    # Borrar base de datos de texturas (se regenera sola)
    db_path = xbmcvfs.translatePath("special://profile/Database")
    if xbmcvfs.exists(db_path):
        try:
            dirs, files = xbmcvfs.listdir(db_path)
            for f in files:
                if f.startswith("Textures") and f.endswith(".db"):
                    xbmcvfs.delete(os.path.join(db_path, f))
        except Exception as e:
            log(f"Error limpiando Textures DB: {e}")

    mark_clean_today()
    notify("Caché y thumbnails limpiados correctamente")
    log("Limpieza completada correctamente")

# ----------------------------------------------------
# POST-INSTALL DIFERIDO
# ----------------------------------------------------

def post_install():
    if not xbmcvfs.exists(POST_FLAG):
        return

    log("Ejecutando post-instalación diferida")

    try:
        xbmc.executebuiltin("UpdateLocalAddons")
        xbmc.executebuiltin("UpdateAddonRepos")
    except Exception as e:
        log(f"Error actualizando repos: {e}")

    try:
        if xbmc.getSkinDir() != SKIN_ID:
            xbmc.executebuiltin(f'LoadSkin({SKIN_ID})')
    except Exception as e:
        log(f"Error cambiando skin: {e}")

    try:
        xbmcvfs.delete(POST_FLAG)
    except:
        pass

    log("Post-instalación finalizada")

# ----------------------------------------------------
# MAIN - ARRANQUE SEGURO ANDROID/WINDOWS
# ----------------------------------------------------

if __name__ == "__main__":

    # Esperar a que Kodi termine de arrancar
    if not monitor.waitForAbort(10):

        try:
            post_install()
        except Exception as e:
            log(f"post_install error: {e}")

        try:
            aggressive_clean()
        except Exception as e:
            log(f"aggressive_clean error: {e}")

    log("Servicio ejecutado correctamente")
