#!/bin/bash
# Verificar que el stack de producción está funcionando correctamente
# Math2 Platform - Production Verification

set -e

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

COMPOSE_FILE="docker-compose.prod.yml"
VERIFICATION_LOG="/tmp/verify-production-$(date +%Y%m%d-%H%M%S).log"

echo -e "${BLUE}🔍 Verificando estado de producción...${NC}"
echo "================================================" | tee -a $VERIFICATION_LOG
date | tee -a $VERIFICATION_LOG
echo "" | tee -a $VERIFICATION_LOG

# Función para verificar estado de contenedores
check_containers() {
    echo -e "${BLUE}📦 Estado de contenedores:${NC}" | tee -a $VERIFICATION_LOG
    docker-compose -f $COMPOSE_FILE ps 2>&1 | tee -a $VERIFICATION_LOG
    echo "" | tee -a $VERIFICATION_LOG
}

# Función para verificar health de cada servicio
check_service_health() {
    local service=$1
    local port=$2
    local endpoint=$3
    
    echo -n "   $service: " | tee -a $VERIFICATION_LOG
    
    # Verificar si el contenedor está corriendo
    if ! docker-compose -f $COMPOSE_FILE ps | grep -q "$service.*Up"; then
        echo -e "${RED}❌ CONTAINER DOWN${NC}" | tee -a $VERIFICATION_LOG
        return 1
    fi
    
    # Verificar health endpoint si aplica
    if [ -n "$endpoint" ]; then
        if curl -sf http://localhost:$port$endpoint > /dev/null 2>&1; then
            echo -e "${GREEN}✅ HEALTHY${NC}" | tee -a $VERIFICATION_LOG
            return 0
        else
            echo -e "${YELLOW}⚠️  RUNNING (No health endpoint)${NC}" | tee -a $VERIFICATION_LOG
            return 0
        fi
    else
        echo -e "${GREEN}✅ RUNNING${NC}" | tee -a $VERIFICATION_LOG
        return 0
    fi
}

# Verificar estado de servicios
echo -e "${BLUE}🏥 Health Checks de Servicios:${NC}" | tee -a $VERIFICATION_LOG
SERVICES=(
    "postgres:5432:"
    "redis:6379:"
    "backend:3001:/health"
    "frontend:3000:"
    "nginx:80:"
    "pdf-worker:3002:/health"
    "exercise-worker:3003:/health"
    "notification-worker:3004:/health"
)

FAILED_SERVICES=0
for service_info in "${SERVICES[@]}"; do
    IFS=':' read -r service port endpoint <<< "$service_info"
    if ! check_service_health "$service" "$port" "$endpoint"; then
        ((FAILED_SERVICES++))
    fi
done

echo "" | tee -a $VERIFICATION_LOG

# Verificar logs recientes (solo errores)
echo -e "${BLUE}📋 Logs recientes (últimos errores):${NC}" | tee -a $VERIFICATION_LOG
for service in backend frontend pdf-worker exercise-worker notification-worker; do
    echo -e "${YELLOW}   [$service] Errores:${NC}" | tee -a $VERIFICATION_LOG
    docker-compose -f $COMPOSE_FILE logs --tail=20 $service 2>&1 | grep -E "(ERROR|FATAL|Exception|Traceback)" | head -5 | tee -a $VERIFICATION_LOG || echo "      No hay errores recientes" | tee -a $VERIFICATION_LOG
    echo "" | tee -a $VERIFICATION_LOG
done

# Verificar recursos
echo -e "${BLUE}💾 Uso de recursos:${NC}" | tee -a $VERIFICATION_LOG
docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}\t{{.BlockIO}}" 2>/dev/null | grep -E "(math-|postgres|redis)" | tee -a $VERIFICATION_LOG || echo "   No se pueden obtener estadísticas" | tee -a $VERIFICATION_LOG
echo "" | tee -a $VERIFICATION_LOG

# Verificar base de datos
echo -e "${BLUE}🗄️  Estado de Base de Datos:${NC}" | tee -a $VERIFICATION_LOG
cd backend

# Verificar conexión a PostgreSQL
if npx prisma db execute --stdin <<EOF 2>/dev/null | tee -a $VERIFICATION_LOG
SELECT current_database(), current_user, version();
EOF
then
    echo -e "${GREEN}✅ Conexión a PostgreSQL OK${NC}" | tee -a $VERIFICATION_LOG
else
    echo -e "${RED}❌ Error conectando a PostgreSQL${NC}" | tee -a $VERIFICATION_LOG
    ((FAILED_SERVICES++))
fi

