#!/bin/bash

# Script de instalación rápida de la arquitectura mejorada
# Ejecutar: bash install_architecture.sh

echo "🚀 Instalando arquitectura mejorada para WhatsApp Bot..."
echo ""

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

# 1. Verificar PHP
echo -e "${YELLOW}[1/7]${NC} Verificando PHP..."
if ! command -v php &> /dev/null; then
    echo -e "${RED}❌ PHP no está instalado${NC}"
    exit 1
fi
PHP_VERSION=$(php -r "echo PHP_VERSION;")
echo -e "${GREEN}✓ PHP $PHP_VERSION detectado${NC}"
echo ""

# 2. Verificar Composer
echo -e "${YELLOW}[2/7]${NC} Verificando Composer..."
if ! command -v composer &> /dev/null; then
    echo -e "${YELLOW}⚠️  Composer no encontrado. Instalando...${NC}"
    php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
    php composer-setup.php --quiet
    rm composer-setup.php
    sudo mv composer.phar /usr/local/bin/composer
fi
echo -e "${GREEN}✓ Composer instalado${NC}"
echo ""

# 3. Instalar dependencias
echo -e "${YELLOW}[3/7]${NC} Instalando dependencias PHP..."
composer install --no-dev --optimize-autoloader
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Dependencias instaladas${NC}"
else
    echo -e "${RED}❌ Error instalando dependencias${NC}"
    exit 1
fi
echo ""

# 4. Verificar/Instalar Redis
echo -e "${YELLOW}[4/7]${NC} Verificando Redis..."
if ! command -v redis-cli &> /dev/null; then
    echo -e "${YELLOW}⚠️  Redis no encontrado. ¿Deseas instalarlo? (s/n)${NC}"
    read -r response
    if [[ "$response" =~ ^([sS][iI]|[sS])$ ]]; then
        if [ -f /etc/debian_version ]; then
            # Debian/Ubuntu
            sudo apt update
            sudo apt install redis-server -y
            sudo systemctl enable redis-server
            sudo systemctl start redis-server
        elif [ -f /etc/redhat-release ]; then
            # CentOS/RHEL
            sudo yum install redis -y
            sudo systemctl enable redis
            sudo systemctl start redis
        else
            echo -e "${RED}❌ Sistema operativo no soportado para instalación automática de Redis${NC}"
            echo "Por favor instala Redis manualmente"
            exit 1
        fi
    else
        echo -e "${RED}❌ Redis es requerido. Instálalo manualmente y vuelve a ejecutar este script${NC}"
        exit 1
    fi
fi

# Verificar que Redis esté corriendo
redis-cli ping > /dev/null 2>&1
if [ $? -eq 0 ]; then
    echo -e "${GREEN}✓ Redis está corriendo${NC}"
else
    echo -e "${RED}❌ Redis no está respondiendo. Iniciando...${NC}"
    sudo systemctl start redis-server || sudo systemctl start redis
    sleep 2
    redis-cli ping > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo -e "${GREEN}✓ Redis iniciado correctamente${NC}"
    else
        echo -e "${RED}❌ No se pudo iniciar Redis${NC}"
        exit 1
    fi
fi
echo ""

# 5. Crear directorios necesarios
echo -e "${YELLOW}[5/7]${NC} Creando directorios..."
mkdir -p logs
mkdir -p uploads
chmod 755 logs uploads
echo -e "${GREEN}✓ Directorios creados${NC}"
echo ""

# 6. Configurar .env
echo -e "${YELLOW}[6/7]${NC} Configurando .env..."
if [ ! -f .env ]; then
    cp .env.example .env
    echo -e "${GREEN}✓ Archivo .env creado${NC}"
    echo -e "${YELLOW}⚠️  Recuerda configurar las variables de WhatsApp en .env${NC}"
else
    echo -e "${YELLOW}⚠️  .env ya existe, no se sobrescribirá${NC}"
fi
echo ""

# 7. Configurar Supervisor (opcional)
echo -e "${YELLOW}[7/7]${NC} ¿Deseas configurar Supervisor para los workers? (s/n)"
read -r response
if [[ "$response" =~ ^([sS][iI]|[sS])$ ]]; then
    if ! command -v supervisorctl &> /dev/null; then
        echo "Instalando Supervisor..."
        if [ -f /etc/debian_version ]; then
            sudo apt install supervisor -y
        elif [ -f /etc/redhat-release ]; then
            sudo yum install supervisor -y
        fi
        sudo systemctl enable supervisor
        sudo systemctl start supervisor
    fi
    
    # Obtener ruta absoluta del proyecto
    PROJECT_DIR=$(pwd)
    
    # Crear configuración de supervisor
    SUPERVISOR_CONF="/etc/supervisor/conf.d/whatsapp-worker.conf"
    
    echo "Creando configuración de supervisor..."
    sudo tee $SUPERVISOR_CONF > /dev/null <<EOF
[program:whatsapp-worker]
command=/usr/bin/php $PROJECT_DIR/worker.php --daemon
process_name=%(program_name)s_%(process_num)02d
numprocs=3
directory=$PROJECT_DIR
autostart=true
autorestart=true
startsecs=1
startretries=3
user=$(whoami)
redirect_stderr=true
stdout_logfile=$PROJECT_DIR/logs/supervisor-worker.log
stdout_logfile_maxbytes=10MB
stdout_logfile_backups=10
stopwaitsecs=30
stopsignal=TERM
EOF
    
    # Recargar supervisor
    sudo supervisorctl reread
    sudo supervisorctl update
    sudo supervisorctl start whatsapp-worker:*
    
    sleep 2
    
    # Verificar estado
    WORKER_STATUS=$(sudo supervisorctl status whatsapp-worker:* | grep RUNNING | wc -l)
    if [ "$WORKER_STATUS" -ge 1 ]; then
        echo -e "${GREEN}✓ Workers iniciados con Supervisor ($WORKER_STATUS procesos)${NC}"
    else
        echo -e "${RED}❌ Error iniciando workers${NC}"
        sudo supervisorctl status whatsapp-worker:*
    fi
else
    echo -e "${YELLOW}⚠️  Puedes iniciar workers manualmente con: php worker.php --daemon${NC}"
fi
echo ""

# Resumen final
echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo -e "${GREEN}✅ Instalación completada${NC}"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo ""
echo "📋 Próximos pasos:"
echo ""
echo "1. Configurar WhatsApp en .env:"
echo "   nano .env"
echo ""
echo "2. Actualizar webhook en WhatsApp:"
echo "   https://tudominio.com/api/webhook_optimized.php"
echo ""
echo "3. Verificar workers:"
echo "   sudo supervisorctl status"
echo ""
echo "4. Ver logs en tiempo real:"
echo "   tail -f logs/webhook.log"
echo "   tail -f logs/worker.log"
echo ""
echo "5. Monitorear Redis:"
echo "   redis-cli"
echo "   KEYS whatsapp:queue:*"
echo ""
echo "📚 Documentación completa: ARQUITECTURA_MEJORADA.md"
echo ""
