#!/bin/bash
# =============================================================================
# Hermes Gateway - Script de despliegue para Plesk + chroot (sin systemd)
# Dominio: codi.iaprosystems.com
# Path:    /var/www/vhosts/iaprosystems.com/codi.iaprosystems.com/httpdocs/
# =============================================================================

set -euo pipefail

# ──────────────────────────────────────────────────────────────
# VARIABLES DE CONFIGURACIÓN — EDITAR ANTES DE EJECUTAR
# ──────────────────────────────────────────────────────────────
TELEGRAM_BOT_TOKEN="REEMPLAZA_CON_TU_BOT_TOKEN"
TELEGRAM_WEBHOOK_SECRET="REEMPLAZA_CON_UN_SECRET_ALEATORIO"   # mínimo 32 chars aleatorios
OPENROUTER_API_KEY="REEMPLAZA_CON_TU_OPENROUTER_KEY"
HERMES_PROFILE="default"                                       # perfil de Hermes a usar

DEPLOY_DIR="/var/www/vhosts/iaprosystems.com/codi.iaprosystems.com/httpdocs"
DOMAIN="codi.iaprosystems.com"
WEBHOOK_PORT=3000          # puerto interno que escucha la app Node
APP_ENTRY="index.js"

# ──────────────────────────────────────────────────────────────
# COLORES
# ──────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'
CYAN='\033[0;36m'; NC='\033[0m'

info()    { echo -e "${CYAN}[INFO]${NC} $*"; }
success() { echo -e "${GREEN}[OK]${NC}   $*"; }
warn()    { echo -e "${YELLOW}[WARN]${NC} $*"; }
error()   { echo -e "${RED}[ERR]${NC}  $*"; exit 1; }

# ──────────────────────────────────────────────────────────────
# 0. VERIFICACIONES PREVIAS
# ──────────────────────────────────────────────────────────────
info "Verificando requisitos del sistema..."

command -v node  >/dev/null 2>&1 || error "Node.js no encontrado"
command -v npm   >/dev/null 2>&1 || error "npm no encontrado"
command -v python3 >/dev/null 2>&1 || error "python3 no encontrado"
command -v pip3  >/dev/null 2>&1 || warn  "pip3 no encontrado — intentando con 'pip'"
command -v curl  >/dev/null 2>&1 || error "curl no encontrado"
command -v git   >/dev/null 2>&1 || error "git no encontrado"

NODE_VER=$(node -e "process.stdout.write(process.version)")
PY_VER=$(python3 --version 2>&1 | awk '{print $2}')
info "Node.js: ${NODE_VER}  |  Python: ${PY_VER}"

# Detectar pip disponible
PIP_CMD="pip3"
command -v pip3 >/dev/null 2>&1 || PIP_CMD="pip"
command -v $PIP_CMD >/dev/null 2>&1 || error "Ningún comando pip encontrado"

# ──────────────────────────────────────────────────────────────
# 1. PREPARAR DIRECTORIO DE DESPLIEGUE
# ──────────────────────────────────────────────────────────────
info "Preparando directorio: ${DEPLOY_DIR}"
mkdir -p "${DEPLOY_DIR}"
cd "${DEPLOY_DIR}"

# ──────────────────────────────────────────────────────────────
# 2. INSTALAR HERMES VIA PIP (modo usuario)
# ──────────────────────────────────────────────────────────────
info "Instalando Hermes Agent via pip (--user)..."
$PIP_CMD install --user --upgrade hermes-agent || {
    warn "Fallo con pip directo — intentando con pip install --break-system-packages"
    $PIP_CMD install --user --upgrade --break-system-packages hermes-agent
}

# Localizar el binario hermes instalado por pip
HERMES_BIN=$(python3 -m site --user-base)/bin/hermes
if [[ ! -f "$HERMES_BIN" ]]; then
    # Buscar en rutas alternativas
    HERMES_BIN=$(find ~/.local/bin /usr/local/bin /usr/bin -name "hermes" 2>/dev/null | head -1)
fi
[[ -z "$HERMES_BIN" ]] && error "No se encontró el binario 'hermes' después de instalar"
success "Hermes instalado en: ${HERMES_BIN}"

# Agregar ~/.local/bin al PATH si no está
if [[ ":$PATH:" != *":$HOME/.local/bin:"* ]]; then
    echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc
    export PATH="$HOME/.local/bin:$PATH"
fi

# ──────────────────────────────────────────────────────────────
# 3. CREAR ARCHIVO .env
# ──────────────────────────────────────────────────────────────
info "Generando archivo .env..."
cat > "${DEPLOY_DIR}/.env" <<EOF
# Hermes Gateway — variables de entorno
NODE_ENV=production
PORT=${WEBHOOK_PORT}
DOMAIN=https://${DOMAIN}

# Telegram
TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN}
TELEGRAM_WEBHOOK_SECRET=${TELEGRAM_WEBHOOK_SECRET}
WEBHOOK_PATH=/webhook

# OpenRouter / LLM
OPENROUTER_API_KEY=${OPENROUTER_API_KEY}

# Hermes
HERMES_PROFILE=${HERMES_PROFILE}
HERMES_BIN=${HERMES_BIN}

# Logs
LOG_LEVEL=info
LOG_FILE=${DEPLOY_DIR}/logs/app.log
EOF
chmod 600 "${DEPLOY_DIR}/.env"
success ".env creado (permisos 600)"

# ──────────────────────────────────────────────────────────────
# 4. CREAR DIRECTORIOS DE LOGS
# ──────────────────────────────────────────────────────────────
mkdir -p "${DEPLOY_DIR}/logs"
info "Directorio de logs creado"

