#!/bin/bash
# scripts/install_translation_system.sh
# Script automatizado para instalar y configurar el sistema de traducción optimizado
# Uso: sudo bash scripts/install_translation_system.sh [pruebas|reod]

set -e  # Detener si hay algún error

# Colores para output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Función para imprimir con color
print_step() {
    echo -e "${BLUE}==>${NC} $1"
}

print_success() {
    echo -e "${GREEN}✓${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

# Verificar que se ejecuta como root
if [ "$EUID" -ne 0 ]; then 
    print_error "Este script debe ejecutarse como root (usa sudo)"
    exit 1
fi

# Obtener environment (pruebas o reod)
ENVIRONMENT=${1:-reod}
if [ "$ENVIRONMENT" != "pruebas" ] && [ "$ENVIRONMENT" != "reod" ]; then
    print_error "Environment inválido. Usa: pruebas o reod"
    exit 1
fi

print_step "Instalando sistema de traducción optimizado para environment: $ENVIRONMENT"
echo ""

# ============================================
# PASO 1: Instalar Redis Server
# ============================================
print_step "PASO 1/6: Instalando Redis Server..."

if command -v redis-server &> /dev/null; then
    print_warning "Redis ya está instalado"
else
    apt-get update -qq
    apt-get install -y redis-server redis-tools
    print_success "Redis instalado"
fi

# Iniciar y habilitar Redis
systemctl start redis-server
systemctl enable redis-server

# Verificar que Redis funciona
if redis-cli ping &> /dev/null; then
    print_success "Redis funcionando correctamente"
else
    print_error "Redis no responde"
    exit 1
fi

echo ""

# ============================================
# PASO 2: Instalar extensión PHP Redis
# ============================================
print_step "PASO 2/6: Instalando extensión PHP Redis..."

if php -m | grep -q redis; then
    print_warning "Extensión PHP Redis ya está instalada"
else
    apt-get install -y php-redis
    print_success "Extensión PHP Redis instalada"
fi

# Reiniciar servicios PHP
if systemctl list-units --type=service | grep -q php.*fpm; then
    systemctl restart php*-fpm
    print_success "PHP-FPM reiniciado"
fi

if systemctl list-units --type=service | grep -q apache2; then
    systemctl restart apache2
    print_success "Apache reiniciado"
fi

# Verificar extensión
if php -m | grep -q redis; then
    print_success "Extensión PHP Redis verificada"
else
    print_error "Extensión PHP Redis no está disponible"
    exit 1
fi

echo ""

# ============================================
# PASO 3: Verificar extensión PCNTL
# ============================================
print_step "PASO 3/6: Verificando extensión PHP PCNTL..."

if php -m | grep -q pcntl; then
    print_success "Extensión PCNTL disponible"
else
    print_warning "Instalando extensión PCNTL..."
    apt-get install -y php-pcntl
    systemctl restart php*-fpm 2>/dev/null || true
    
    if php -m | grep -q pcntl; then
        print_success "Extensión PCNTL instalada"
    else
        print_error "No se pudo instalar PCNTL"
        exit 1
    fi
fi

echo ""

# ============================================
# PASO 4: Actualizar configuración de Supervisor
# ============================================
print_step "PASO 4/6: Actualizando configuración de Supervisor..."

SUPERVISOR_CONF="/etc/supervisor/conf.d/bot.conf"

# Hacer backup de la configuración actual
if [ -f "$SUPERVISOR_CONF" ]; then
    cp "$SUPERVISOR_CONF" "$SUPERVISOR_CONF.backup.$(date +%Y%m%d_%H%M%S)"
    print_success "Backup de configuración creado"
fi

# Detener worker antiguo si existe
if supervisorctl status translation-worker &> /dev/null; then
    supervisorctl stop translation-worker
    print_success "Worker antiguo detenido"
fi

# Crear nueva configuración
cat > "$SUPERVISOR_CONF" << 'EOF'
# Bot de Discord (sin cambios)
[program:discordbot]
command=/usr/bin/php /var/www/html/bot/discord_bot.php
environment=APP_ENVIRONMENT="reod"
directory=/var/www/html/bot/
autostart=true
autorestart=true
stderr_logfile=/var/www/html/bot/logs/discordbot.err.log
stdout_logfile=/var/www/html/bot/logs/discordbot.out.log
user=www-data

# Pool de Workers de Traducción (NUEVO)
[program:translation-worker-pool]
command=/usr/bin/php /var/www/html/bot/scripts/start_worker_pool.php
environment=APP_ENVIRONMENT="reod"
directory=/var/www/html/bot/
autostart=true
autorestart=true
stderr_logfile=/var/www/html/bot/logs/translation-worker-pool.err.log
stdout_logfile=/var/www/html/bot/logs/translation-worker-pool.out.log
user=www-data
numprocs=1
stopwaitsecs=30
stopsignal=TERM
EOF

print_success "Configuración de Supervisor actualizada"

# Recargar Supervisor
supervisorctl reread
supervisorctl update
print_success "Supervisor recargado"

echo ""

# ============================================
# PASO 5: Iniciar pool de workers
# ============================================
print_step "PASO 5/6: Iniciando pool de workers..."

# Dar permisos de ejecución a scripts
chmod +x /var/www/html/bot/scripts/*.sh
chmod +x /var/www/html/bot/scripts/*.php

# Iniciar pool
supervisorctl start translation-worker-pool
sleep 3

# Verificar estado
if supervisorctl status translation-worker-pool | grep -q RUNNING; then
    print_success "Pool de workers iniciado"
else
    print_error "Pool de workers no se inició correctamente"
    supervisorctl tail translation-worker-pool stderr
    exit 1
fi

echo ""

# ============================================
# PASO 6: Verificar instalación
# ============================================
print_step "PASO 6/6: Verificando instalación..."

# Verificar workers activos
WORKER_COUNT=$(ps aux | grep -c '[T]ranslationWorker' || echo "0")
if [ "$WORKER_COUNT" -ge 4 ]; then
    print_success "Workers activos: $WORKER_COUNT"
else
    print_warning "Workers activos: $WORKER_COUNT (esperados: 4+)"
fi

# Verificar Redis
if redis-cli -h 10.10.4.17 -p 6379 ping &> /dev/null; then
    print_success "Conexión a Redis: OK"
else
    print_warning "No se puede conectar a Redis en 10.10.4.17:6379"
fi

# Verificar supervisor
if supervisorctl status | grep -q "translation-worker-pool.*RUNNING"; then
    print_success "Supervisor: OK"
else
    print_warning "Supervisor: Verificar estado"
fi

echo ""
echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  INSTALACIÓN COMPLETADA EXITOSAMENTE  ${NC}"
echo -e "${GREEN}========================================${NC}"
echo ""

# Mostrar estadísticas
print_step "Estadísticas del sistema:"
php /var/www/html/bot/scripts/translation_stats.php

echo ""
print_step "Comandos útiles:"
echo "  Ver logs:        tail -f /var/www/html/bot/logs/translation-worker-pool.out.log"
echo "  Ver estadísticas: php /var/www/html/bot/scripts/translation_stats.php"
echo "  Reiniciar:       sudo supervisorctl restart translation-worker-pool"
echo "  Detener:         sudo supervisorctl stop translation-worker-pool"
echo ""

print_success "Sistema de traducción optimizado instalado y funcionando"
print_success "Capacidad: ~400 traducciones/minuto (13x más que antes)"
