#!/usr/bin/env bash
# =============================================================
# SOLAR NET HUB — Panel v3 (WebKit2GTK)
# =============================================================
set -euo pipefail

REPO_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
PANEL_PY="$REPO_DIR/INSTALLER_V3/panel.py"
FONT_SRC="$REPO_DIR/INSTALLER_V3/Dune_Rise.otf"
ICON_SRC="$REPO_DIR/INSTALLER_V3/oasis-logo.png"
APPS_DIR="$HOME/.local/share/applications"
ICONS_DIR="$HOME/.local/share/icons/hicolor/256x256/apps"

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

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

check_display(){
  [ -n "${DISPLAY:-}" ] || [ -n "${WAYLAND_DISPLAY:-}" ] && return
  echo -e "${C_FAIL}✘  Sin sesión gráfica.${C_RESET}"; exit 1
}

install_font(){
  local dst="$HOME/.local/share/fonts/Dune_Rise.otf"
  [ -f "$FONT_SRC" ] && [ ! -f "$dst" ] && {
    mkdir -p "$HOME/.local/share/fonts"
    cp -f "$FONT_SRC" "$dst"
    fc-cache -f >/dev/null 2>&1 || true
    echo -e "${C_OK}✔  Fuente Dune Rise instalada.${C_RESET}"
  }
}

check_webkit(){
  python3 -c "
import gi
for v in ('4.1','4.0'):
    try:
        gi.require_version('WebKit2', v)
        from gi.repository import WebKit2
        print(v)
        break
    except Exception:
        pass
" 2>/dev/null
}

install_webkit(){
  echo -e "${C_WARN}⚠  WebKit2GTK no encontrado. Instalando...${C_RESET}"
  if have apt-get; then
    sudo apt-get install -y python3-gi python3-gi-cairo \
      gir1.2-webkit2-4.0 libwebkit2gtk-4.0-dev 2>/dev/null || \
    sudo apt-get install -y python3-gi python3-gi-cairo \
      gir1.2-webkit2-4.1 libwebkit2gtk-4.1-dev 2>/dev/null
  elif have pacman; then
    sudo pacman -Sy --noconfirm webkit2gtk python-gobject
  elif have dnf; then
    sudo dnf install -y python3-gobject webkit2gtk4.0
  elif have zypper; then
    sudo zypper --non-interactive install python3-gobject webkit2gtk3
  else
    echo -e "${C_FAIL}✘  Instala manualmente: gir1.2-webkit2-4.0${C_RESET}"
    exit 1
  fi
}

register_desktop(){
  mkdir -p "$APPS_DIR" "$ICONS_DIR"
  [ -f "$ICON_SRC" ] && cp -f "$ICON_SRC" "$ICONS_DIR/oasis.png"

  # Borrar entradas antiguas con nombres distintos
  rm -f "$APPS_DIR/solarnethub.desktop" \
        "$APPS_DIR/solarnethub-panel.desktop" \
        "$APPS_DIR/INSTALLER.desktop" \
        "$APPS_DIR/oasis.desktop"

  cat > "$APPS_DIR/oasis-panel.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=OASIS
GenericName=OASIS Panel
Comment=Panel de control OASIS y ECOIN
Exec=/bin/bash -lc '$REPO_DIR/start_panel_v3.sh'
Icon=oasis
Terminal=false
Categories=Network;System;Utility;
Keywords=oasis;ecoin;solar;hub;
StartupWMClass=oasis-panel
StartupNotify=true
EOF

  # Copiar al Escritorio si existe
  local desk
  desk="$(xdg-user-dir DESKTOP 2>/dev/null || echo "$HOME/Desktop")"
  [ -d "$desk" ] && cp -f "$APPS_DIR/oasis-panel.desktop" "$desk/" && \
    chmod +x "$desk/oasis-panel.desktop" 2>/dev/null || true

  have update-desktop-database && \
    update-desktop-database "$APPS_DIR" >/dev/null 2>&1 || true
  have gtk-update-icon-cache && \
    gtk-update-icon-cache -f "$HOME/.local/share/icons/hicolor" >/dev/null 2>&1 || true

  echo -e "${C_OK}✔  Registrado en el menú como 'Solar Net Hub'${C_RESET}"
}

# ── Main ──────────────────────────────────────────────────────
echo -e "${C_INFO}== SOLAR NET HUB :: Panel v3 (WebKit2GTK) ==${C_RESET}"

check_display
install_font 2>/dev/null || true
register_desktop 2>/dev/null || true

WK_VER="$(check_webkit)"
if [ -z "$WK_VER" ]; then
  install_webkit
  WK_VER="$(check_webkit)"
  [ -z "$WK_VER" ] && {
    echo -e "${C_FAIL}✘  WebKit2GTK no disponible tras instalación.${C_RESET}"
    exit 1
  }
fi

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