from __future__ import annotations

# Sudachi para el add-on de Switch de Batocera 43.1 (Mundo Games, 2026-10-26).
# Porta las opciones del generador de Sudachi del add-on de Batocera 41 (numeración yuzu: resolution_scale 1 = 0.75x,
# gpuaccuracy 0 = Normal) y reutiliza del generador de Eden del 43.1 los atajos, el HUD y la autoconfiguración de mandos.
# Config propia en /userdata/system/configs/sudachi (qt-config.ini y custom/ por juego); NAND, partidas, mods y llaves
# compartidos con Eden en /userdata/system/configs/yuzu.

import glob
import os
import shutil
import stat
import subprocess
from pathlib import Path

from configgen import Command as Command
from configgen.batoceraPaths import mkdir_if_not_exists
from configgen.controller import generate_sdl_game_controller_config
try:
    from configgen.utils.configparser import CaseSensitiveRawConfigParser
except ImportError:
    from batocera_common.configparser import CaseSensitiveRawConfigParser

from generators.edenGenerator import EdenGenerator, ensure_symlink

APPIMAGE = "/userdata/system/switch/appimages/sudachi.AppImage"
SUDACHI = "/userdata/system/configs/sudachi"
YUZU = "/userdata/system/configs/yuzu"
TEMPLATE = "/userdata/system/switch/configgen/qt-config.ini.template"


