#!/bin/bash
# Script de inicio para el stack SKEEN (WACRM + Hermes)

set -e

PROJECT_ROOT="/root/skeen-roadmap-hermes"
WACRM_DIR="/root/skeen-wacrm"
HERMES_VENV="/root/hermes-venv"

echo "=========================================="
echo "Iniciando Stack SKEEN"
echo "=========================================="

# 1. Iniciar PostgreSQL
echo "[1/4] Iniciando PostgreSQL..."
systemctl start postgresql

# 2. Iniciar Redis
echo "[2/4] Iniciando Redis..."
systemctl start redis-server

# 3. Iniciar WACRM (en background)
echo "[3/4] Iniciando WACRM..."
cd "$WACRM_DIR"
export NEXT_PUBLIC_APP_URL=http://localhost:3000
export NEXT_PUBLIC_SUPABASE_URL=http://localhost:54321
export NEXT_PUBLIC_SUPABASE_ANON_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNrZWVuIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTk3NTc0MDAsImV4cCI6MTkxNzUxMzgwMH0.skeen_dev_key
export SUPABASE_SERVICE_ROLE_KEY=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InNrZWVuIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc1OTc1NzQwMCwiZXhwIjoxOTE3NTEzODAwfQ.skeen_dev_service
export ENCRYPTION_KEY=0000000000000000000000000000000000000000000000000000000000000000
export WHATSAPP_VERIFY_TOKEN=skeen_webhook_verify_2026

# Iniciar WACRM en background
nohup npm run dev > /var/log/wacrm.log 2>&1 &
echo "WACRM iniciado en puerto 3000 (PID: $!)"

# 4. Iniciar Hermes (en background)
echo "[4/4] Iniciando Hermes..."
source "$HERMES_VENV/bin/activate"
export HERMES_MODEL_PROVIDER=openai
export HERMES_MODEL=gpt-4o
export OPENAI_API_KEY=${OPENAI_API_KEY:-sk-test}
export HERMES_WEBHOOK_PORT=8080
export HERMES_API_SERVER_ENABLED=true
export HERMES_CRON_ENABLED=true
export WACRM_URL=http://localhost:3000
export WACRM_API_KEY=wacrm_dev_key
export SKEEN_SERVICES_JSON=/root/skeen-roadmap-hermes/hermes/skills/skeen-services.json

# Iniciar Hermes gateway en background
nohup hermes gateway start > /var/log/hermes.log 2>&1 &
echo "Hermes iniciado en puerto 8080 (PID: $!)"

echo "=========================================="
echo "Stack SKEEN iniciado!"
echo "=========================================="
echo ""
echo "Servicios:"
echo "  - WACRM:     http://localhost:3000"
echo "  - Hermes:    http://localhost:8080"
echo "  - Nginx:     http://localhost:80"
echo ""
echo "Logs:"
echo "  - WACRM:     tail -f /var/log/wacrm.log"
echo "  - Hermes:    tail -f /var/log/hermes.log"
echo ""
echo "Para detener:"
echo "  pkill -f 'next dev'"
echo "  pkill -f 'hermes gateway'"
