#!/bin/bash

# ==========================================================
# WMM - Wallpaper Master Manager
# Interactive installer and dependency checker
# ==========================================================

# Colors for the checklist
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No color

# Obtener la ruta absoluta del directorio del script
SCRIPT_DIR="$(dirname "$(realpath "$0")")"

# ----------------------------------------------------------
# 1. DETECCIÓN DE PLATAFORMA
# ----------------------------------------------------------
PLATFORM=$(uname -s | tr '[:upper:]' '[:lower:]')
if [ "$PLATFORM" != "linux" ]; then
    echo -e "${RED}ERROR: Unsupported platform: $PLATFORM${NC}"
    exit 1
fi
echo -e "${GREEN}Platform: $PLATFORM${NC}"

# ----------------------------------------------------------
# 2. DETECCIÓN DEL ESCRITORIO
# ----------------------------------------------------------
DESKTOP="${XDG_CURRENT_DESKTOP:-${DESKTOP_SESSION:-unknown}}"
DESKTOP=$(echo "$DESKTOP" | tr '[:upper:]' '[:lower:]')

# Normalizar variantes conocidas (X-Cinnamon -> cinnamon, ubuntu:GNOME -> gnome, etc.)
case "$DESKTOP" in
    x-cinnamon|cinnamon2d) DESKTOP="cinnamon" ;;
    ubuntu*|gnome*)        DESKTOP="gnome" ;;
    plasma*)               DESKTOP="kde" ;;
esac

# Verificar que el escritorio está realmente instalado
case "$DESKTOP" in
    cinnamon)
        command -v cinnamon >/dev/null 2>&1 || DESKTOP="unknown"
        ;;
    gnome)
        command -v gnome-shell >/dev/null 2>&1 || DESKTOP="unknown"
        ;;
    *)
        DESKTOP="unknown"
        ;;
esac

if [ "$DESKTOP" = "unknown" ]; then
    echo -e "${RED}ERROR: Could not detect a supported desktop environment.${NC}"
    exit 1
fi
echo -e "${GREEN}Desktop: $DESKTOP${NC}"

# ----------------------------------------------------------
# 3. RUTAS XDG (BASE DE DATOS Y CACHÉ)
# ----------------------------------------------------------
DATA_BASE="${XDG_DATA_HOME:-$HOME/.local/share}"
CACHE_BASE="${XDG_CACHE_HOME:-$HOME/.cache}"
echo "Data base: $DATA_BASE"
echo "Cache base: $CACHE_BASE"

# ----------------------------------------------------------
# 4. DEFINIR DOMINIO Y RUTAS DE INSTALACIÓN SEGÚN ESCRITORIO
# ----------------------------------------------------------
case "$DESKTOP" in
    cinnamon)
        APP_DOMAIN="wmm-applet@maki"
        APPLET_DIR="$DATA_BASE/cinnamon/applets/$APP_DOMAIN"
        ;;
    gnome)
        APP_DOMAIN="wmm@maki"
        APPLET_DIR="$DATA_BASE/gnome-shell/extensions/$APP_DOMAIN"
        ;;
    *)
        echo -e "${RED}ERROR: Unsupported desktop: $DESKTOP${NC}"
        exit 1
        ;;
esac

CACHE_DIR="$CACHE_BASE/wmm"

echo "App domain: $APP_DOMAIN"
echo "Installation path: $APPLET_DIR"
echo "Cache path: $CACHE_DIR"

# Copiar el metadata.json y el JS correspondiente al escritorio
case "$DESKTOP" in
    cinnamon)
        cp -f "$SCRIPT_DIR/wmm_platform/shell/cinnamon/metadata.cinnamon.json" "$APPLET_DIR/metadata.json"
        cp -f "$SCRIPT_DIR/wmm_platform/shell/cinnamon/applet.js" "$APPLET_DIR/applet.js"
        echo "Archivos de Cinnamon copiados a $APPLET_DIR."
        ;;
    gnome)
        cp -f "$SCRIPT_DIR/wmm_platform/shell/gnome/metadata.gnome.json" "$APPLET_DIR/metadata.json"
        cp -f "$SCRIPT_DIR/wmm_platform/shell/gnome/extension.js" "$APPLET_DIR/extension.js"
        echo "Archivos de GNOME copiados a $APPLET_DIR."
        ;;
esac

# ----------------------------------------------------------
# 5. GENERAR settings_core.ini
# ----------------------------------------------------------
INI_FILE="$SCRIPT_DIR/data/settings_core.ini"

