#!/usr/bin/env bash
# =============================================================
# SOLAR NET HUB — Panel de control (lanzador)
# Lanza panel.py si python3-gi está disponible;
# si no, lo instala y reintenta.
# =============================================================
set -euo pipefail

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

C_RESET='\033[0m'
C_OK='\033[1;32m'
C_FAIL='\033[1;31m'
C_WARN='\033[1;33m'
C_INFO='\033[1;36m'

have(){ command -v "$1" >/dev/null 2>&1; }

# ── Instalar fuente Dune Rise (usuario, sin root) ─────────────────────────
install_font(){
  local src="$REPO_DIR/INSTALLER/Dune_Rise.otf"
  local dst="$HOME/.local/share/fonts/Dune_Rise.otf"
  if [ -f "$src" ] && [ ! -f "$dst" ]; then
    mkdir -p "$HOME/.local/share/fonts"
    cp -f "$src" "$dst"
    fc-cache -f >/dev/null 2>&1 || true
  fi
}

# ── Verificar / instalar python3-gi ──────────────────────────────────────
check_gi(){
  python3 -c "import gi; gi.require_version('Gtk','3.0'); from gi.repository import Gtk" \
    >/dev/null 2>&1
}

install_gi(){
  echo -e "${C_WARN}⚠  python3-gi no encontrado. Instalando…${C_RESET}"
  if have apt-get;  then sudo apt-get install -y python3-gi python3-gi-cairo gir1.2-gtk-3.0
  elif have pacman; then sudo pacman -Sy --noconfirm python-gobject
  elif have dnf;    then sudo dnf install -y python3-gobject gtk3
  elif have zypper; then sudo zypper --non-interactive install python3-gobject gtk3
  else
    echo -e "${C_FAIL}✘  Gestor de paquetes no soportado.${C_RESET}"
    echo    "   Instala manualmente: python3-gi / python-gobject"
    exit 1
  fi
}

# ── Verificar DISPLAY / Wayland ───────────────────────────────────────────
check_display(){
  if [ -z "${DISPLAY:-}" ] && [ -z "${WAYLAND_DISPLAY:-}" ]; then
    echo -e "${C_FAIL}✘  No hay sesión gráfica (DISPLAY/WAYLAND_DISPLAY vacíos).${C_RESET}"
    echo    "   Ejecuta este script desde tu escritorio o una terminal gráfica."
    exit 1
  fi
}

# ── Main ─────────────────────────────────────────────────────────────────
echo -e "${C_INFO}== SOLAR NET HUB :: Panel de Control ==${C_RESET}"

check_display

install_font 2>/dev/null || true

if ! check_gi; then
  install_gi
  if ! check_gi; then
    echo -e "${C_FAIL}✘  No se pudo cargar python3-gi tras la instalación.${C_RESET}"
    echo    "   Intenta cerrar sesión y volver a entrar, o instala python3-gi manualmente."
    exit 1
  fi
fi

echo -e "${C_OK}✔  python3-gi listo. Lanzando panel…${C_RESET}"
exec python3 "$PANEL_PY" "$@"
