#!/bin/bash
# SKEEN — Iniciar todos los servicios del ecosistema
# Uso: ./skeen-start-all.sh

set -e

echo "=========================================="
echo "Iniciando ecosistema SKEEN"
echo "=========================================="

# 1. Supabase (PostgreSQL + Auth + Storage + Realtime)
echo "[1/6] Iniciando Supabase self-hosted..."
cd /root/skeen-supabase/docker
docker compose up -d

# Esperar a que Supabase DB esté saludable
echo "Esperando a que PostgreSQL esté listo..."
for i in {1..30}; do
  if docker exec supabase-db pg_isready -U postgres > /dev/null 2>&1; then
    echo "PostgreSQL listo"
    break
  fi
  sleep 2
done

# 2. Odoo 17
echo "[2/6] Iniciando Odoo 17..."
cd /root/skeen-odoo
source /root/odoo-venv/bin/activate
export SUPABASE_URL="http://localhost:8000"
export SUPABASE_SERVICE_ROLE_KEY="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoic2VydmljZV9yb2xlIiwiaXNzIjoic3VwYWJhc2UiLCJpYXQiOjE2NDE3NjkyMDAsImV4cCI6MTc5OTUzNTYwMH0.XA05Pgn-gkEKaZEaHYFc9DAyP45uNJdsl8DL9axUxbc"
nohup ./odoo-bin -c odoo.conf --logfile=/tmp/odoo.log > /tmp/odoo_stdout.log 2>&1 &
echo "Odoo iniciando con PID $!"

# 3. WACRM
echo "[3/6] Iniciando WACRM..."
cd /root/skeen-wacrm
nohup npm start > /tmp/wacrm.log 2>&1 &
echo "WACRM iniciando con PID $!"

# 4. Frontend React
echo "[4/6] Iniciando Frontend React..."
cd /root/skeen-frontend
nohup npm run dev > /tmp/frontend.log 2>&1 &
echo "Frontend iniciando con PID $!"

# 5. Hermes gateway
echo "[5/7] Iniciando Hermes gateway..."
cd /root
HERMES_ACCEPT_HOOKS=1 nohup /root/hermes-venv/bin/hermes gateway run > /tmp/hermes-gateway.log 2>&1 &
echo "Hermes gateway iniciando con PID $!"

# 6. Hermes serve (API/dashboard)
echo "[6/7] Iniciando Hermes serve..."
cd /root
source /root/hermes-venv/bin/activate
nohup hermes serve --host 0.0.0.0 --port 9119 --skip-build > /tmp/hermes-serve.log 2>&1 &
echo "Hermes serve iniciando con PID $!"

# 6. Bridge webhook SKEEN
echo "[7/7] Iniciando Bridge webhook SKEEN..."
cd /root/skeen-roadmap-hermes/hermes
nohup node webhook-bridge.js > /tmp/hermes-bridge.log 2>&1 &
echo "Bridge iniciando con PID $!"

echo ""
echo "=========================================="
echo "Todos los servicios fueron iniciados"
echo "Espera 15-30 segundos y verifica con:"
echo "  ss -tlnp | grep -E '3000|5173|8069|8000|8090|8644|8080|9119'"
echo "=========================================="