echo "Generating platform configuration..."
cat > "$INI_FILE" << EOF
# WMM Platform Configuration
# Generated by install.sh on $(date)
platform=$PLATFORM
desktop=$DESKTOP
app_domain=$APP_DOMAIN
data_base=$DATA_BASE
cache_base=$CACHE_BASE
EOF

echo -e "${GREEN}Configuration saved to $INI_FILE${NC}"

# ----------------------------------------------------------
# 6. DEPENDENCIAS DE WMM (INSTALABLES)
# ----------------------------------------------------------
declare -A WMM_DEPENDENCIES
WMM_DEPENDENCIES=(
    ["Python 3"]="python3 --version|python3"
    ["Pillow (Python Imaging)"]="python3 -c 'from PIL import Image'|python3-pillow"
    ["NumPy (Python scientific computing)"]="python3 -c 'import numpy'|python3-numpy"
    ["Libnotify (notifications)"]="command -v notify-send|libnotify-bin"
    ["GetText"]="command -v xgettext|gettext"
    ["Zenity (dialogs)"]="command -v zenity|zenity"
)

# ----------------------------------------------------------
# 7. DEPENDENCIAS DE GNOME (SOLO SI EL ESCRITORIO ES GNOME)
# ----------------------------------------------------------
declare -A GNOME_DEPENDENCIES
if [ "$DESKTOP" = "gnome" ]; then
    GNOME_DEPENDENCIES=(
        ["GNOME Shell Extensions"]="command -v gnome-extensions|gnome-shell-extension-prefs"
        ["GNOME Shell Extension Manager"]="command -v gnome-extensions-app|gnome-shell-extension-prefs"
    )
fi

# ----------------------------------------------------------
# 8. DEPENDENCIAS DEL SISTEMA (SOLO VERIFICACIÓN)
# ----------------------------------------------------------
declare -A SYSTEM_DEPENDENCIES
SYSTEM_DEPENDENCIES=(
    ["PyGObject (GTK bindings)"]="python3 -c 'import gi; gi.require_version(\"Gtk\", \"3.0\")'"
    ["GTK 3.0 Introspection"]="python3 -c 'import gi; gi.require_version(\"Gtk\", \"3.0\")'"
    ["GLib 2.0 Introspection"]="python3 -c 'import gi; gi.require_version(\"GLib\", \"2.0\")'"
    ["pkill (signals)"]="command -v pkill"
)
# ----------------------------------------------------------
# 8. FUNCIONES DE VERIFICACIÓN Y CHECKLIST
# ----------------------------------------------------------

