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

# =========================
# OASIS Installer (simple)
# =========================

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
: "${SELF:=$SCRIPT_DIR/installer_oasis.sh}"

INSTALLER_DIR="$SCRIPT_DIR"
CSS_SOURCE="$INSTALLER_DIR/gtk_oasis.css"

# Imagen/icono
HERO_FILE="$INSTALLER_DIR/oasis-logito.png"; [ -f "$HERO_FILE" ] || HERO_FILE="$INSTALLER_DIR/oasis-logo.png"
WINDOW_ICON="$INSTALLER_DIR/oasis-logo.png"

# Tema / ventana
NAME="OasisInstaller"
THEME_NAME="SolarOasis"
YAD_THEME="${THEME_NAME}:dark"

# Repo (se mantiene por compatibilidad con funciones existentes)
OASIS_REPO_DEFAULT="https://code.03c8.net/KrakensLab/oasis.git"

# Estado persistente
STATE_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/oasis-installer"
STATE_FILE="$STATE_DIR/state"
mkdir -p "$STATE_DIR"

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

# ===== NUEVO: chequeo de npm (único cambio funcional pedido) =====
npm_ok(){
  # Permite forzar el estado "no instalado" para pruebas:
  #   OASIS_FORCE_INSTALL=1 ./INSTALLER/installer_oasis.sh
  if [ "${OASIS_FORCE_INSTALL:-0}" = "1" ]; then
    return 1
  fi
  have npm && npm -v >/dev/null 2>&1
}

# ---------- Preflight ----------
preflight(){
  # DISPLAY “de cortesía”
  if [ -z "${DISPLAY:-}" ]; then export DISPLAY=":0"; fi
  # YAD disponible?
  if ! have yad; then
    echo "✘ Falta 'yad'. Instálalo y vuelve a ejecutar." >&2
    exit 1
  fi
}