# Verificar estado de migraciones
echo -e "${BLUE}🔄 Estado de migraciones:${NC}" | tee -a $VERIFICATION_LOG
if npx prisma migrate status 2>&1 | tee -a $VERIFICATION_LOG | grep -q "Database schema is up to date"; then
    echo -e "${GREEN}✅ Migraciones al día${NC}" | tee -a $VERIFICATION_LOG
else
    echo -e "${YELLOW}⚠️  Verificar estado de migraciones${NC}" | tee -a $VERIFICATION_LOG
fi
cd ..

# Verificar Redis
echo -e "${BLUE}📊 Estado de Redis:${NC}" | tee -a $VERIFICATION_LOG
if docker-compose -f $COMPOSE_FILE exec -T redis redis-cli -a ${REDIS_PASSWORD} info stats 2>/dev/null | grep -E "(total_connections_received|total_commands_processed)" | tee -a $VERIFICATION_LOG; then
    echo -e "${GREEN}✅ Redis respondiendo${NC}" | tee -a $VERIFICATION_LOG
else
    echo -e "${YELLOW}⚠️  Redis no responde a comandos${NC}" | tee -a $VERIFICATION_LOG
fi
echo "" | tee -a $VERIFICATION_LOG

# Verificar volúmenes
echo -e "${BLUE}💾 Estado de volúmenes:${NC}" | tee -a $VERIFICATION_LOG
docker volume ls | grep -E "math|postgres_data|redis_data" | tee -a $VERIFICATION_LOG
echo "" | tee -a $VERIFICATION_LOG

# Tests de endpoints HTTP
echo -e "${BLUE}🌐 Tests de Endpoints:${NC}" | tee -a $VERIFICATION_LOG

# Backend health
echo -n "   Backend (/health): " | tee -a $VERIFICATION_LOG
if curl -sf http://localhost:3001/health > /dev/null 2>&1; then
    echo -e "${GREEN}✅ OK${NC}" | tee -a $VERIFICATION_LOG
else
    echo -e "${RED}❌ FAIL${NC}" | tee -a $VERIFICATION_LOG
    ((FAILED_SERVICES++))
fi

# Frontend
echo -n "   Frontend (/: " | tee -a $VERIFICATION_LOG
if curl -sf http://localhost > /dev/null 2>&1; then
    echo -e "${GREEN}✅ OK${NC}" | tee -a $VERIFICATION_LOG
else
    echo -e "${RED}❌ FAIL${NC}" | tee -a $VERIFICATION_LOG
    ((FAILED_SERVICES++))
fi

# API endpoints adicionales
echo -n "   API (/api/status): " | tee -a $VERIFICATION_LOG
if curl -sf http://localhost:3001/api/status > /dev/null 2>&1 || curl -sf http://localhost/api/status > /dev/null 2>&1; then
    echo -e "${GREEN}✅ OK${NC}" | tee -a $VERIFICATION_LOG
else
    echo -e "${YELLOW}⚠️  No disponible${NC}" | tee -a $VERIFICATION_LOG
fi

echo "" | tee -a $VERIFICATION_LOG

# Resumen final
echo -e "${BLUE}================================================${NC}" | tee -a $VERIFICATION_LOG
echo -e "${BLUE}📊 RESUMEN DE VERIFICACIÓN${NC}" | tee -a $VERIFICATION_LOG
echo -e "${BLUE}================================================${NC}" | tee -a $VERIFICATION_LOG

if [ $FAILED_SERVICES -eq 0 ]; then
    echo -e "${GREEN}✅ TODOS LOS SERVICIOS FUNCIONAN CORRECTAMENTE${NC}" | tee -a $VERIFICATION_LOG
else
    echo -e "${RED}❌ $FAILED_SERVICES SERVICIO(S) CON PROBLEMAS${NC}" | tee -a $VERIFICATION_LOG
fi

echo "" | tee -a $VERIFICATION_LOG
echo -e "${BLUE}📁 Log guardado en:${NC} $VERIFICATION_LOG" | tee -a $VERIFICATION_LOG
echo "" | tee -a $VERIFICATION_LOG

# Recomendaciones
if [ $FAILED_SERVICES -gt 0 ]; then
    echo -e "${YELLOW}⚠️  Recomendaciones:${NC}" | tee -a $VERIFICATION_LOG
    echo "   1. Revisa los logs: docker-compose -f $COMPOSE_FILE logs -f [servicio]" | tee -a $VERIFICATION_LOG
    echo "   2. Verifica variables de entorno en .env" | tee -a $VERIFICATION_LOG
    echo "   3. Reinicia servicios: docker-compose -f $COMPOSE_FILE restart" | tee -a $VERIFICATION_LOG
    echo "   4. Si persiste: docker-compose -f $COMPOSE_FILE down && ./scripts/start-production.sh" | tee -a $VERIFICATION_LOG
fi

exit $FAILED_SERVICES
