#!/usr/bin/env bash
set -euo pipefail

# ==============================
# OASIS — Lanzador del instalador GUI (con logs)
# ==============================
REPO_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
INSTALLER_SH="$REPO_DIR/INSTALLER/installer.sh"

# Colores y símbolos
C_RESET='\033[0m'; C_OK='\033[1;32m'; C_FAIL='\033[1;31m'; C_WARN='\033[1;33m'; C_INFO='\033[1;36m'
OK="✔"; FAIL="✘"; WARN="⚠"

have() { command -v "$1" >/dev/null 2>&1; }
pm_name() {
  if have apt-get; then echo "apt";
  elif have pacman; then echo "pacman";
  elif have dnf; then echo "dnf";
  elif have zypper; then echo "zypper";
  else echo "unknown"; fi
}

need_root_msg() {
  echo -e "${C_WARN}${WARN}${C_RESET} Se necesitan privilegios de administrador para instalar paquetes."
}

install_pkgs_apt()    { need_root_msg; sudo apt-get update && sudo apt-get install -y yad policykit-1 hicolor-icon-theme xdg-user-dirs; }
install_pkgs_pacman() { need_root_msg; sudo pacman -Sy --noconfirm yad polkit hicolor-icon-theme xdg-user-dirs; }
install_pkgs_dnf()    { need_root_msg; sudo dnf install -y yad polkit hicolor-icon-theme xdg-user-dirs; }
install_pkgs_zypper() { need_root_msg; sudo zypper --non-interactive install yad polkit hicolor-icon-theme xdg-user-dirs; }

check_hicolor() {
  if have dpkg; then dpkg -s hicolor-icon-theme >/dev/null 2>&1; return $?;
  elif have rpm; then rpm -q hicolor-icon-theme >/dev/null 2>&1; return $?;
  else return 0; fi
}

log_dep() {  # $1=nombre $2=cmd/test
  if eval "$2"; then
    printf "  %b %s %-22s%s\n" "${C_OK}${OK}${C_RESET}" "|" "$1" "${C_OK}[OK]${C_RESET}"
  else
    printf "  %b %s %-22s%s\n" "${C_FAIL}${FAIL}${C_RESET}" "|" "$1" "${C_FAIL}[FALTA]${C_RESET}"
    return 1
  fi
}

ensure_deps() {
  echo -e "${C_INFO}╔════════ DEPENDENCIAS DEL VISOR (GUI) ════════╗${C_RESET}"
  local missing=()

  log_dep "yad" "have yad" || missing+=("yad")
  log_dep "pkexec/polkit" "have pkexec || have polkit" || missing+=("policykit-1")
  log_dep "xdg-user-dirs-update" "have xdg-user-dirs-update" || missing+=("xdg-user-dirs")
  log_dep "hicolor-icon-theme" "check_hicolor" || missing+=("hicolor-icon-theme")

  printf "  └ Gestor detectado: %s\n\n" "$(pm_name)"

  if ((${#missing[@]})); then
    echo -e "${C_WARN}${WARN}${C_RESET} Paquetes a instalar: ${missing[*]}"
    if have apt-get; then install_pkgs_apt
    elif have pacman; then install_pkgs_pacman
    elif have dnf; then install_pkgs_dnf
    elif have zypper; then install_pkgs_zypper
    else
      echo -e "${C_FAIL}${FAIL}${C_RESET} Gestor no soportado. Instala manualmente: ${missing[*]}"
      exit 1
    fi
    echo
  else
    echo -e "${C_OK}${OK}${C_RESET} Todo listo. Sin instalaciones extra.\n"
  fi
}

preflight() {
  echo -e "${C_INFO}╔════════ PRE-FLIGHT ════════╗${C_RESET}"
  printf "  %s Repo dir:      %s\n" "|" "$REPO_DIR"
  printf "  %s Installer.sh:  %s\n" "|" "$INSTALLER_SH"
  printf "  %s DISPLAY:       %s\n" "|" "${DISPLAY:-<vacío>}"
  printf "  %s Sesión:        %s / %s\n\n" "|" "${XDG_SESSION_TYPE:-?}" "${DESKTOP_SESSION:-?}"

  if [[ ! -f "$INSTALLER_SH" ]]; then
    echo -e "${C_FAIL}${FAIL}${C_RESET} No existe: $INSTALLER_SH"
    echo "  Asegúrate de clonar el repo con la carpeta INSTALLER completa."
    exit 1
  fi
  if [[ ! -x "$INSTALLER_SH" ]]; then chmod +x "$INSTALLER_SH"; fi
}

launch_installer() {
  have xdg-user-dirs-update && xdg-user-dirs-update >/dev/null 2>&1 || true
  echo -e "${C_INFO}▶ Lanzando instalador gráfico...${C_RESET}"
  # Si exec falla, mostramos error y salimos
  exec "$INSTALLER_SH" || {
    echo -e "${C_FAIL}${FAIL}${C_RESET} No se pudo ejecutar: $INSTALLER_SH"
    exit 1
  }
}

echo -e "${C_INFO}== OASIS :: Preparando GUI Installer ==${C_RESET}"
preflight
ensure_deps
launch_installer
