#!/bin/bash

# Script de verificación de salud del sistema Anexo76
# Verifica que todos los servicios estén corriendo correctamente

set -e

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

echo "========================================="
echo "   Anexo76 - Verificación de Sistema"
echo "========================================="
echo ""

# Función para verificar un servicio
check_service() {
    local service_name=$1
    local container_name=$2
    local health_url=$3
    
    echo -e "${BLUE}Verificando ${service_name}...${NC}"
    
    # Verificar si el contenedor existe
    if ! docker ps -a --format '{{.Names}}' | grep -q "^${container_name}$"; then
        echo -e "${RED}✗ Contenedor ${container_name} no existe${NC}"
        return 1
    fi
    
    # Verificar si está corriendo
    if ! docker ps --format '{{.Names}}' | grep -q "^${container_name}$"; then
        echo -e "${RED}✗ Contenedor ${container_name} no está corriendo${NC}"
        echo "  Estado:"
        docker ps -a --filter "name=${container_name}" --format "table {{.Names}}\t{{.Status}}"
        return 1
    fi
    
    # Verificar estado de salud
    health_status=$(docker inspect --format='{{.State.Health.Status}}' "${container_name}" 2>/dev/null || echo "none")
    
    if [ "$health_status" = "healthy" ]; then
        echo -e "${GREEN}✓ ${service_name} está saludable${NC}"
        
        # Verificar URL si se proporciona
        if [ -n "$health_url" ]; then
            if curl -f -s "$health_url" > /dev/null 2>&1; then
                echo -e "${GREEN}  ✓ URL accesible: ${health_url}${NC}"
            else
                echo -e "${YELLOW}  ⚠ URL no accesible: ${health_url}${NC}"
            fi
        fi
        return 0
    elif [ "$health_status" = "starting" ]; then
        echo -e "${YELLOW}⚠ ${service_name} está iniciando...${NC}"
        return 1
    elif [ "$health_status" = "unhealthy" ]; then
        echo -e "${RED}✗ ${service_name} no está saludable${NC}"
        echo "  Últimos logs:"
        docker logs --tail=20 "${container_name}"
        return 1
    else
        echo -e "${YELLOW}⚠ ${service_name} no tiene healthcheck configurado${NC}"
        return 0
    fi
}

# Función para verificar recursos
check_resources() {
    echo -e "${BLUE}Verificando recursos del sistema...${NC}"
    
    # Verificar uso de CPU y memoria
    docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.MemPerc}}" \
        anexo76-postgres anexo76-postgres-keycloak anexo76-keycloak anexo76-backend anexo76-frontend 2>/dev/null || true
    
    echo ""
}

# Función para verificar redes
check_networks() {
    echo -e "${BLUE}Verificando redes Docker...${NC}"
    
    local networks=("anexo76_backend-net" "anexo76_auth-net" "anexo76_frontend-net")
    local all_ok=true
    
    for network in "${networks[@]}"; do
        if docker network ls --format '{{.Name}}' | grep -q "^${network}$"; then
            echo -e "${GREEN}✓ Red ${network} existe${NC}"
        else
            echo -e "${RED}✗ Red ${network} no existe${NC}"
            all_ok=false
        fi
    done
    
    echo ""
    return 0
}

# Función para verificar volúmenes
check_volumes() {
    echo -e "${BLUE}Verificando volúmenes Docker...${NC}"
    
    local volumes=("anexo76_postgres_app_data" "anexo76_postgres_keycloak_data" "anexo76_keycloak_data" "anexo76_frontend_node_modules")
    local all_ok=true
    
    for volume in "${volumes[@]}"; do
        if docker volume ls --format '{{.Name}}' | grep -q "^${volume}$"; then
            size=$(docker volume inspect --format '{{ .Mountpoint }}' "$volume" 2>/dev/null | xargs du -sh 2>/dev/null | cut -f1 || echo "?")
            echo -e "${GREEN}✓ Volumen ${volume} (${size})${NC}"
        else
            echo -e "${YELLOW}⚠ Volumen ${volume} no existe${NC}"
            all_ok=false
        fi
    done
    
    echo ""
    return 0
}

# Verificar Docker
if ! command -v docker &> /dev/null; then
    echo -e "${RED}✗ Docker no está instalado${NC}"
    exit 1
fi

if ! docker info &> /dev/null; then
    echo -e "${RED}✗ Docker daemon no está corriendo${NC}"
    exit 1
fi

# Verificar servicios
echo "Verificando servicios..."
echo ""

services_ok=true

check_service "PostgreSQL App" "anexo76-postgres-a76" "" || services_ok=false
echo ""

check_service "PostgreSQL Keycloak" "anexo76-postgres-keycloak" "" || services_ok=false
echo ""

check_service "Keycloak" "anexo76-keycloak" "http://localhost:8080/" || services_ok=false
echo ""

check_service "Backend" "anexo76-backend" "http://localhost:8000/api/health" || services_ok=false
echo ""

check_service "Frontend" "anexo76-frontend" "http://localhost:5173" || services_ok=false
echo ""

# Verificar redes y volúmenes
check_networks
check_volumes

# Verificar recursos
check_resources

# Resumen final
echo "========================================="
if [ "$services_ok" = true ]; then
    echo -e "${GREEN}✓ Todos los servicios están funcionando correctamente${NC}"
    echo "========================================="
    echo ""
    echo "URLs de acceso:"
    echo -e "  ${GREEN}•${NC} Frontend:  ${BLUE}http://localhost:5173${NC}"
    echo -e "  ${GREEN}•${NC} Backend:   ${BLUE}http://localhost:8000/api${NC}"
    echo -e "  ${GREEN}•${NC} API Docs:  ${BLUE}http://localhost:8000/api/docs${NC}"
    echo -e "  ${GREEN}•${NC} Keycloak:  ${BLUE}http://localhost:8080${NC}"
    echo ""
    exit 0
else
    echo -e "${YELLOW}⚠ Algunos servicios tienen problemas${NC}"
    echo "========================================="
    echo ""
    echo "Comandos útiles para diagnóstico:"
    echo "  • Ver logs de todos:  docker-compose logs -f"
    echo "  • Ver logs servicio:  docker-compose logs -f [servicio]"
    echo "  • Reiniciar servicio: docker-compose restart [servicio]"
    echo "  • Estado completo:    docker-compose ps"
    echo ""
    exit 1
fi
