#!/bin/bash
# Script de deployment rápido con Docker

set -e

echo "🐳 Deployment de WhatsApp Bot Manager con Docker"
echo "================================================"
echo ""

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

# 1. Verificar Docker
echo -e "${YELLOW}[1/6]${NC} Verificando Docker..."
if ! command -v docker &> /dev/null; then
    echo -e "${RED}❌ Docker no está instalado${NC}"
    echo "Instala Docker desde: https://docs.docker.com/get-docker/"
    exit 1
fi

if ! command -v docker-compose &> /dev/null; then
    echo -e "${RED}❌ Docker Compose no está instalado${NC}"
    echo "Instala Docker Compose desde: https://docs.docker.com/compose/install/"
    exit 1
fi

DOCKER_VERSION=$(docker --version)
COMPOSE_VERSION=$(docker-compose --version)
echo -e "${GREEN}✓ $DOCKER_VERSION${NC}"
echo -e "${GREEN}✓ $COMPOSE_VERSION${NC}"
echo ""

# 2. Verificar .env
echo -e "${YELLOW}[2/6]${NC} Verificando configuración..."
if [ ! -f .env ]; then
    echo -e "${YELLOW}⚠️  .env no existe, creando desde .env.docker...${NC}"
    cp .env.docker .env
    echo -e "${RED}⚠️  IMPORTANTE: Configura tus credenciales de WhatsApp en .env${NC}"
    echo ""
    echo "Edita el archivo .env y configura:"
    echo "  - WHATSAPP_TOKEN"
    echo "  - WHATSAPP_PHONE_NUMBER_ID"
    echo "  - WEBHOOK_VERIFY_TOKEN"
    echo "  - DB_PASS"
    echo ""
    read -p "¿Deseas editar .env ahora? (s/n) " -n 1 -r
    echo
    if [[ $REPLY =~ ^[Ss]$ ]]; then
        ${EDITOR:-nano} .env
    else
        echo -e "${YELLOW}⚠️  Recuerda configurar .env antes de usar el bot${NC}"
    fi
else
    echo -e "${GREEN}✓ .env encontrado${NC}"
fi
echo ""

# 3. Detener contenedores existentes
echo -e "${YELLOW}[3/6]${NC} Deteniendo contenedores existentes..."
docker-compose down 2>/dev/null || true
echo -e "${GREEN}✓ Limpieza completada${NC}"
echo ""

# 4. Construir imágenes
echo -e "${YELLOW}[4/6]${NC} Construyendo imágenes Docker..."
echo -e "${BLUE}Esto puede tomar varios minutos la primera vez...${NC}"
docker-compose build --no-cache
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Imágenes construidas${NC}"
else
    echo -e "${RED}❌ Error construyendo imágenes${NC}"
    exit 1
fi
echo ""

# 5. Iniciar servicios
echo -e "${YELLOW}[5/6]${NC} Iniciando servicios..."
docker-compose up -d
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Servicios iniciados${NC}"
else
    echo -e "${RED}❌ Error iniciando servicios${NC}"
    exit 1
fi
echo ""

# Esperar a que los servicios estén listos
echo "⏳ Esperando que los servicios estén listos..."
sleep 10

# 6. Verificar estado
echo -e "${YELLOW}[6/6]${NC} Verificando estado de servicios..."
echo ""

# Health check
echo "🏥 Health Check:"
HEALTH_STATUS=$(curl -s http://localhost:${APP_PORT:-8080}/health.php 2>/dev/null || echo '{"status":"unreachable"}')
HEALTH=$(echo $HEALTH_STATUS | grep -o '"status":"[^"]*"' | cut -d'"' -f4)

if [ "$HEALTH" == "healthy" ]; then
    echo -e "${GREEN}✓ Aplicación: HEALTHY${NC}"
else
    echo -e "${RED}✗ Aplicación: $HEALTH${NC}"
    echo "Ver logs con: docker-compose logs app"
fi
echo ""

# Estado de contenedores
echo "📦 Estado de contenedores:"
docker-compose ps
echo ""

# Workers
echo "👷 Workers:"
WORKERS=$(docker-compose exec -T app supervisorctl status 2>/dev/null | grep whatsapp-worker || echo "No disponible")
if echo "$WORKERS" | grep -q "RUNNING"; then
    WORKER_COUNT=$(echo "$WORKERS" | grep -c "RUNNING")
    echo -e "${GREEN}✓ $WORKER_COUNT workers corriendo${NC}"
else
    echo -e "${YELLOW}⚠️  Workers no verificables (puede estar iniciando)${NC}"
fi
echo ""

# Redis
echo "💾 Redis:"
REDIS_PING=$(docker-compose exec -T redis redis-cli ping 2>/dev/null || echo "ERROR")
if [ "$REDIS_PING" == "PONG" ]; then
    echo -e "${GREEN}✓ Redis: PONG${NC}"
else
    echo -e "${RED}✗ Redis: no responde${NC}"
fi
echo ""

# MySQL
echo "🗄️  MySQL:"
MYSQL_STATUS=$(docker-compose exec -T db mysqladmin ping -h localhost -u root -p${DB_ROOT_PASSWORD:-rootpass} 2>/dev/null | grep -c "alive")
if [ "$MYSQL_STATUS" -eq 1 ]; then
    echo -e "${GREEN}✓ MySQL: alive${NC}"
else
    echo -e "${RED}✗ MySQL: no responde${NC}"
fi
echo ""

# Resumen final
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo -e "${GREEN}✅ Deployment completado${NC}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "🌐 Aplicación disponible en:"
echo "   http://localhost:${APP_PORT:-8080}"
echo ""
echo "📊 Herramientas de desarrollo (--profile dev):"
echo "   PHPMyAdmin: http://localhost:${PHPMYADMIN_PORT:-8081}"
echo "   Redis Commander: http://localhost:${REDIS_COMMANDER_PORT:-8082}"
echo ""
echo "📋 Comandos útiles:"
echo "   Ver logs:      docker-compose logs -f"
echo "   Ver estado:    docker-compose ps"
echo "   Reiniciar:     docker-compose restart"
echo "   Detener:       docker-compose down"
echo "   Shell app:     docker-compose exec app sh"
echo ""
echo "🔗 Webhook URL para WhatsApp:"
echo "   https://tudominio.com/api/webhook_optimized.php"
echo ""
echo "📚 Documentación completa: DOCKER_README.md"
echo ""

# Preguntar si desea ver logs
read -p "¿Deseas ver los logs en tiempo real? (s/n) " -n 1 -r
echo
if [[ $REPLY =~ ^[Ss]$ ]]; then
    docker-compose logs -f
fi
