#!/bin/bash

# Script de actualización para AI Learning Platform en producción
# Puede ejecutarse como el usuario de despliegue (chat-englishworldcenter) o como root.
# - Como usuario de despliegue: debe estar en el grupo 'docker' (cerrar sesión y volver a entrar tras el primer deploy).
# - Como root: Git configurará automáticamente safe.directory para este repositorio.
# Ejecutar siempre desde la raíz del proyecto.

set -e # Exit on any error

echo "🔄 Starting AI Learning Platform Production Update..."

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

# Configuration (DEPLOY_USER debe coincidir con deploy-to-server.sh)
PROJECT_NAME="ai-learning-platform"
DEPLOY_USER="chat-englishworldcenter"

# Docker container/image naming (debe coincidir con docker-compose.yml)
POSTGRES_CONTAINER="ai-learning-platform-ewc-postgres"
TEMPORAL_CONTAINER="ai-learning-platform-ewc-temporal"
BACKEND_CONTAINER="ai-learning-platform-ewc-backend"
FRONTEND_PROD_CONTAINER="ai-learning-platform-ewc-frontend-prod"
BACKEND_IMAGE="ai-learning-platform-ewc-backend:latest"
FRONTEND_PROD_IMAGE="ai-learning-platform-ewc-frontend-prod:latest"

# --- Check if running as the correct user ---
#if [ "$USER" != "$DEPLOY_USER" ]; then
#    echo -e "${RED}❌ Error: This script must be run as the '${DEPLOY_USER}' user.${NC}"
#    echo -e "${YELLOW}Please log in as '${DEPLOY_USER}' and run the script again.${NC}"
#    exit 1
#fi

# --- Check required tools ---
if ! command -v docker &> /dev/null; then
    echo -e "${RED}❌ Error: Docker is not installed or not in PATH.${NC}"
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    echo -e "${RED}❌ Error: Docker Compose is not installed or not in PATH.${NC}"
    exit 1
fi

if ! command -v git &> /dev/null; then
    echo -e "${RED}❌ Error: Git is not installed or not in PATH.${NC}"
    exit 1
fi

# --- Check if in project directory ---
if [ ! -f "docker-compose.yml" ]; then
    echo -e "${RED}❌ Error: docker-compose.yml not found.${NC}"
    echo -e "${YELLOW}Please run this script from the project root directory.${NC}"
    exit 1
fi

# --- Check if backup.sh exists ---
if [ ! -f "backup.sh" ]; then
    echo -e "${RED}❌ Error: backup.sh not found.${NC}"
    echo -e "${YELLOW}Please ensure backup.sh exists in the project directory.${NC}"
    echo -e "${YELLOW}This file should have been created by deploy-to-server.sh${NC}"
    exit 1
fi

# --- Si se ejecuta como root: configurar Git safe.directory para evitar "dubious ownership" ---
if [ "$(id -u)" -eq 0 ]; then
    REPO_DIR="$(pwd)"
    if ! git config --global --get-all safe.directory 2>/dev/null | grep -Fxq "$REPO_DIR"; then
        echo -e "${BLUE}ℹ️  Ejecutando como root: añadiendo este directorio a Git safe.directory...${NC}"
        git config --global --add safe.directory "$REPO_DIR"
        echo -e "${GREEN}✅ Git configurado para este repositorio${NC}"
    fi
fi

# --- Si no es root: comprobar que el usuario puede usar Docker (p. ej. está en el grupo docker) ---
if [ "$(id -u)" -ne 0 ]; then
    if ! docker info >/dev/null 2>&1; then
        echo -e "${RED}❌ Error: No tienes permisos para usar Docker.${NC}"
        echo -e "${YELLOW}El usuario '${USER}' debe estar en el grupo 'docker'. Ejecuta (como root):${NC}"
        echo -e "  ${BLUE}sudo usermod -aG docker ${USER}${NC}"
        echo -e "${YELLOW}Luego cierra sesión y vuelve a entrar, o ejecuta: newgrp docker${NC}"
        exit 1
    fi
fi

# Cuando se ejecuta como root, Git usa el usuario de despliegue para que SSH use sus claves (HOME explícito)
GIT_CMD="git"
if [ "$(id -u)" -eq 0 ]; then
    DEPLOY_HOME=$(getent passwd "$DEPLOY_USER" 2>/dev/null | cut -d: -f6)
    [ -z "$DEPLOY_HOME" ] && DEPLOY_HOME="/home/$DEPLOY_USER"
    GIT_CMD="sudo -u $DEPLOY_USER env HOME=$DEPLOY_HOME git"
