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

# ==============================
# OASIS — Lanzador GUI (simple) + Desktop Entry
# ==============================

REPO_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
INSTALLER_SH="$REPO_DIR/INSTALLER/installer_oasis.sh"

# Colores y símbolos (logs bonitos)
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="⚠"

APP_NAME="OASIS"                      # Nombre de la aplicación
DESKTOP_ID="oasis.desktop"            # fichero .desktop
DESKTOP_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/applications"
ICON_THEME_DIR="${XDG_DATA_HOME:-$HOME/.local/share}/icons/hicolor"
ICON_REL_PATH="256x256/apps"          # carpeta dentro de hicolor
ICON_BASENAME="oasis-logo.png"        # preferido
STARTUP_WM_CLASS="OasisInstaller"     # coincide con yad --name/--class del installer

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 pueden necesitar privilegios para instalar paquetes."; }

install_pkgs_apt()    { need_root_msg; sudo apt-get update && sudo apt-get install -y yad hicolor-icon-theme xdg-user-dirs; }
install_pkgs_pacman() { need_root_msg; sudo pacman -Sy --noconfirm yad hicolor-icon-theme xdg-user-dirs; }
install_pkgs_dnf()    { need_root_msg; sudo dnf install -y yad hicolor-icon-theme xdg-user-dirs; }
install_pkgs_zypper() { need_root_msg; sudo zypper --non-interactive install yad 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 GUI ════════╗${C_RESET}"
  local missing=()

  log_dep "yad" "have yad" || missing+=("yad")
  log_dep "hicolor-icon-theme" "check_hicolor" || missing+=("hicolor-icon-theme")
  log_dep "xdg-user-dirs-update" "have xdg-user-dirs-update" || missing+=("xdg-user-dirs")

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

  if ((${#missing[@]})); then
    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
}

# ---------- Icono: localizar el mejor candidato en el repo ----------
find_repo_icon() {
  local base="$REPO_DIR/INSTALLER/icons/hicolor/$ICON_REL_PATH"
  local candidates=(
    "$base/$ICON_BASENAME"
    "$base/oasis-hero.png"
    "$base/ecoin.png"
    "$base/oasis-logo.png"
  )
  local c
  for c in "${candidates[@]}"; do
    [[ -f "$c" ]] && { echo "$c"; return 0; }
  done
  # fallback a los que están junto al installer por si acaso
  local f2
  for f2 in "$REPO_DIR/INSTALLER/oasis-logo.png" "$REPO_DIR/INSTALLER/oasis-ecoin.png" "$REPO_DIR/INSTALLER/ecoin.png"; do
    [[ -f "$f2" ]] && { echo "$f2"; return 0; }
  done
  return 1
}

# ---------- Instalar/actualizar icono e .desktop en el perfil del usuario ----------
install_user_shortcut() {
  echo -e "${C_INFO}╔════════ REGISTRO EN MENÚ DE APLICACIONES ════════╗${C_RESET}"

  mkdir -p "$DESKTOP_DIR"
  mkdir -p "$ICON_THEME_DIR/$ICON_REL_PATH"

  local src_icon dst_icon icon_name_noext
  if src_icon="$(find_repo_icon)"; then
    icon_name_noext="$(basename "$src_icon")"
    icon_name_noext="${icon_name_noext%.*}"          # sin extensión
    # Usaremos 'oasis-logo' como nombre lógico de icono (sin extensión)
    dst_icon="$ICON_THEME_DIR/$ICON_REL_PATH/oasis-logo.png"
    cp -f "$src_icon" "$dst_icon"
    echo -e "  ${OK} Icono copiado: $dst_icon"
  else
    echo -e "  ${WARN} Icono no encontrado en el repo. Se usará ruta absoluta si es necesario."
    dst_icon=""  # forzará usar ruta absoluta si tenemos alguna
  fi

  # Construir .desktop (Icon= por nombre si está en hicolor; si no, por ruta absoluta)
  local desktop_file="$DESKTOP_DIR/$DESKTOP_ID"
  local icon_line
  if [[ -n "${dst_icon:-}" && -f "$dst_icon" ]]; then
    icon_line="Icon=oasis-logo"
  else
    # último intento: usa alguno relativo al repo si existe
    local repo_icon_fallback; repo_icon_fallback="$(find_repo_icon || true)"
    if [[ -n "${repo_icon_fallback:-}" ]]; then
      icon_line="Icon=${repo_icon_fallback}"
    else
      icon_line="Icon=application-default-icon"
    fi
  fi

  cat > "$desktop_file" <<EOF
[Desktop Entry]
Type=Application
Name=${APP_NAME}
Comment=OASIS Installer & Launcher
Exec=${INSTALLER_SH}
Terminal=false
${icon_line}
Categories=Utility;Network;
StartupWMClass=${STARTUP_WM_CLASS}
Keywords=Oasis;Solar;Net;Hub;Installer;
EOF

  echo -e "  ${OK} Desktop entry: $desktop_file"

  # Refrescar caches si están disponibles (no es crítico si faltan)
  if have update-desktop-database; then
    update-desktop-database "${DESKTOP_DIR%/applications}" >/dev/null 2>&1 || true
  fi
  if have gtk-update-icon-cache; then
    gtk-update-icon-cache -f "$ICON_THEME_DIR" >/dev/null 2>&1 || true
  fi

  # Integración adicional para algunos desktops
  if have xdg-icon-resource; then
    # (No imprescindible al copiar en hicolor, pero ayuda si el tema activo no indexa)
    xdg-icon-resource install --size 256 "$ICON_THEME_DIR/$ICON_REL_PATH/oasis-logo.png" "oasis-logo" >/dev/null 2>&1 || true
  fi

  echo -e "${C_OK}${OK}${C_RESET} Registrado en el menú de aplicaciones como “${APP_NAME}”.\n"
}

launch_installer() {
  have xdg-user-dirs-update && xdg-user-dirs-update >/dev/null 2>&1 || true
  echo -e "${C_INFO}▶ Lanzando instalador gráfico (OASIS)…${C_RESET}"
  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
install_user_shortcut
launch_installer