# ──────────────────────────────────────────────────────────────
# 5. INSTALAR DEPENDENCIAS NODE
# ──────────────────────────────────────────────────────────────
info "Instalando dependencias Node.js..."
cd "${DEPLOY_DIR}"
npm install --omit=dev
success "node_modules instalado"

# ──────────────────────────────────────────────────────────────
# 6. INSTALAR / VERIFICAR PM2 (via npx o instalación global)
# ──────────────────────────────────────────────────────────────
info "Verificando PM2..."
if ! command -v pm2 >/dev/null 2>&1; then
    info "PM2 no encontrado globalmente — instalando con npm (--prefix ~/.local)"
    npm install --prefix ~/.local pm2
    export PATH="$HOME/.local/bin:$PATH"
fi

PM2_BIN=$(command -v pm2 2>/dev/null || echo "$HOME/.local/bin/pm2")
[[ ! -f "$PM2_BIN" ]] && error "No se pudo instalar PM2"
success "PM2 disponible: ${PM2_BIN}"

# ──────────────────────────────────────────────────────────────
# 7. CREAR ecosystem.config.js para PM2
# ──────────────────────────────────────────────────────────────
info "Generando ecosystem.config.js para PM2..."
cat > "${DEPLOY_DIR}/ecosystem.config.js" <<EOF
module.exports = {
  apps: [{
    name        : 'hermes-gateway',
    script      : '${DEPLOY_DIR}/index.js',
    cwd         : '${DEPLOY_DIR}',
    interpreter : 'node',
    instances   : 1,
    autorestart : true,
    watch       : false,
    max_memory_restart: '256M',
    env: {
      NODE_ENV : 'production',
      PORT     : ${WEBHOOK_PORT}
    },
    env_file    : '${DEPLOY_DIR}/.env',
    out_file    : '${DEPLOY_DIR}/logs/pm2-out.log',
    error_file  : '${DEPLOY_DIR}/logs/pm2-err.log',
    merge_logs  : true,
    log_date_format: 'YYYY-MM-DD HH:mm:ss Z'
  }]
};
EOF
success "ecosystem.config.js creado"

# ──────────────────────────────────────────────────────────────
# 8. ARRANCAR APP CON PM2
# ──────────────────────────────────────────────────────────────
info "Arrancando Hermes Gateway con PM2..."
cd "${DEPLOY_DIR}"
$PM2_BIN delete hermes-gateway 2>/dev/null || true
$PM2_BIN start ecosystem.config.js
$PM2_BIN save
success "App arrancada con PM2"

# ──────────────────────────────────────────────────────────────
# 9. CONFIGURAR PM2 PARA ARRANCAR SIN SYSTEMD (cron @reboot)
# ──────────────────────────────────────────────────────────────
info "Configurando arranque automático via crontab (@reboot, sin systemd)..."
PM2_STARTUP_CMD="$PM2_BIN resurrect"
CRON_LINE="@reboot sleep 30 && ${PM2_STARTUP_CMD} >> ${DEPLOY_DIR}/logs/pm2-reboot.log 2>&1"

# Añadir solo si no existe ya
(crontab -l 2>/dev/null | grep -qF "pm2 resurrect") || \
    (crontab -l 2>/dev/null; echo "$CRON_LINE") | crontab -
success "Cron @reboot configurado para PM2 resurrect"

# ──────────────────────────────────────────────────────────────
# 10. REGISTRAR WEBHOOK DE TELEGRAM
# ──────────────────────────────────────────────────────────────
info "Registrando webhook de Telegram..."
WEBHOOK_URL="https://${DOMAIN}/webhook"
REGISTER_RESPONSE=$(curl -s -X POST \
    "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/setWebhook" \
    -H "Content-Type: application/json" \
    -d "{
        \"url\": \"${WEBHOOK_URL}\",
        \"secret_token\": \"${TELEGRAM_WEBHOOK_SECRET}\",
        \"allowed_updates\": [\"message\",\"callback_query\",\"inline_query\"],
        \"drop_pending_updates\": true
    }")

echo "$REGISTER_RESPONSE" | python3 -c "
import sys, json
resp = json.load(sys.stdin)
if resp.get('ok'):
    print('\033[0;32m[OK]   Webhook registrado:', resp.get('description','OK'), '\033[0m')
else:
    print('\033[0;31m[ERR]  Error al registrar webhook:', resp, '\033[0m')
"

# ──────────────────────────────────────────────────────────────
# 11. VERIFICACIÓN FINAL
# ──────────────────────────────────────────────────────────────
echo ""
info "──── ESTADO FINAL ────"
$PM2_BIN list
echo ""
info "Verificando endpoint de salud en http://localhost:${WEBHOOK_PORT}/health ..."
sleep 3
curl -sf "http://localhost:${WEBHOOK_PORT}/health" && success "App responde correctamente" || \
    warn "La app no responde en /health — revisa los logs: $PM2_BIN logs hermes-gateway"

echo ""
success "══════════════════════════════════════════════"
success " Despliegue completado: https://${DOMAIN}"
success "══════════════════════════════════════════════"
echo ""
echo "  Comandos útiles:"
echo "    ${PM2_BIN} logs hermes-gateway    # ver logs en tiempo real"
echo "    ${PM2_BIN} restart hermes-gateway # reiniciar app"
echo "    ${PM2_BIN} stop hermes-gateway    # detener app"
echo "    cat ${DEPLOY_DIR}/logs/app.log    # log de aplicación"
echo ""