fi

echo ""
echo -e "${YELLOW}📋 Pre-update checklist:${NC}"
echo -e "  ✓ Running as: $USER ($([ "$(id -u)" -eq 0 ] && echo 'root' || echo 'deploy user'))"
echo -e "  ✓ In project directory: $(pwd)"
echo -e "  ✓ Docker is available"
echo -e "  ✓ Docker Compose is available"
echo -e "  ✓ Git is available"
echo ""

# Show current status
echo -e "${BLUE}📊 Current status:${NC}"
echo -e "${BLUE}Git branch: $($GIT_CMD branch --show-current)${NC}"
echo -e "${BLUE}Last commit: $($GIT_CMD log -1 --oneline)${NC}"
echo ""

# Show running containers
echo -e "${BLUE}Currently running containers:${NC}"
docker-compose ps
echo ""

# --- IMPORTANT WARNING AND INFORMATION ---
echo -e "${RED}╔════════════════════════════════════════════════════════════════╗${NC}"
echo -e "${RED}║                    ⚠️  ADVERTENCIA IMPORTANTE ⚠️                ║${NC}"
echo -e "${RED}╚════════════════════════════════════════════════════════════════╝${NC}"
echo ""
echo -e "${YELLOW}🔴 RECOMENDACIÓN CRÍTICA:${NC}"
echo -e "${YELLOW}   Antes de continuar, se RECOMIENDA ENCARECIDAMENTE crear un${NC}"
echo -e "${YELLOW}   SNAPSHOT del servidor completo desde tu proveedor de hosting.${NC}"
echo ""
echo -e "${YELLOW}   Un snapshot te permite:${NC}"
echo -e "${YELLOW}   • Restaurar el servidor completo en caso de fallo crítico${NC}"
echo -e "${YELLOW}   • Revertir cambios en el sistema operativo${NC}"
echo -e "${YELLOW}   • Recuperación rápida ante cualquier problema${NC}"
echo ""
echo -e "${YELLOW}   ¿Has creado un snapshot del servidor antes de continuar?${NC}"
echo ""

# Confirmation prompt - BEFORE ANY CHANGES
echo -e "${YELLOW}⚠️  Este script realizará las siguientes acciones:${NC}"
echo ""
echo -e "${BLUE}FASE 1 - Actualización del Sistema:${NC}"
echo -e "  1. Actualizar lista de paquetes (apt update)"
echo -e "  2. Actualizar paquetes del sistema (apt upgrade)"
echo -e "  3. Limpiar paquetes no utilizados"
echo ""
echo -e "${BLUE}FASE 2 - Actualización de la Aplicación:${NC}"
echo -e "  4. Crear backup de base de datos y archivos"
echo -e "  5. Detener backend y frontend (PRESERVA PostgreSQL)"
echo -e "  6. Purgar contenedores e imágenes Docker no utilizados"
echo -e "  7. Crear backup de archivos .env (con fecha/hora)"
echo -e "  8. Descargar último código desde Git"
echo -e "  9. Reconstruir backend y frontend (sin caché)"
echo -e " 10. Iniciar contenedores"
echo -e " 11. Verificar y corregir vulnerabilidades de seguridad"
echo -e " 12. Ejecutar migraciones de base de datos"
echo -e " 13. Reiniciar backend para aplicar cambios"
echo ""
echo -e "${RED}⚠️  IMPORTANTE:${NC}"
echo -e "${RED}   • Este proceso detendrá la aplicación temporalmente${NC}"
echo -e "${RED}   • La actualización puede tardar varios minutos${NC}"
echo -e "${RED}   • Se requiere conexión a internet estable${NC}"
echo -e "${RED}   • Asegúrate de tener suficiente espacio en disco${NC}"
echo ""
read -p "¿Has creado un snapshot Y deseas continuar con la actualización? (yes/no): " -r
if [[ ! $REPLY =~ ^[Yy][Ee][Ss]$ ]]; then
    echo -e "${YELLOW}❌ Actualización cancelada por el usuario${NC}"
    echo -e "${GREEN}✅ Buena decisión. Crea un snapshot del servidor y vuelve a ejecutar el script.${NC}"
    exit 0