ensure_basics(){
  local miss=()
  have yad || miss+=("yad")
  command -v pkexec >/dev/null 2>&1 || miss+=("policykit-1")
  have xdg-user-dirs-update || miss+=("xdg-user-dirs")
  if command -v dpkg >/dev/null 2>&1; then
    dpkg -s hicolor-icon-theme >/dev/null 2>&1 || miss+=("hicolor-icon-theme")
  fi
  if ((${#miss[@]})); then
    if have apt-get; then
      if have pkexec; then pkexec bash -lc "apt-get update && apt-get install -y ${miss[*]}";
      else sudo apt-get update && sudo apt-get install -y "${miss[@]}"; fi
    fi
  fi
}

ensure_theme(){
  local tdir="$HOME/.themes/${THEME_NAME}/gtk-3.0"
  mkdir -p "$tdir"
  if [ -f "$CSS_SOURCE" ]; then
    sed 's/\r$//' "$CSS_SOURCE" > "$tdir/gtk.css"
  else
    cat > "$tdir/gtk.css" <<'CSS'
*{background:#000;color:#E6E6E6;font-family:"Dune Rise","Cantarell","Ubuntu","DejaVu Sans",sans-serif;font-size:13pt}
grid{padding:18px}
button{
  border:2px solid #FF4E00; border-radius:14px; background:#000; color:#FF4E00;
  min-width:380px; min-height:46px; margin:10px 0; letter-spacing:.5px;
}
button:hover{ background:#27D980; color:#000; }
button:active{ background:#FF4E00; color:#000; }
image{ margin:8px auto 6px auto; }
CSS
  fi
}

# YAD wrapper
yad_cmd(){ GTK_THEME="$YAD_THEME" NO_AT_BRIDGE=1 yad --name="$NAME" --class="$NAME" "$@"; }

# -------- Detección / estado de OASIS --------
oasis_is_installed_dir(){
  local d="$1"
  [[ -f "$d/oasis.sh" ]] || [[ -f "$d/src/server/server.js" ]] || [[ -d "$d/src/server/node_modules" ]]
}

save_oasis_dir(){
  local d="$1"
  mkdir -p "$STATE_DIR"
  {
    echo "OASIS_DIR=$d"
    date +"SAVED=%Y-%m-%dT%H:%M:%S"
  } > "$STATE_FILE"
}

read_saved_dir(){
  [ -f "$STATE_FILE" ] && sed -n 's/^OASIS_DIR=//p' "$STATE_FILE" | head -n1 || true
}

guess_oasis_dir(){
  local cands=()

  # 1) Padre del installer (estructura estándar)
  cands+=("$SCRIPT_DIR/..")

  # 2) Guardado previo
  local saved; saved="$(read_saved_dir || true)"
  [ -n "${saved:-}" ] && cands+=("$saved")

  # 3) Candidatas típicas
  cands+=("$HOME/COFRE/CODERS/oasis" "$HOME/oasis" "$HOME/Projects/oasis" "$HOME/Documentos/oasis")

  local d
  for d in "${cands[@]}"; do
    d="$(cd "$d" 2>/dev/null && pwd || true)"
    [ -n "$d" ] || continue
    if oasis_is_installed_dir "$d"; then
      echo "$d"; return 0
    fi
  done
  echo "$HOME/oasis"
}

# -------- Comandos auxiliares existentes (sin cambios) --------
node_setup_cmd(){ cat <<'EOF'
set -e
apt-get update
apt-get install -y git curl ca-certificates tar gnupg
curl -fsSL https://deb.nodesource.com/setup_22.x | bash -
apt-get install -y nodejs
node -v && npm -v
EOF
}

oasis_install_cmd(){ cat <<EOF
set -e
if [ ! -d "$2/.git" ]; then git clone --depth 1 "$1" "$2"; else cd "$2" && git pull --rebase || true; fi
cd "$2/src/server"
npm install .
npm audit fix || true
EOF
}

oasis_start_cmd(){ cat <<'EOF'
set -e
DIR="$1"
PORT="${2:-3000}"

# ¿Ya está levantado?
if ss -lnt sport = :$PORT | grep -q "$PORT"; then
  echo "Oasis ya está escuchando en $PORT"
else
  nohup bash -lc "cd \"$DIR\" && exec bash oasis.sh" > /tmp/oasis_gui.log 2>&1 &
  for i in $(seq 1 30); do
    if ss -lnt sport = :$PORT | grep -q "$PORT"; then
      echo "Oasis levantado en $PORT"
      break
    fi
    sleep 1
  done
fi

# Abrir navegador siempre
xdg-open "http://localhost:$PORT" >/dev/null 2>&1 || true
EOF
}

progress_user(){ bash -lc "$2" 2>&1 | yad_cmd --progress --title="$1" --pulsate --auto-close --no-buttons --width=700 --height=180 --center; }
progress_root(){ pkexec bash -lc "$2" 2>&1 | yad_cmd --progress --title="$1" --pulsate --auto-close --no-buttons --width=700 --height=180 --center; }

oasis_quick_install(){
  local dir="$1"
  progress_root "OASIS: Node.js 22" "$(node_setup_cmd)"
  progress_user "OASIS: Clonar + npm" "$(oasis_install_cmd "$OASIS_REPO_DEFAULT" "$dir")"
  save_oasis_dir "$dir"
}

oasis_quick_start(){
  local dir="$1"
  progress_user "OASIS: Abrir" "$(oasis_start_cmd "$dir" 3000)"
}

# -------- UI --------
home_oasis_dialog(){
  local OASIS_DIR; OASIS_DIR="$(guess_oasis_dir)"
  save_oasis_dir "$OASIS_DIR"

  local O_VER="—"
  if [ -f "$OASIS_DIR/src/server/package.json" ]; then
    O_VER="$(sed -n 's/.*"version"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$OASIS_DIR/src/server/package.json" | head -n1)"
    [ -z "$O_VER" ] && O_VER="—"
  fi

  # Subcomandos (OPEN se mantiene EXACTO como antes)
  local BTN_OPEN_SITE="/bin/bash -lc '$SELF --open-site'"
  local BTN_INSTALL="/bin/bash -lc '$SELF --do-install'"
  local BTN_OPEN="/bin/bash -lc '$SELF --open-now'"

  # ===== ÚNICO CAMBIO: decidir etiqueta/acción de INSTALL según npm =====
  local INSTALL_LABEL="INSTALL:BTN"
  if npm_ok; then
    INSTALL_LABEL="ALREADY INSTALLED:BTN"
    BTN_INSTALL="/bin/true"
  fi
  # (No tocamos BTN_OPEN)

  yad_cmd \
    --title="SOLAR NET HUB" --window-icon="$WINDOW_ICON" \
    --center --width=720 --height=600 \
    --image="$HERO_FILE" --image-on-top \
    --form --borders=16 --columns=1 --align=center \
    \
    --field="OASIS PROJECT:BTN"  "$BTN_OPEN_SITE" \
    --field="$INSTALL_LABEL"     "$BTN_INSTALL" \
    --field="OPEN:BTN"           "$BTN_OPEN" \
    --field="VERSION ( $O_VER ):BTN" "/bin/true" \
    \
    --buttons-layout=center \
    --button="CERRAR:0"
}

# -------- Subcomandos --------
case "${1:-}" in
  --open-site)
    xdg-open "https://oasis-project.pub" >/dev/null 2>&1 || true
    exit 0
    ;;
  --do-install)
    preflight; ensure_basics; ensure_theme
    # Ejecutar el install.sh del raíz del repo (padre de INSTALLER)
    if [ -f "$SCRIPT_DIR/../install.sh" ]; then
      /bin/bash -lc "cd \"$SCRIPT_DIR/..\" && bash install.sh"
    else
      yad_cmd --error --title="OASIS Installer" --text="No se encontró install.sh en $SCRIPT_DIR/.."
      exit 1
    fi
    # Guardar ruta para OPEN
    dir="$(cd "$SCRIPT_DIR/.." && pwd)"
    save_oasis_dir "$dir"
    exit 0
    ;;
  --open-now)
    preflight; ensure_basics; ensure_theme
    dir="$(read_saved_dir)"; [ -n "${dir:-}" ] || dir="$(guess_oasis_dir)"
    save_oasis_dir "$dir"
    oasis_quick_start "$dir"
    exit 0
    ;;
  *)
    preflight; ensure_basics; ensure_theme
    home_oasis_dialog
    ;;
esac
