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

# =========================
# SOLAR NET HUB - Installer
# =========================

# --- Rutas ---
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &>/dev/null && pwd)"
: "${SELF:=$SCRIPT_DIR/installer.sh}"                 # ruta absoluta a este script
INSTALLER_DIR="$SCRIPT_DIR"
CSS_SOURCE="$INSTALLER_DIR/gtk.css"
HERO_IMAGE="$INSTALLER_DIR/oasis-ecoin.png"         # imagen con los dos logos (head)

# ICONOS INDIVIDUALES (se usan en ensure_local_icons y en el .desktop)
ICON_OASIS="$INSTALLER_DIR/oasis-logo.png"
ICON_ECOIN="$INSTALLER_DIR/ecoin.png"

APPS_DIR="$HOME/.local/share/applications"
DESKTOP_DIR="$(xdg-user-dir DESKTOP 2>/dev/null || echo "$HOME/Desktop")"

# --- Tema local (no toca sistema) ---
NAME="SolarHubInstaller"
THEME_NAME="SolarHub"
YAD_THEME="${THEME_NAME}:dark"
ORANGE="#FF4E00"
GREEN="#27D980"

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

# Iconos locales (sin instalar nada en el sistema/usuario)
ensure_local_icons(){
  local base="$INSTALLER_DIR/icons/hicolor/256x256/apps"
  local idx="$INSTALLER_DIR/icons/hicolor/index.theme"
  mkdir -p "$base"
  install -m 0644 "$ICON_OASIS" "$base/oasis-logo.png"
  install -m 0644 "$ICON_ECOIN" "$base/ecoin.png"
  cat > "$idx" <<'EOF'
[Icon Theme]
Name=Hicolor
Comment=Local fallback for Solar Net Hub
Directories=256x256/apps

[256x256/apps]
Size=256
Context=Applications
Type=Fixed
EOF
  # Hacer visible este tema SOLO para este proceso y descendientes
  export GTK_ICON_THEME_PATH="$INSTALLER_DIR/icons${GTK_ICON_THEME_PATH:+:$GTK_ICON_THEME_PATH}"
}

pkg_install(){
  local pkgs=("$@")
  if have apt-get; then
    if have pkexec; then pkexec bash -lc "apt-get update && apt-get install -y ${pkgs[*]}" || sudo apt-get update && sudo apt-get install -y "${pkgs[@]}";
    else sudo apt-get update && sudo apt-get install -y "${pkgs[@]}"; fi
  elif have pacman; then
    if have pkexec; then pkexec bash -lc "pacman -Sy --noconfirm ${pkgs[*]}" || sudo pacman -Sy --noconfirm "${pkgs[@]}";
    else sudo pacman -Sy --noconfirm "${pkgs[@]}"; fi
  elif have dnf; then
    if have pkexec; then pkexec bash -lc "dnf install -y ${pkgs[*]}" || sudo dnf install -y "${pkgs[@]}";
    else sudo dnf install -y "${pkgs[@]}"; fi
  elif have zypper; then
    if have pkexec; then pkexec bash -lc "zypper --non-interactive install ${pkgs[*]}" || sudo zypper --non-interactive install "${pkgs[@]}";
    else sudo zypper --non-interactive install "${pkgs[@]}"; fi
  else
    echo "❌ Gestor de paquetes no soportado." >&2; exit 1
  fi
}