fi
echo ""

# --- System update and cleanup ---
echo -e "${YELLOW}🔄 FASE 1: Actualizando paquetes del sistema...${NC}"
echo ""
echo -e "${BLUE}Running apt update...${NC}"
if sudo apt update; then
    echo -e "${GREEN}✅ Package list updated${NC}"
else
    echo -e "${RED}⚠️  apt update failed, continuing anyway...${NC}"
fi

echo -e "${BLUE}Running apt upgrade...${NC}"
if sudo DEBIAN_FRONTEND=noninteractive apt upgrade -y; then
    echo -e "${GREEN}✅ System packages upgraded${NC}"
else
    echo -e "${RED}⚠️  apt upgrade failed, continuing anyway...${NC}"
fi

echo -e "${BLUE}Cleaning up unused packages...${NC}"
if sudo apt autoremove -y && sudo apt autoclean -y; then
    echo -e "${GREEN}✅ Unused packages cleaned${NC}"
else
    echo -e "${RED}⚠️  Package cleanup failed, continuing anyway...${NC}"
fi
echo ""
echo -e "${GREEN}✅ FASE 1 completada${NC}"
echo ""

# Step 1: Create backup
echo -e "${YELLOW}🔄 FASE 2: Actualizando la aplicación...${NC}"
echo ""
echo -e "${YELLOW}💾 Paso 4/12: Creando backup antes de actualizar...${NC}"
if ./backup.sh; then
    echo -e "${GREEN}✅ Backup completed successfully${NC}"
else
    echo -e "${RED}❌ Backup failed${NC}"
    read -p "Do you want to continue without backup? (yes/no): " -r
    if [[ ! $REPLY =~ ^[Yy][Ee][Ss]$ ]]; then
        echo -e "${YELLOW}Update cancelled by user${NC}"
        exit 1
    fi
fi

# Step 2: Stop specific containers (PRESERVING PostgreSQL)
echo -e "${YELLOW}🛑 Paso 5/12: Deteniendo backend y frontend (PRESERVANDO PostgreSQL)...${NC}"
docker-compose stop backend frontend-prod temporal
echo -e "${GREEN}✅ Backend y frontend detenidos (PostgreSQL sigue corriendo)${NC}"
echo ""

# Docker cleanup after stopping containers - LIMPIEZA SEGURA
echo -e "${YELLOW}🐳 Paso 6/12: Limpiando objetos Docker dangling del proyecto...${NC}"
echo -e "${BLUE}ℹ️  Limpieza segura: solo objetos dangling (no asociados a contenedores)${NC}"

# Eliminar imágenes específicas del proyecto (solo si no están en uso)
echo -e "${BLUE}Removing project-specific images...${NC}"
docker rmi "$BACKEND_IMAGE" 2>/dev/null || echo -e "${YELLOW}⚠️  Backend image not found or in use${NC}"
docker rmi "$FRONTEND_PROD_IMAGE" 2>/dev/null || echo -e "${YELLOW}⚠️  Frontend image not found or in use${NC}"

# Limpieza segura: solo objetos dangling (no asociados a ningún contenedor)
echo -e "${BLUE}Removing dangling images (sin etiquetas y no usadas)...${NC}"
docker image prune -f --filter "dangling=true" 2>/dev/null || echo -e "${YELLOW}⚠️  No dangling images to remove${NC}"

echo -e "${BLUE}Removing dangling volumes (no asociados a ningún contenedor)...${NC}"
docker volume prune -f --filter "dangling=true" 2>/dev/null || echo -e "${YELLOW}⚠️  No dangling volumes to remove${NC}"

echo -e "${BLUE}Removing unused networks (sin contenedores conectados, >24h)...${NC}"
docker network prune -f --filter "until=24h" 2>/dev/null || echo -e "${YELLOW}⚠️  No unused networks to remove${NC}"

echo -e "${GREEN}✅ Limpieza segura de Docker completada${NC}"
echo -e "${BLUE}ℹ️  Nota: No se borraron contenedores parados ni objetos de otros proyectos${NC}"
echo ""

# Step 3: Backup .env files before pulling
echo -e "${YELLOW}💾 Paso 7/12: Creando backup de archivos .env...${NC}"
BACKUP_TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# Backup root .env
if [ -f ".env" ]; then
    cp .env ".env.backup.${BACKUP_TIMESTAMP}"
    echo -e "${GREEN}✅ Backup creado: .env.backup.${BACKUP_TIMESTAMP}${NC}"
