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

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

# --- Rutas ---
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"
INSTALLER_DIR="$SCRIPT_DIR"
CSS_SOURCE="$INSTALLER_DIR/gtk.css"                 # (lo añadimos luego)
ICON_OASIS="$INSTALLER_DIR/oasis-logo.webp"
ICON_ECOIN="$INSTALLER_DIR/ecoin.png"

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

# --- Theming local (no toca el sistema) ---
NAME="SolarHubInstaller"       # --name/--class (CSS scope)
THEME_NAME="SolarHub"          # ~/.themes/SolarHub/gtk-3.0/gtk.css
YAD_THEME="${THEME_NAME}:dark"
ORANGE="#FF4E00"
GREEN="#27D980"
GREY="#b9b9b9"

# --- Helpers básicos ---
have(){ command -v "$1" >/dev/null 2>&1; }
pkg_install(){
  local pkgs=("$@")
  if have apt-get; then
    pkexec bash -lc "apt-get update && apt-get install -y ${pkgs[*]}"
  elif have pacman; then
    pkexec bash -lc "pacman -Sy --noconfirm ${pkgs[*]}"
  elif have dnf; then
    pkexec bash -lc "dnf install -y ${pkgs[*]}"
  elif have zypper; then
    pkexec bash -lc "zypper --non-interactive install ${pkgs[*]}"
  else
    echo "❌ Gestor de paquetes no soportado. Instala manualmente: yad, policykit-1, hicolor-icon-theme, xdg-user-dirs" >&2
    exit 1
  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
    # CSS mínimo por si aún no creaste gtk.css
    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" yad --name="$NAME" --class="$NAME" "$@"; }

progress_user(){   # $1=title $2=cmd (como string)
  bash -lc "$2" 2>&1 | yad_cmd --progress --title="$1" --pulsate --auto-close --no-buttons \
    --width=940 --height=260 --center
}
progress_root(){   # $1=title $2=cmd (string) -> pkexec
  pkexec bash -lc "$2" 2>&1 | yad_cmd --progress --title="$1" --pulsate --auto-close --no-buttons \
    --width=940 --height=260 --center
}

ensure_launcher(){
  mkdir -p "$APPS_DIR" "$DESKTOP_DIR"
  cat > "$APPS_DIR/INSTALLER.desktop" <<EOF
[Desktop Entry]
Type=Application
Name=INSTALLER
Comment=OASIS & ECOIN
Exec=/bin/bash -lc '$SCRIPT_DIR/install.sh'
Icon=${ICON_OASIS:-system-software-install}
Terminal=false
Categories=System;Utility;
StartupNotify=true
EOF
  cp -f "$APPS_DIR/INSTALLER.desktop" "$DESKTOP_DIR/INSTALLER.desktop" 2>/dev/null || true
  chmod +x "$DESKTOP_DIR/INSTALLER.desktop" 2>/dev/null || true
}

# ========= Detección de 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" ]; }

# ========= Comandos OASIS =========
node_setup_cmd(){ # $1=major (22/18)
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(){ # $1 repo  $2 dir
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(){ # $1 dir
cat <<EOF
set -e
MODEL_DIR="$1/AI"; mkdir -p "\$MODEL_DIR"
if [ ! -f "\$MODEL_DIR/$OASIS_MODEL_FILE" ]; then
  echo "Descargando modelo..."
  curl -L -o "\$MODEL_DIR/$OASIS_MODEL_TAR" "$OASIS_MODEL_URL"
  echo "Descomprimiendo..."
  tar -xzf "\$MODEL_DIR/$OASIS_MODEL_TAR" -C "\$MODEL_DIR"
  rm "\$MODEL_DIR/$OASIS_MODEL_TAR"
fi
EOF
}
oasis_start_cmd(){ # $1 dir
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
}
oasis_stop_cmd(){ cat <<'EOF'
set -e
pkill -f 'node .*server\.js' || true
pkill -f 'bash oasis\.sh'    || true
EOF
}

# ========= Comandos 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(){ # $1 repo  $2 dir
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(){ # $1 dir
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(){ # $1 dir
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(){ # $1 dir
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(){ # major repo dir
  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(){ # repo dir
  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 (dos mitades) =========
home(){
  # Clave segura para paned/plug (≤2e9)
  if command -v shuf >/dev/null 2>&1; then
    KEY="$(shuf -i 1-2000000000 -n 1)"
  else
    KEY=$(( (RANDOM<<15) | RANDOM )); KEY=$((KEY%2000000000+1))
  fi

  # --- MITAD IZQUIERDA: OASIS ---
  local O_TEXT O_BTN
  if oasis_installed; then
    O_TEXT="<span size='x-large' weight='heavy' foreground='$ORANGE'>OASIS</span>\n<span foreground='$GREEN'>Instalado</span>"
    O_BTN="bash -lc '$0 --oasis-start'!$ICON_OASIS!Abrir OASIS"
  else
    O_TEXT="<span size='x-large' weight='heavy' foreground='$ORANGE'>OASIS</span>\n<span foreground='$ORANGE'>No instalado</span>"
    O_BTN="bash -lc '$0 --oasis-install'!$ICON_OASIS!Instalar OASIS"
  fi

  yad_cmd --plug="$KEY" --form --borders=28 --columns=1 \
    ${ICON_OASIS:+--image="$ICON_OASIS"} --image-on-top \
    --text="$O_TEXT" \
    --field=":BTN" "$O_BTN" \
    --no-buttons --buttons-layout=center &
  PID_L=$!

  # --- MITAD DERECHA: ECOIN ---
  local E_TEXT E_BTN1 E_BTN2
  if ! ecoin_installed; then
    E_TEXT="<span size='x-large' weight='heavy' foreground='$ORANGE'>ECOIN</span>\n<span foreground='$ORANGE'>No instalado</span>"
    E_BTN1="bash -lc '$0 --ecoin-install'!$ICON_ECOIN!Instalar ECOIN"
    E_BTN2=""
  else
    if ecoin_wallet_exists; then
      E_TEXT="<span size='x-large' weight='heavy' foreground='$ORANGE'>ECOIN</span>\n<span foreground='$GREEN'>Cartera detectada</span>"
      E_BTN1="bash -lc '$0 --wallet-connect'!$ICON_ECOIN!Conectar cartera"
      E_BTN2="bash -lc '$0 --ecoin-gui'!$ICON_ECOIN!Abrir ECOIN GUI"
    else
      E_TEXT="<span size='x-large' weight='heavy' foreground='$ORANGE'>ECOIN</span>\n<span foreground='$ORANGE'>Sin cartera</span>"
      E_BTN1="bash -lc '$0 --wallet-create'!$ICON_ECOIN!Crear cartera"
      E_BTN2=""
    fi
  fi

  if [ -n "$E_BTN2" ]; then
    yad_cmd --plug="$KEY" --form --borders=28 --columns=1 \
      ${ICON_ECOIN:+--image="$ICON_ECOIN"} --image-on-top \
      --text="$E_TEXT" \
      --field=":BTN" "$E_BTN1" \
      --field=":BTN" "$E_BTN2" \
      --no-buttons --buttons-layout=center &
  else
    yad_cmd --plug="$KEY" --form --borders=28 --columns=1 \
      ${ICON_ECOIN:+--image="$ICON_ECOIN"} --image-on-top \
      --text="$E_TEXT" \
      --field=":BTN" "$E_BTN1" \
      --no-buttons --buttons-layout=center &
  fi
  PID_R=$!

  sleep 0.35
  yad_cmd --paned --key="$KEY" \
    --title="SOLAR NET HUB" --width=1180 --height=740 --center \
    --button="Cerrar:0"

  kill "$PID_L" "$PID_R" 2>/dev/null || true
}

# ========= Entrypoint =========
ensure_basics
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 ;;
esac
ensure_basics(){
  local miss=()
  command -v yad >/dev/null 2>&1 || miss+=("yad")
  command -v pkexec >/dev/null 2>&1 || miss+=("policykit-1")
  command -v xdg-user-dirs-update >/dev/null 2>&1 || 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
  ((${#miss[@]})) && pkg_install "${miss[@]}"
}