# ----------------------------------------------------------
# FUNCIÓN PARA VERIFICAR UNA DEPENDENCIA
# ----------------------------------------------------------
check_dep() {
    local test_cmd="$1"
    if eval "$test_cmd" &> /dev/null; then
        echo 1 # Instalada
    else
        echo 0 # No instalada
    fi
}
# ----------------------------------------------------------
# FUNCIÓN PARA MOSTRAR EL CHECKLIST
# ----------------------------------------------------------
print_checklist() {
    local installed_count=0
    local missing_count=0
    echo -e "\nDependency status:"

    # --- Bloque 1: Dependencias del Sistema (solo verificación) ---
    echo -e "\n${GREEN}[System dependencies]${NC}"
    for dep_name in "${!SYSTEM_DEPENDENCIES[@]}"; do
        test_cmd="${SYSTEM_DEPENDENCIES[$dep_name]}"
        status=$(check_dep "$test_cmd")
        if [ "$status" -eq 1 ]; then
            echo -e "  ${GREEN}[✔]${NC} $dep_name"
            ((installed_count++))
        else
            echo -e "  ${RED}[✘]${NC} $dep_name (required for $DESKTOP)"
            ((missing_count++))
        fi
    done

    # --- Bloque 2: Dependencias de GNOME (solo si estamos en GNOME) ---
    if [ "$DESKTOP" = "gnome" ]; then
        echo -e "\n${GREEN}[GNOME dependencies]${NC}"
        for dep_name in "${!GNOME_DEPENDENCIES[@]}"; do
            test_cmd="${GNOME_DEPENDENCIES[$dep_name]%%|*}"
            status=$(check_dep "$test_cmd")
            if [ "$status" -eq 1 ]; then
                echo -e "  ${GREEN}[✔]${NC} $dep_name"
                ((installed_count++))
            else
                echo -e "  ${RED}[✘]${NC} $dep_name"
                ((missing_count++))
            fi
        done
    fi

    # --- Bloque 3: Dependencias de WMM (instalables) ---
    echo -e "\n${GREEN}[WMM dependencies]${NC}"
    for dep_name in "${!WMM_DEPENDENCIES[@]}"; do
        test_cmd="${WMM_DEPENDENCIES[$dep_name]%%|*}"
        status=$(check_dep "$test_cmd")
        if [ "$status" -eq 1 ]; then
            echo -e "  ${GREEN}[✔]${NC} $dep_name"
            ((installed_count++))
        else
            echo -e "  ${RED}[✘]${NC} $dep_name"
            ((missing_count++))
        fi
    done

    echo -e "\n${GREEN}$installed_count installed${NC}, ${RED}$missing_count missing${NC}"
    return $missing_count
}
# ----------------------------------------------------------
# FUNCIÓN PARA INSTALAR LOS ARCHIVOS DE WMM
# ----------------------------------------------------------
install_files() {
    echo -e "\nCreating directory structure and copying files..."

    # Verificar que estamos en la raíz del proyecto
    if [ ! -f "$SCRIPT_DIR/wmm_platform/shell/cinnamon/metadata.cinnamon.json" ] \
       && [ ! -f "$SCRIPT_DIR/wmm_platform/shell/gnome/metadata.gnome.json" ] \
       || [ ! -d "$SCRIPT_DIR/python" ] \
       || [ ! -d "$SCRIPT_DIR/wmm_platform" ] \
       || [ ! -d "$SCRIPT_DIR/data" ] \
       || [ ! -d "$SCRIPT_DIR/help" ] \
       || [ ! -d "$SCRIPT_DIR/po" ]; then
        echo "ERROR: Project structure not found."
        echo "Make sure you run the script from the project root folder"
        echo "with all required files (metadata.*.json in wmm_platform/shell/, python/, data/, help/, po/)."
        exit 1
    fi

    # Crear los directorios necesarios
    mkdir -p "$APPLET_DIR/data" "$APPLET_DIR/python" "$APPLET_DIR/wmm_platform"
    mkdir -p "$CACHE_DIR/thumbnails"

    # Copiar todo el proyecto al destino
    cp -r "$SCRIPT_DIR"/* "$APPLET_DIR/" || {
        echo "Error copying files. Do you have write permission on $APPLET_DIR?"
        exit 1
    }
    echo "Files copied successfully."

    # Asegurar permisos de ejecución en los scripts de atajo
    find "$APPLET_DIR/wmm_platform/shell/" -name "*.sh" -exec chmod +x {} \;
    echo "Execution permissions set for shell scripts."

    # Copiar el metadata.json y el JS correspondiente al escritorio
    case "$DESKTOP" in
        cinnamon)
            cp -f "$SCRIPT_DIR/wmm_platform/shell/cinnamon/metadata.cinnamon.json" "$APPLET_DIR/metadata.json"
            cp -f "$SCRIPT_DIR/wmm_platform/shell/cinnamon/applet.js" "$APPLET_DIR/applet.js"
            echo "Archivos de Cinnamon copiados a $APPLET_DIR."
            ;;
        gnome)
            cp -f "$SCRIPT_DIR/wmm_platform/shell/gnome/metadata.gnome.json" "$APPLET_DIR/metadata.json"
            cp -f "$SCRIPT_DIR/wmm_platform/shell/gnome/extension.js" "$APPLET_DIR/extension.js"
            echo "Archivos de GNOME copiados a $APPLET_DIR."
            ;;
    esac

    # Limpiar archivos de desarrollo...
    find "$APPLET_DIR" -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null
    find "$APPLET_DIR" -type f -name "*.pyc" -delete 2>/dev/null
    echo "Development files cleaned."

    # Asegurar que el .ini existe en el destino
    if [ ! -f "$APPLET_DIR/data/settings_core.ini" ]; then
        cp "$INI_FILE" "$APPLET_DIR/data/settings_core.ini"
        echo "Platform configuration copied."
    fi

    echo -e "${GREEN}Installation files ready.${NC}"
}

# ----------------------------------------------------------
# SCRIPT START
# ----------------------------------------------------------
clear
echo "=============================================="
echo "  WMM - Wallpaper Multi-Monitor Manager"
echo "  Dependency Check"
echo "=============================================="

# First pass: show current status
print_checklist
missing=$?

if [ $missing -eq 0 ]; then
    install_files
    echo -e "\n=============================================="
    echo "  Installation completed successfully!"
    echo "  WMM has been installed at: $APPLET_DIR"
    echo "=============================================="
    case "$DESKTOP" in
        cinnamon)
            echo -e "\nTo enable the applet, go to Cinnamon Applets settings"
            echo "and activate 'WMM Manager'."
            ;;
        gnome)
            echo -e "\nTo enable the extension, restart your session,"
            echo "open GNOME Extensions and enable 'WMM Manager'."
            ;;
        *)
            echo -e "\nRestart your session to load the applet/extension."
            ;;
    esac

    echo ""
    read -p "Press Enter to exit..." dummy
    exit 0
fi

# If dependencies are missing, ask whether to install them
echo -e "\nDo you want to install the missing dependencies? (y/n)"
read -p "Option: " answer || true
if [ "$answer" != "y" ] && [ "$answer" != "Y" ]; then
    echo "Installation cancelled. No dependencies will be installed."
    echo "You can install them manually later."
    exit 1
fi

# Attempt to install the missing dependencies
echo -e "\nInstalling dependencies..."

# Detect package manager
if command -v apt &> /dev/null; then
    PKG_MANAGER="apt"
    INSTALL_CMD="sudo apt install -y"
elif command -v dnf &> /dev/null; then
    PKG_MANAGER="dnf"
    INSTALL_CMD="sudo dnf install -y"
elif command -v pacman &> /dev/null; then
    PKG_MANAGER="pacman"
    INSTALL_CMD="sudo pacman -Sy --noconfirm"
    # Package name mapping for Arch
    declare -A PACMAN_MAP
    PACMAN_MAP=(
        ["python3"]="python"
        ["python3-pillow"]="python-pillow"
        ["python3-numpy"]="python-numpy"
        ["libnotify-bin"]="libnotify"
        ["gnome-shell-extension-prefs"]="gnome-shell-extensions"
    )
else
    echo "Could not detect package manager."
    echo "Please install the packages listed above manually."
    exit 1
fi

# Build list of missing packages (from WMM_DEPENDENCIES and GNOME_DEPENDENCIES)
MISSING_PKGS=""
for dep_name in "${!WMM_DEPENDENCIES[@]}" "${!GNOME_DEPENDENCIES[@]}"; do
    # Obtener el comando de verificación y el nombre del paquete
    if [ -n "${WMM_DEPENDENCIES[$dep_name]}" ]; then
        test_cmd="${WMM_DEPENDENCIES[$dep_name]%%|*}"
        packages="${WMM_DEPENDENCIES[$dep_name]##*|}"
    else
        test_cmd="${GNOME_DEPENDENCIES[$dep_name]%%|*}"
        packages="${GNOME_DEPENDENCIES[$dep_name]##*|}"
    fi
    status=$(check_dep "$test_cmd")
    if [ "$status" -eq 0 ]; then
        if [ "$PKG_MANAGER" = "pacman" ]; then
            for pkg in $packages; do
                MISSING_PKGS="$MISSING_PKGS ${PACMAN_MAP[$pkg]:-$pkg}"
            done
        else
            MISSING_PKGS="$MISSING_PKGS $packages"
        fi
    fi
done

# Install
if [ -n "$MISSING_PKGS" ]; then
    echo "Running: $INSTALL_CMD $MISSING_PKGS"
    $INSTALL_CMD $MISSING_PKGS
else
    echo "No pending packages."
fi

# Second pass: verify after installation
echo -e "\nVerifying dependencies after installation..."
print_checklist
missing=$?

if [ $missing -eq 0 ]; then
    echo "All dependencies have been successfully installed."
    install_files
    echo -e "\n=============================================="
    echo "  Installation completed successfully!"
    echo "  WMM has been installed at: $APPLET_DIR"
    echo "=============================================="
    case "$DESKTOP" in
        cinnamon)
            echo -e "\nTo enable the applet, go to Cinnamon Applets settings"
            echo "and activate 'WMM Manager'."
            ;;
        gnome)
            echo -e "\nTo enable the extension, restart your session,"
            echo "open GNOME Extensions and enable 'WMM Manager'."
            ;;
        *)
            echo -e "\nRestart your session to load the applet/extension."
            ;;
    esac

    echo ""
    read -p "Press Enter to exit..." dummy
    exit 0
else
    echo -e "\nSome dependencies could not be installed."
    echo "Check the error messages and try manually."
    exit 1
fi