else
    echo -e "${YELLOW}⚠️  No se encontró .env en la raíz${NC}"
fi

# Backup backend/.env
if [ -f "backend/.env" ]; then
    cp backend/.env "backend/.env.backup.${BACKUP_TIMESTAMP}"
    echo -e "${GREEN}✅ Backup creado: backend/.env.backup.${BACKUP_TIMESTAMP}${NC}"
else
    echo -e "${YELLOW}⚠️  No se encontró backend/.env${NC}"
fi

# Backup frontend/.env
if [ -f "frontend/.env" ]; then
    cp frontend/.env "frontend/.env.backup.${BACKUP_TIMESTAMP}"
    echo -e "${GREEN}✅ Backup creado: frontend/.env.backup.${BACKUP_TIMESTAMP}${NC}"
else
    echo -e "${YELLOW}⚠️  No se encontró frontend/.env${NC}"
fi
echo ""

# Step 4: Pull latest changes (como root: Git se ejecuta como usuario de despliegue para usar sus claves SSH)
echo -e "${YELLOW}📥 Paso 8/12: Descargando últimos cambios del repositorio...${NC}"
if ! $GIT_CMD fetch origin; then
    echo -e "${RED}❌ No se pudo conectar con GitHub (Permission denied).${NC}"
    echo ""
    if [ "$(id -u)" -eq 0 ]; then
        echo -e "${YELLOW}El usuario '${DEPLOY_USER}' debe tener claves SSH para GitHub en su ~/.ssh${NC}"
        echo -e "${YELLOW}Si root tiene las claves, cópialas al usuario de despliegue:${NC}"
        echo -e "  ${BLUE}sudo cp -r /root/.ssh /home/${DEPLOY_USER}/.ssh${NC}"
        echo -e "  ${BLUE}sudo chown -R ${DEPLOY_USER}:${DEPLOY_USER} /home/${DEPLOY_USER}/.ssh${NC}"
        echo -e "  ${BLUE}sudo chmod 700 /home/${DEPLOY_USER}/.ssh${NC}"
        echo -e "  ${BLUE}sudo chmod 600 /home/${DEPLOY_USER}/.ssh/* 2>/dev/null${NC}"
    fi
    exit 1
fi
CURRENT_BRANCH=$($GIT_CMD branch --show-current)
echo -e "${BLUE}ℹ️  Current branch: ${CURRENT_BRANCH}${NC}"

# Show what will be updated
echo -e "${BLUE}📊 Changes to be pulled:${NC}"
$GIT_CMD log HEAD..origin/${CURRENT_BRANCH} --oneline --no-decorate | head -10

# Confirm before pulling
read -p "Continue with git pull? (yes/no): " -r
if [[ ! $REPLY =~ ^[Yy][Ee][Ss]$ ]]; then
    echo -e "${YELLOW}Update cancelled by user${NC}"
    echo -e "${BLUE}Restarting previous version...${NC}"
    docker-compose --profile prod up -d
    exit 1
fi

$GIT_CMD pull origin ${CURRENT_BRANCH}
echo -e "${GREEN}✅ Code updated successfully${NC}"

echo -e "${BLUE}📊 Restaurando .env desde backups...${NC}"
if [ -f "backups/env" ]; then
    cp backups/env ./.env
    echo -e "${GREEN}✅ .env restaurado${NC}"
else
    echo -e "${YELLOW}⚠️  No existe backups/env, se mantiene .env actual${NC}"
fi
if [ -f "backups/envBackend" ]; then
    cp backups/envBackend backend/.env
    echo -e "${GREEN}✅ backend/.env restaurado${NC}"
else
    echo -e "${YELLOW}⚠️  No existe backups/envBackend, se mantiene backend/.env actual${NC}"
fi
if [ -f "backups/envFrontend" ]; then
    cp backups/envFrontend frontend/.env
    echo -e "${GREEN}✅ frontend/.env restaurado${NC}"
else
    echo -e "${YELLOW}⚠️  No existe backups/envFrontend, se mantiene frontend/.env actual${NC}"
fi
echo ""