ensure_basics(){
  local miss=()
  have yad || miss+=("yad")
  if ! command -v pkexec >/dev/null 2>&1; then
    if have apt-get; then miss+=("policykit-1"); else miss+=("polkit"); fi
  fi
  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")
  elif command -v rpm >/dev/null 2>&1; then
    rpm -q hicolor-icon-theme >/dev/null 2>&1 || miss+=("hicolor-icon-theme")
  fi
  if ((${#miss[@]})); then
    pkg_install "${miss[@]}"
  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:"Cantarell","Ubuntu","DejaVu Sans",sans-serif;font-size:12pt}
button{background:#FF4E00;color:#000;border:none;border-radius:16px;padding:12px 18px;font-weight:800}
button:hover{background:#ff6a26} button:active{background:#e24a00}
CSS
  fi
}

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

progress_user(){   # $1 título, $2 comando (string)
  bash -lc "$2" 2>&1 | yad_cmd --progress --title="$1" --pulsate --auto-close --no-buttons \
    --width=800 --height=260 --center
}
progress_root(){   # $1 título, $2 comando (string, root)
  pkexec bash -lc "$2" 2>&1 | yad_cmd --progress --title="$1" --pulsate --auto-close --no-buttons \
    --width=800 --height=260 --center
}

ensure_launcher(){
  mkdir -p "$APPS_DIR" "$DESKTOP_DIR"
  local ABS_INSTALLER="$SCRIPT_DIR/installer.sh"
  local ABS_ICON="$ICON_OASIS"; [ -f "$ABS_ICON" ] || ABS_ICON="$HERO_IMAGE"

  cat > "$APPS_DIR/INSTALLER.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=OASIS Installer
Comment=Install or launch OASIS & ECOIN
TryExec=/bin/bash
Exec=/bin/bash -lc '$ABS_INSTALLER'
Icon=$ABS_ICON
Terminal=false
Categories=System;Utility;
StartupNotify=true
EOF

  cp -f "$APPS_DIR/INSTALLER.desktop" "$DESKTOP_DIR/INSTALLER.desktop" 2>/dev/null || true
  chmod 644 "$APPS_DIR/INSTALLER.desktop" 2>/dev/null || true
  chmod +x "$DESKTOP_DIR/INSTALLER.desktop" 2>/dev/null || true
  command -v update-desktop-database >/dev/null 2>&1 && \
    update-desktop-database "$HOME/.local/share/applications" >/dev/null 2>&1 || true
}

ensure_user_fonts(){
  local FONTS_SRC_DIR="$INSTALLER_DIR"
  local FONTS_DST_DIR="$HOME/.local/share/fonts"
  local copied=0

  mkdir -p "$FONTS_DST_DIR"

  # Copia Dune Rise (OTF/TTF) si existe en INSTALLER
  for f in "$FONTS_SRC_DIR"/Dune_Rise.otf "$FONTS_SRC_DIR"/Dune_Rise.ttf; do
    if [ -f "$f" ]; then
      cp -f "$f" "$FONTS_DST_DIR/" && copied=1
    fi
  done

  # Refresca caché si hemos copiado algo
  if [ "$copied" = 1 ]; then
    fc-cache -f >/dev/null 2>&1 || true
  fi
}

# ========== Estado ==========
OASIS_DIR_DEFAULT="${HOME}/oasis"
OASIS_REPO_DEFAULT="https://code.03c8.net/KrakensLab/oasis.git"
OASIS_MODEL_FILE="oasis-42-1-chat.Q4_K_M.gguf"
OASIS_MODEL_TAR="${OASIS_MODEL_FILE}.tar.gz"
OASIS_MODEL_URL="https://solarnethub.com/code/models/${OASIS_MODEL_TAR}"
oasis_installed(){ local d="${1:-$OASIS_DIR_DEFAULT}"; [[ -d "$d/src/server/node_modules" && -f "$d/AI/$OASIS_MODEL_FILE" ]]; }

ECOIN_DIR_DEFAULT="${HOME}/ecoin"
ECOIN_REPO_DEFAULT="https://github.com/epsylon/ecoin"
ecoin_installed(){ local d="${1:-$ECOIN_DIR_DEFAULT}"; [[ -x "$d/ecoin/ecoin-qt" || -x "$d/ecoin/src/ecoind" ]]; }
ecoin_wallet_exists(){ [ -f "$HOME/.ecoin/wallet.dat" ]; }

# ========== OASIS ==========
node_setup_cmd(){ cat <<EOF
set -e
apt-get update
apt-get install -y git curl tar ca-certificates gnupg
curl -fsSL https://deb.nodesource.com/setup_${1}.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_model_cmd(){ cat <<EOF
set -e
MODEL_DIR="$1/AI"; mkdir -p "\$MODEL_DIR"
if [ ! -f "\$MODEL_DIR/$OASIS_MODEL_FILE" ]; then
  curl -L -o "\$MODEL_DIR/$OASIS_MODEL_TAR" "$OASIS_MODEL_URL"
  tar -xzf "\$MODEL_DIR/$OASIS_MODEL_TAR" -C "\$MODEL_DIR"
  rm "\$MODEL_DIR/$OASIS_MODEL_TAR"
fi
EOF
}
oasis_start_cmd(){ cat <<EOF
set -e
if [ -x "$1/oasis.sh" ]; then cd "$1" && exec bash oasis.sh; else cd "$1/src/server" && exec node server.js; fi
EOF
}

# ========== ECOIN ==========
ecoin_deps_cmd(){ cat <<'EOF'
set -e
apt-get update
apt-get install -y qt5-qmake qtbase5-dev qttools5-dev-tools \
  build-essential libssl-dev libssl3 libdb5.3-dev libdb5.3++-dev \
  libleveldb-dev miniupnpc libminiupnpc-dev libqrencode-dev patchelf git curl
EOF
}
ecoin_clone_or_pull_cmd(){ cat <<EOF
set -e
if [ ! -d "$2/.git" ]; then git clone "$1" "$2"; else cd "$2" && git pull --rebase || true; fi
EOF
}
ecoin_build_qt_cmd(){ cat <<EOF
set -e
cd "$1/ecoin"
QMAKE="/usr/lib/x86_64-linux-gnu/qt5/bin/qmake"; [ -x "\$QMAKE" ] || QMAKE="\$(command -v qmake || true)"
[ -n "\$QMAKE" ] || { echo "qmake no encontrado"; exit 1; }
"\$QMAKE" USE_UPNP=- USE_IPV6=- -o Makefile ecoin-qt.pro
qmake USE_UPNP=- USE_IPV6=-
make -j"\$(nproc)" || make
EOF
}
ecoin_build_daemon_cmd(){ cat <<EOF
set -e
cd "$1/ecoin/src"
make -f makefile.linux USE_UPNP=- USE_IPV6=- -j"\$(nproc)" || make -f makefile.linux USE_UPNP=- USE_IPV6=-
strip ecoind || true
EOF
}
ecoin_qt_cmd(){ cat <<EOF
set -e
if [ -x "$1/ecoin/ecoin-qt" ]; then cd "$1/ecoin" && exec ./ecoin-qt; else echo "ecoin-qt no encontrado"; fi
EOF
}
ensure_ecoin_conf_cmd(){ cat <<'EOF'
set -e
CONF="$HOME/.ecoin/ecoin.conf"
mkdir -p "$HOME/.ecoin"
if [ ! -f "$CONF" ]; then
  PW="$(tr -dc 'a-zA-Z0-9' < /dev/urandom | head -c 24)"
  cat > "$CONF" <<CFG
rpcuser=ecoinrpc
rpcpassword=${PW}
rpcallowip=127.0.0.1
testnet=0
noirc=1
listen=1
server=1
daemon=1
addnode=46.163.118.220
CFG
  chmod 600 "$CONF"
fi
EOF
}
ecoin_create_wallet_cmd(){ cat <<'EOF'
set -e
CONF="$HOME/.ecoin/ecoin.conf"
EOF
printf "%s\n" "$(ensure_ecoin_conf_cmd)"
cat <<'EOF'
if [ -x "$HOME/ecoin/ecoin/ecoin-qt" ]; then
  cd "$HOME/ecoin/ecoin" && ./ecoin-qt || true
elif [ -x "$HOME/ecoin/ecoin/src/ecoind" ]; then
  cd "$HOME/ecoin/ecoin/src" && ./ecoind -daemon || true
else
  echo "ECOIN no está compilado. Instálalo primero."
fi
EOF
}
ecoin_connect_wallet_cmd(){ cat <<'EOF'
set -e
CONF="$HOME/.ecoin/ecoin.conf"
EOF
printf "%s\n" "$(ensure_ecoin_conf_cmd)"
cat <<'EOF'
if [ -x "$HOME/ecoin/ecoin/src/ecoind" ]; then
  cd "$HOME/ecoin/ecoin/src" && ./ecoind -daemon
else
  echo "ecoind no encontrado. Abre ECOIN (Qt) o recompila."
fi
EOF
}

# ========== Flujos rápidos ==========
oasis_quick_install(){
  local major="${1:-22}" repo="${2:-$OASIS_REPO_DEFAULT}" dir="${3:-$OASIS_DIR_DEFAULT}"
  progress_root  "OASIS: Node $major" "$(node_setup_cmd "$major")"
  progress_user  "OASIS: Repo + npm"  "$(oasis_install_cmd "$repo" "$dir")"
  progress_user  "OASIS: Modelo IA"   "$(oasis_model_cmd "$dir")"
}
oasis_quick_start(){ local dir="${1:-$OASIS_DIR_DEFAULT}"; progress_user "OASIS: Arrancar" "$(oasis_start_cmd "$dir")"; }
ecoin_quick_install(){
  local repo="${1:-$ECOIN_REPO_DEFAULT}" dir="${2:-$ECOIN_DIR_DEFAULT}"
  progress_root "ECOIN: Dependencias" "$(ecoin_deps_cmd)"
  progress_user "ECOIN: Clonar/Pull"  "$(ecoin_clone_or_pull_cmd "$repo" "$dir")"
  progress_user "ECOIN: Build Qt"     "$(ecoin_build_qt_cmd "$dir")"
  progress_user "ECOIN: Build Daemon" "$(ecoin_build_daemon_cmd "$dir")"
}



# ========== Home: 2 columnas x 4 filas (orden fijo, sin vars sueltas) ==========
# ========= Home: 2 columnas x 4 filas (orden fijo + lógica básica) =========
home_single_dialog(){
  # Estados rápidos
  local O_INST=0 E_INST=0 E_WAL=0
  oasis_installed && O_INST=1
  ecoin_installed && E_INST=1
  ecoin_wallet_exists && E_WAL=1

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

  # IZQUIERDA (OASIS)
  local L1_NAME="OASIS:BTN"
  local L1_VAL="/bin/bash -lc 'xdg-open https://oasis-project.pub >/dev/null 2>&1 &'"

  local L2_NAME L2_VAL
  if (( O_INST )); then L2_NAME="INSTALADO:BTN"; L2_VAL="/bin/true"
  else                   L2_NAME="INSTALAR:BTN";  L2_VAL="/bin/bash -lc \"$SELF --oasis-install\""; fi

  local L3_NAME="ABRIR:BTN"
  local L3_VAL; (( O_INST )) && L3_VAL="/bin/bash -lc \"$SELF --oasis-start\"" || L3_VAL="/bin/true"

  local L4_NAME="VERSIÓN ( $O_VER ):BTN"
  local L4_VAL="/bin/true"

  # DERECHA (ECOIN)
  local R1_NAME="ECOIN:BTN"
  local R1_VAL="/bin/bash -lc 'xdg-open https://ecoin.03c8.net/ >/dev/null 2>&1 &'"

  local R2_NAME R2_VAL
  if (( E_INST )); then R2_NAME="INSTALADO:BTN"; R2_VAL="/bin/true"
  else                   R2_NAME="INSTALAR:BTN";  R2_VAL="/bin/bash -lc \"$SELF --ecoin-install\""; fi

  local R3_NAME="CONECTAR CARTERA:BTN"
  local R3_VAL; (( E_INST )) && R3_VAL="/bin/bash -lc \"$SELF --wallet-connect\"" || R3_VAL="/bin/true"

  local R4_NAME="ABRIR GUI:BTN"
  local R4_VAL; (( E_INST )) && R4_VAL="/bin/bash -lc \"$SELF --ecoin-gui\"" || R4_VAL="/bin/true"

  # DIÁLOGO (F1 izq, F1 dcha, F2 izq, F2 dcha, ...)
  local DIALOG_ARGS=(
    --name="$NAME" --class="$NAME"
    --title="SOLAR NET HUB" --window-icon="$ICON_OASIS"
    --center --width=1200 --height=780
    --image="$HERO_IMAGE" --image-on-top
    --form --borders=18 --columns=2 --align=center

    # Fila 1
    --field="$L1_NAME" "$L1_VAL"
    --field="$R1_NAME" "$R1_VAL"
    # Fila 2
    --field="$L2_NAME" "$L2_VAL"
    --field="$R2_NAME" "$R2_VAL"
    # Fila 3
    --field="$L3_NAME" "$L3_VAL"
    --field="$R3_NAME" "$R3_VAL"
    # Fila 4
    --field="$L4_NAME" "$L4_VAL"
    --field="$R4_NAME" "$R4_VAL"

    --buttons-layout=center
    --button="Cerrar:0"
  )

  yad_cmd "${DIALOG_ARGS[@]}"
}


# ========== Entrypoint ==========
ensure_basics
ensure_user_fonts   2>/dev/null || true
ensure_local_icons
ensure_theme
ensure_launcher

case "${1:-}" in
  --oasis-install) oasis_quick_install 22 "$OASIS_REPO_DEFAULT" "$OASIS_DIR_DEFAULT" ;;
  --oasis-start)   oasis_quick_start "$OASIS_DIR_DEFAULT" ;;
  --ecoin-install) ecoin_quick_install "$ECOIN_REPO_DEFAULT" "$ECOIN_DIR_DEFAULT" ;;
  --wallet-create) progress_user "ECOIN: Crear cartera"   "$(ecoin_create_wallet_cmd)" ;;
  --wallet-connect)progress_user "ECOIN: Conectar cartera" "$(ecoin_connect_wallet_cmd)" ;;
  --ecoin-gui)     progress_user "ECOIN: Wallet (Qt)"     "$(ecoin_qt_cmd "$ECOIN_DIR_DEFAULT")" ;;
  *)               home_single_dialog ;;
esac