class SudachiGenerator(EdenGenerator):

    def generate(self, system, rom, playersControllers, metadata, guns, wheels, gameResolution):
        st = os.stat(APPIMAGE)
        os.chmod(APPIMAGE, st.st_mode | stat.S_IEXEC)

        # Si Sudachi o su proceso dwarfs murieron a la fuerza, queda un montaje FUSE huérfano en /tmp/.mount_sudac*
        # que el AppImage reutiliza y el emulador muere con "Illegal instruction". Se desmonta antes de arrancar.
        for m in glob.glob("/tmp/.mount_sudac*"):
            try:
                os.listdir(m)
            except OSError:
                subprocess.run(["umount", "-l", m], check=False)

        # Carpetas comunes de Switch (las mismas que crea Eden en el 43.1)
        for d in ["/userdata/bios/switch/keys", "/userdata/bios/switch/firmware", YUZU + "/nand/system/Contents",
                  YUZU + "/nand/user", "/userdata/saves/switch/eden_citron/save/save_user",
                  "/userdata/saves/switch/eden_citron/save/save_system", "/userdata/saves/switch/eden_citron/mods",
                  "/userdata/roms/switch_update/dlc", "/userdata/roms/switch_update/update"]:
            mkdir_if_not_exists(Path(d))
        ensure_symlink("/userdata/bios/switch/keys", YUZU + "/keys")
        ensure_symlink("/userdata/bios/switch/firmware", YUZU + "/nand/system/Contents/registered")
        ensure_symlink("/userdata/saves/switch/eden_citron/save/save_user", YUZU + "/nand/user/save")
        ensure_symlink("/userdata/saves/switch/eden_citron/save/save_system", YUZU + "/nand/system/save")
        ensure_symlink("/userdata/saves/switch/eden_citron/mods", YUZU + "/load")

        # Carpeta propia de Sudachi, como en v41: config y custom propios; el resto enlazado a yuzu
        if os.path.islink(SUDACHI):
            os.unlink(SUDACHI)
        mkdir_if_not_exists(Path(SUDACHI))
        mkdir_if_not_exists(Path(SUDACHI + "/custom"))
        for d in ["amiibo", "keys", "load", "nand", "screenshots", "sdmc", "shader"]:
            mkdir_if_not_exists(Path(YUZU + "/" + d)) if d not in ["keys", "load"] else None
            ensure_symlink(YUZU + "/" + d, SUDACHI + "/" + d)
        for d in ["/userdata/system/.config/sudachi", "/userdata/system/.local/share/sudachi"]:
            if os.path.isdir(d) and not os.path.islink(d):
                shutil.rmtree(d)
        mkdir_if_not_exists(Path("/userdata/system/.cache/sudachi"))

        configFile = SUDACHI + "/qt-config.ini"
        beforeFile = SUDACHI + "/beforeqt-config.ini"
        autoPads = not system.isOptSet('yuzu_auto_controller_config') or system.config["yuzu_auto_controller_config"] != "0"
        if autoPads:
            # Mandos automáticos: los genera el código del 43.1; luego se aplican encima las opciones de Sudachi
            EdenGenerator.writeYuzuConfig(configFile, TEMPLATE, system, playersControllers, 2, "sudachi")
        SudachiGenerator.writeSudachiConfig(configFile, beforeFile, system)

        commandArray = ["padsp", APPIMAGE, "-f", "-g", rom]
        environment = {"XDG_DATA_HOME": "/userdata/system/configs",
                       "XDG_CONFIG_HOME": "/userdata/system/configs",
                       "XDG_CACHE_HOME": "/userdata/system/configs",
                       "SDL_GAMECONTROLLERCONFIG": generate_sdl_game_controller_config(playersControllers),
                       # Igual que Eden: sin HIDAPI para Xbox/PS/Switch (si no, el mando Xbox por Bluetooth se apaga)
                       "SDL_JOYSTICK_HIDAPI": "1",
                       "SDL_JOYSTICK_HIDAPI_STEAMDECK": "0",
                       "SDL_JOYSTICK_HIDAPI_PS4": "0",
                       "SDL_JOYSTICK_HIDAPI_PS5": "0",
                       "SDL_JOYSTICK_HIDAPI_SWITCH": "0",
                       "SDL_JOYSTICK_HIDAPI_XBOX": "0",
                       "DRI_PRIME": "1",
                       "AMD_VULKAN_ICD": "RADV",
                       "DISABLE_LAYER_AMD_SWITCHABLE_GRAPHICS_1": "1",
                       "QT_XKB_CONFIG_ROOT": "/usr/share/X11/xkb",
                       "QT_QPA_PLATFORM": "xcb",
                       "NO_AT_BRIDGE": "1",
                       "XDG_MENU_PREFIX": "batocera-",
                       "XDG_CONFIG_DIRS": "/etc/xdg",
                       "XDG_CURRENT_DESKTOP": "XFCE",
                       "DESKTOP_SESSION": "XFCE",
                       "QT_FONT_DPI": "96",
                       "QT_SCALE_FACTOR": "1",
                       "GDK_SCALE": "1"}
        return Command.Command(array=commandArray, env=environment)

    @staticmethod
    def writeSudachiConfig(configFile, beforeFile, system):
        c = CaseSensitiveRawConfigParser()
        c.optionxform = str
        if os.path.exists(configFile):
            c.read(configFile)

        def opt(key):
            return system.config[key] if system.isOptSet(key) else None

        def put(sec, key, value, default):
            if not c.has_section(sec):
                c.add_section(sec)
            c.set(sec, key, value)
            if default is not None:
                c.set(sec, key + "\\default", default)

        def choose(sec, key, option, fallback, default_when_set="false", default_when_unset="true"):
            v = opt(option)
            if v is not None:
                put(sec, key, v, default_when_set)
            else:
                put(sec, key, fallback, default_when_unset)

        # UI
        put("UI", "fullscreen", "true", "false")
        put("UI", "confirmClose", "false", "false")
        put("UI", "firstStart", "false", "false")
        put("UI", "displayTitleBars", "false", "false")
        put("UI", "confirmStop", "2", "false")
        put("UI", "enable_discord_presence", opt('yuzu_enable_discord_presence') or "false", "false")
        put("UI", "calloutFlags", "1", "false")
        choose("UI", "singleWindowMode", 'single_window', "true")
        choose("UI", "select_user_on_boot", 'user_profile', "true")
        put("UI", "hideInactiveMouse", "true", "true")
        put("UI", "Paths\\gamedirs\\1\\deep_scan", "true", "false")
        put("UI", "Paths\\gamedirs\\1\\expanded", "true", "true")
        put("UI", "Paths\\gamedirs\\1\\path", "/userdata/roms/switch", None)
        put("UI", "Paths\\gamedirs\\size", "1", None)
        put("UI", "Screenshots\\enable_screenshot_save_as", "true", "true")
        put("UI", "Screenshots\\screenshot_path", "/userdata/screenshots", "false")
        put("UI", "Shortcuts\\Main%20Window\\Exit%20sudachi\\Controller_KeySeq", "Minus+Plus", "false")
        put("UI", "Shortcuts\\Main%20Window\\Fullscreen\\KeySeq", "F4", "false")
        put("UI", "Shortcuts\\Main%20Window\\Fullscreen\\Controller_KeySeq", "Minus+B", "false")
        put("UI", "Shortcuts\\Main%20Window\\Exit%20Fullscreen\\Controller_KeySeq", "Home+ZL", "false")

        # Data Storage (NAND, mods y SD compartidos con Eden del 43.1)
        for k in ["dump", "load", "nand", "sdmc", "tas"]:
            put("Data%20Storage", k + "_directory", YUZU + "/" + k, "true")
        put("Data%20Storage", "use_virtual_sd", "true", "true")

        # Core
        choose("Core", "use_multi_core", 'multicore', "true")

        # Renderer (valores por defecto de v41)
        put("Renderer", "aspect_ratio", opt('sudachi_ratio') or opt('suyu_ratio') or "5", "false")
        put("Renderer", "backend", opt('yuzu_backend') or "0", "false")
        put("Renderer", "use_asynchronous_shaders", opt('async_shaders') or "true", "false")
        choose("Renderer", "shader_backend", 'shaderbackend', "0")
        choose("Renderer", "use_asynchronous_gpu_emulation", 'async_gpu', "true")
        choose("Renderer", "nvdec_emulation", 'nvdec_emu', "2")
        put("Renderer", "gpu_accuracy", opt('gpuaccuracy') or "0", "false")
        if opt('vsync') is not None:
            put("Renderer", "use_vsync", opt('vsync'), "true" if opt('vsync') == "2" else "false")
        else:
            put("Renderer", "use_vsync", "1", "false")
        put("Renderer", "use_caches_gc", opt('gpu_cache_gc') or "false", "false")
        choose("Renderer", "max_anisotropy", 'anisotropy', "0")
        choose("Renderer", "resolution_setup", 'resolution_scale', "2")
        choose("Renderer", "scaling_filter", 'scale_filter', "1")
        choose("Renderer", "anti_aliasing", 'aliasing_method', "0")
        choose("Renderer", "accelerate_astc", 'accelerate_astc', "1")
        if opt('astc_recompression') is not None:
            put("Renderer", "astc_recompression", opt('astc_recompression'), "false")
            if opt('astc_recompression') == "0":
                c.set("Renderer", "use_vsync\\default", "true")
        else:
            put("Renderer", "astc_recompression", "0", "true")
        put("Renderer", "async_astc", "false", "true")

        # Cpu
        choose("Cpu", "cpu_accuracy", 'cpuaccuracy', "0")

        # System
        choose("System", "language_index", 'language', "1")
        choose("System", "sound_index", 'audio_mode', "1")
        choose("System", "region_index", 'region', "1")
        if opt('dock_mode') == "0":
            put("System", "use_docked_mode", "0", "false")
        else:
            put("System", "use_docked_mode", "1", "true")

        # Applets
        put("LibraryApplet", "swkbd_applet_mode", "0", "false")

        for f in (configFile, beforeFile):
            with open(f, "w") as out:
                c.write(out)