# Step 6: Rebuild specific containers
echo -e "${YELLOW}🔨 Paso 9/13: Reconstruyendo backend y frontend con código nuevo...${NC}"
docker-compose --profile prod build --no-cache backend frontend-prod
echo -e "${GREEN}✅ Backend y frontend reconstruidos${NC}"

# Step 7: Start containers
echo -e "${YELLOW}🚀 Paso 10/13: Iniciando contenedores...${NC}"

# Check if PostgreSQL is running
echo -e "${BLUE}ℹ️  Verificando que PostgreSQL está corriendo...${NC}"
if ! docker ps --format '{{.Names}}' | grep -q "^${POSTGRES_CONTAINER}$"; then
    echo -e "${YELLOW}⚠️  PostgreSQL no está corriendo, iniciándolo...${NC}"
    docker-compose up -d postgres temporal
    sleep 10
fi

# Start backend and frontend
docker-compose --profile prod up -d backend frontend-prod
echo -e "${GREEN}✅ Backend y frontend iniciados${NC}"

# Wait for services to be ready
echo -e "${YELLOW}⏳ Waiting for services to start...${NC}"
sleep 15

# Step 7.5: Security audit and fix (after containers are running)
echo -e "${YELLOW}🔒 Paso 11/13: Verificando vulnerabilidades de seguridad...${NC}"

# Check root directory
echo -e "${BLUE}   Verificando vulnerabilidades en directorio raíz...${NC}"

# Check if npm is available on the server
if command -v npm > /dev/null 2>&1; then
    # Check root directory vulnerabilities locally
    if [ -f "package.json" ]; then
        if npm audit --audit-level=moderate > /dev/null 2>&1; then
            echo -e "${GREEN}   ✅ No hay vulnerabilidades en directorio raíz${NC}"
        else
            echo -e "${YELLOW}   ⚠️  Vulnerabilidades encontradas en directorio raíz${NC}"
            echo -e "${BLUE}   Aplicando correcciones automáticas...${NC}"
            if npm audit fix; then
                echo -e "${GREEN}   ✅ Vulnerabilidades corregidas en directorio raíz${NC}"
            else
                echo -e "${YELLOW}   ⚠️  No se pudieron corregir todas las vulnerabilidades${NC}"
            fi
        fi
    else
        echo -e "${YELLOW}   ⚠️  No se encontró package.json en directorio raíz, omitiendo verificación${NC}"
    fi
else
    echo -e "${YELLOW}   ⚠️  npm no está disponible en el servidor, omitiendo verificación de directorio raíz${NC}"
    echo -e "${BLUE}   ℹ️  Las vulnerabilidades se corregirán en la próxima build${NC}"
fi

# Check backend
echo -e "${BLUE}   Verificando vulnerabilidades en backend...${NC}"

# Check if npm is available on the server
if command -v npm > /dev/null 2>&1; then
    # Check backend vulnerabilities locally
    if [ -d "backend" ] && [ -f "backend/package.json" ]; then
        cd backend
        if npm audit --audit-level=moderate > /dev/null 2>&1; then
            echo -e "${GREEN}   ✅ No hay vulnerabilidades en backend${NC}"
        else
            echo -e "${YELLOW}   ⚠️  Vulnerabilidades encontradas en backend${NC}"
            echo -e "${BLUE}   Aplicando correcciones automáticas...${NC}"
            if npm audit fix; then
                echo -e "${GREEN}   ✅ Vulnerabilidades corregidas en backend${NC}"
            else
                echo -e "${YELLOW}   ⚠️  No se pudieron corregir todas las vulnerabilidades${NC}"
            fi
        fi
        cd ..
    else
        echo -e "${YELLOW}   ⚠️  No se encontró package.json en backend, omitiendo verificación${NC}"
    fi
else
    echo -e "${YELLOW}   ⚠️  npm no está disponible en el servidor, omitiendo verificación de backend${NC}"
    echo -e "${BLUE}   ℹ️  Las vulnerabilidades se corregirán en la próxima build${NC}"
fi

# Check frontend (skip in production as it's a static build)
echo -e "${BLUE}   Verificando vulnerabilidades en frontend...${NC}"
echo -e "${YELLOW}   ℹ️  Frontend en producción es una build estática, verificando en directorio local...${NC}"

