#!/bin/bash
# scripts/fix_installation.sh
# Script para corregir problemas comunes después de la instalación

set -e

RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

print_step() {
    echo -e "${BLUE}==>${NC} $1"
}

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

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

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

print_step "Corrigiendo problemas de instalación..."
echo ""

# Corregir permisos de logs
print_step "1. Corrigiendo permisos de logs..."
chown -R www-data:www-data /var/www/html/bot/logs/
chmod -R 775 /var/www/html/bot/logs/
print_success "Permisos de logs corregidos"

# Reiniciar workers
print_step "2. Reiniciando workers..."
supervisorctl restart translation-worker-pool
sleep 3
print_success "Workers reiniciados"

# Verificar workers
print_step "3. Verificando workers..."
WORKER_COUNT=$(ps aux | grep -c '[T]ranslationWorker' || echo "0")
if [ "$WORKER_COUNT" -ge 4 ]; then
    print_success "Workers activos: $WORKER_COUNT"
else
    print_error "Workers activos: $WORKER_COUNT (esperados: 4+)"
    echo "Ver logs: tail -f /var/www/html/bot/logs/translation-worker-pool.err.log"
    exit 1
fi

# Verificar Redis
print_step "4. Verificando Redis..."
if redis-cli ping &> /dev/null; then
    print_success "Redis funcionando"
else
    print_error "Redis no responde"
    exit 1
fi

echo ""
print_success "Todos los problemas corregidos"
echo ""

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

echo ""
print_success "Sistema funcionando correctamente"