# Check if npm is available on the server
if command -v npm > /dev/null 2>&1; then
    # Check frontend vulnerabilities in local directory
    if [ -d "frontend" ] && [ -f "frontend/package.json" ]; then
        cd frontend
        if npm audit --audit-level=moderate > /dev/null 2>&1; then
            echo -e "${GREEN}   ✅ No hay vulnerabilidades en frontend${NC}"
        else
            echo -e "${YELLOW}   ⚠️  Vulnerabilidades encontradas en frontend${NC}"
            echo -e "${BLUE}   Aplicando correcciones automáticas...${NC}"
            if npm audit fix; then
                echo -e "${GREEN}   ✅ Vulnerabilidades corregidas en frontend${NC}"
            else
                echo -e "${YELLOW}   ⚠️  No se pudieron corregir todas las vulnerabilidades${NC}"
            fi
        fi
        cd ..
    else
        echo -e "${YELLOW}   ⚠️  Directorio frontend no encontrado, omitiendo verificación${NC}"
    fi
else
    echo -e "${YELLOW}   ⚠️  npm no está disponible en el servidor, omitiendo verificación de frontend${NC}"
    echo -e "${BLUE}   ℹ️  Las vulnerabilidades del frontend se corregirán en la próxima build${NC}"
fi

echo -e "${GREEN}✅ Verificación de seguridad completada${NC}"
echo ""

# Wait for PostgreSQL to be fully ready
echo -e "${BLUE}⏳ Waiting for PostgreSQL to be ready...${NC}"
until docker exec "$POSTGRES_CONTAINER" pg_isready -U postgres > /dev/null 2>&1; do
    echo -e "${BLUE}   PostgreSQL is not ready yet, waiting...${NC}"
    sleep 2
done
echo -e "${GREEN}✅ PostgreSQL is ready${NC}"

# Wait for backend to be ready
echo -e "${BLUE}⏳ Waiting for backend to be ready...${NC}"
sleep 10

# Step 8: Check database and run migrations
echo -e "${YELLOW}🔄 Paso 12/13: Verificando y configurando base de datos...${NC}"

# Check if database exists and has application tables
echo -e "${BLUE}ℹ️  Checking if database exists and has application tables...${NC}"
DB_EXISTS=$(docker exec "$POSTGRES_CONTAINER" psql -U postgres -lqt | cut -d \| -f 1 | grep -qw ai_learning_platform && echo "true" || echo "false")
HAS_TABLES="false"

if [ "$DB_EXISTS" = "true" ]; then
    # Check if database has application tables
    echo -e "${BLUE}ℹ️  Checking if database has application tables...${NC}"
    if docker exec "$POSTGRES_CONTAINER" psql -U postgres -d ai_learning_platform -c "\dt" | grep -q "users\|bots\|conversations"; then
        HAS_TABLES="true"
        echo -e "${GREEN}✅ Database exists and has application tables${NC}"
    else
        echo -e "${YELLOW}📊 Database exists but is empty, needs baseline${NC}"
    fi
else
    echo -e "${YELLOW}📊 Database does not exist, creating fresh database...${NC}"
    docker exec "$POSTGRES_CONTAINER" psql -U postgres -c "CREATE DATABASE ai_learning_platform;"
    echo -e "${GREEN}✅ Database created successfully${NC}"
fi

# Apply migrations using common script
echo -e "${BLUE}ℹ️  Applying database migrations using common script...${NC}"

if ./scripts/migrate-database.sh; then
    echo -e "${GREEN}✅ Migrations applied successfully${NC}"
else
    echo -e "${RED}❌ Migration failed${NC}"
    echo -e "${YELLOW}⚠️  Application is running but migrations failed!${NC}"
    echo -e "${YELLOW}Check the logs: docker logs ${BACKEND_CONTAINER}${NC}"
    echo ""
    echo -e "${BLUE}🔧 You can try manually:${NC}"
    echo -e "  docker exec ${BACKEND_CONTAINER} npx prisma migrate deploy"
    echo -e "  docker exec ${BACKEND_CONTAINER} npx prisma migrate status"
    exit 1
fi

# Reiniciar backend después de migraciones (para asegurar que carga el esquema actualizado)
echo -e "${YELLOW}♻️  Paso 13/13: Reiniciando backend para aplicar cambios...${NC}"
docker-compose --profile prod restart backend
sleep 5

# Verify services are running
echo ""
echo -e "${YELLOW}✅ Verificando estado de servicios...${NC}"
echo -e "${BLUE}📊 Checking service status...${NC}"
docker-compose ps

if docker-compose ps | grep -q "Up"; then
    echo -e "${GREEN}✅ All services are running${NC}"
else
    echo -e "${RED}❌ Some services may not be running properly${NC}"
    echo -e "${YELLOW}Check the logs: docker-compose logs -f${NC}"
    exit 1
fi

# Final health check
echo ""
echo -e "${YELLOW}🏥 Running health checks...${NC}"

# Check backend health (with retries)
BACKEND_HEALTHY=false
for i in {1..10}; do
    if curl -sf http://localhost:3000/health > /dev/null 2>&1; then
        echo -e "${GREEN}✅ Backend is responding (attempt $i/10)${NC}"
        BACKEND_HEALTHY=true
        break
    else
        if [ $i -lt 10 ]; then
            echo -e "${YELLOW}⏳ Backend not ready yet, waiting... (attempt $i/10)${NC}"
            sleep 5
        fi
    fi
done

if [ "$BACKEND_HEALTHY" = false ]; then
    echo -e "${RED}❌ Backend health check failed after 5 attempts${NC}"
    echo -e "${YELLOW}Check the logs: docker logs ${BACKEND_CONTAINER}${NC}"
fi

# Check frontend
if curl -sf http://localhost:8080 > /dev/null 2>&1; then
    echo -e "${GREEN}✅ Frontend is responding${NC}"
else
    echo -e "${YELLOW}⚠️  Frontend not responding on port 8080${NC}"
    echo -e "${YELLOW}This may be normal if nginx is handling the frontend${NC}"
fi

# Success message
echo ""
echo -e "${GREEN}═══════════════════════════════════════════════════════════${NC}"
echo -e "${GREEN}🎉 ¡Actualización completada con éxito!${NC}"
echo -e "${GREEN}═══════════════════════════════════════════════════════════${NC}"
echo ""
echo -e "${BLUE}📋 Resumen de la actualización:${NC}"
echo -e "  ✓ Paquetes del sistema actualizados"
echo -e "  ✓ Backup de base de datos creado"
echo -e "  ✓ Backup de archivos .env creados (timestamp: ${BACKUP_TIMESTAMP})"
echo -e "  ✓ Código actualizado desde la rama ${CURRENT_BRANCH}"
echo -e "  ✓ Backend y frontend reconstruidos"
echo -e "  ✓ Base de datos PostgreSQL preservada"
echo -e "  ✓ Migraciones de base de datos aplicadas"
echo -e "  ✓ Servicios reiniciados y verificados"
echo ""
echo -e "${BLUE}🔧 Comandos útiles:${NC}"
echo -e "  Ver todos los logs:       docker-compose logs -f"
echo -e "  Logs del backend:         docker logs ${BACKEND_CONTAINER} -f"
echo -e "  Logs del frontend:        docker logs ${FRONTEND_PROD_CONTAINER} -f"
echo -e "  Logs de Postgres:         docker logs ${POSTGRES_CONTAINER} -f"
echo -e "  Logs de Temporal:         docker logs ${TEMPORAL_CONTAINER} -f"
echo -e "  Estado de servicios:      docker-compose ps"
echo -e "  Reiniciar todos:          docker-compose --profile prod restart"
echo -e "  Reiniciar backend:        docker-compose restart backend"
echo -e "  Estado de migraciones:    docker exec ${BACKEND_CONTAINER} npx prisma migrate status"
echo ""
echo -e "${BLUE}🔄 Instrucciones de rollback (si es necesario):${NC}"
echo -e "  1. Detener contenedores:    docker-compose --profile prod down"
echo -e "  2. Restaurar base de datos: cat ~/backups/db_backup_YYYYMMDD_HHMMSS.sql | docker exec -i ${POSTGRES_CONTAINER} psql -U postgres -d ai_learning_platform"
echo -e "  3. Volver código anterior:  git checkout <hash-commit-anterior>"
echo -e "  4. Reconstruir e iniciar:   docker-compose --profile prod up -d --build"
echo ""
echo -e "${BLUE}📁 Ubicación de backups: ~/backups/${NC}"
echo -e "${BLUE}Último backup creado:${NC}"
ls -lht ~/backups/ 2>/dev/null | head -5 || echo "  No se encontraron backups"
echo ""
echo -e "${GREEN}✅ ¡Tu aplicación está ejecutando la última versión!${NC}"