#!/bin/bash

# Este script se encarga del despliegue en producción de English World Center Chatbot.
# Puede ejecutarse como root o como el usuario de despliegue. Si se ejecuta como root,
# no se usa sudo y los paths del servicio/cron usan el directorio del proyecto actual.

set -e # Exit on any error

echo "🚀 Starting English World Center Chatbot Production Deployment..."

# 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
PROJECT_NAME="englishworldcenter-chatbot"
DOMAIN_NAME="${1:-chat.englishworldcenter.com}"
EMAIL="${2:-operaciones+ewc@acceleralia.com}"
DEPLOY_USER="chat-englishworldcenter"

# Directorio del proyecto (donde se ejecuta el script)
PROJECT_DIR="$(pwd)"
RUNNING_AS_ROOT=false
if [ "$(id -u)" -eq 0 ]; then
    RUNNING_AS_ROOT=true
    SUDO=""  # Sin sudo cuando somos root
else
    SUDO="sudo"
fi

# Show configuration (parameters are optional)
if [ -z "$1" ] || [ -z "$2" ]; then
    echo -e "${BLUE}ℹ️  Using default configuration (no parameters provided)${NC}"
fi

echo -e "${BLUE}📋 Configuration:${NC}"
echo -e "  Project: ${PROJECT_NAME}"
echo -e "  Domain: ${DOMAIN_NAME}"
echo -e "  Email: ${EMAIL}"
echo -e "  Deploy User: ${DEPLOY_USER}"
echo -e "  Project Dir: ${PROJECT_DIR}"
echo -e "  Running as: $([ "$RUNNING_AS_ROOT" = true ] && echo 'root' || echo "$USER")"
echo ""

# --- Comprobar que estamos en el directorio del proyecto ---
if [ ! -f ".env" ] && [ ! -f "docker-compose.yml" ]; then
    echo -e "${RED}❌ Error: Execute this script from the project root (where .env and docker-compose.yml are).${NC}"
    exit 1
fi

# Update system packages
echo -e "${YELLOW}📦 Updating system packages...${NC}"
$SUDO apt update && $SUDO apt upgrade -y

# Install Docker if not installed
if ! command -v docker &> /dev/null; then
    echo -e "${YELLOW}🐳 Installing Docker...${NC}"
    curl -fsSL https://get.docker.com -o get-docker.sh
    $SUDO sh get-docker.sh
    # Añadir al usuario de la app al grupo docker (para que pueda usar docker si no es root)
    $SUDO usermod -aG docker "$DEPLOY_USER" 2>/dev/null || true
    [ "$RUNNING_AS_ROOT" = false ] && $SUDO usermod -aG docker "$USER" 2>/dev/null || true
    rm -f get-docker.sh
    echo -e "${GREEN}✅ Docker installed successfully${NC}"
else
    echo -e "${GREEN}✅ Docker already installed${NC}"
fi
# Asegurar que el usuario de despliegue pueda usar Docker (también cuando Docker ya estaba instalado)
$SUDO usermod -aG docker "$DEPLOY_USER" 2>/dev/null || true
[ "$RUNNING_AS_ROOT" = false ] && $SUDO usermod -aG docker "$USER" 2>/dev/null || true

# Install Docker Compose if not installed
if ! command -v docker-compose &> /dev/null; then
    echo -e "${YELLOW}🐳 Installing Docker Compose...${NC}"
    $SUDO curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    $SUDO chmod +x /usr/local/bin/docker-compose
    echo -e "${GREEN}✅ Docker Compose installed successfully${NC}"
else
    echo -e "${GREEN}✅ Docker Compose already installed${NC}"
fi

# Apache como reverse proxy (compatible con entornos donde ya corre Apache)
if ! command -v apache2 &> /dev/null && ! command -v apachectl &> /dev/null; then
    echo -e "${YELLOW}🌐 Installing Apache...${NC}"
    $SUDO apt install apache2 -y
    echo -e "${GREEN}✅ Apache installed successfully${NC}"
else
    echo -e "${GREEN}✅ Apache already installed${NC}"
fi

# Módulos necesarios para proxy y SSL
for mod in proxy proxy_http proxy_wstunnel rewrite ssl headers; do
    if $SUDO a2enmod "$mod" 2>/dev/null; then
        echo -e "${BLUE}   Módulo Apache $mod habilitado${NC}"
    fi
done

# Certbot y plugin Apache (si certbot ya existía puede tener solo plugin nginx; instalamos el de Apache siempre)
echo -e "${YELLOW}🔒 Ensuring Certbot and Apache plugin...${NC}"
$SUDO apt install -y certbot python3-certbot-apache 2>/dev/null || true
if ! $SUDO certbot plugins 2>/dev/null | grep -q apache; then
    echo -e "${RED}❌ No se pudo instalar el plugin Apache de Certbot. Instale manualmente: apt install python3-certbot-apache${NC}"
    exit 1
fi
echo -e "${GREEN}✅ Certbot con plugin Apache listo${NC}"

# Plantilla Apache equivalente a `frontend/nginx.conf.PROD`
# (compartida también por `fix-apache-ewc.sh`)
# shellcheck source=scripts/apache-ewc-config.inc.sh
source "${PROJECT_DIR}/scripts/apache-ewc-config.inc.sh"

# Create production environment file
echo -e "${YELLOW}⚙️  Verifying environment configuration...${NC}"
if [ ! -f ".env" ]; then
    echo -e "${RED}❌ Error: .env file not found.${NC}"
    echo -e "${YELLOW}Please ensure the repository is cloned and the .env file exists and is configured correctly.${NC}"
    exit 1
fi

# Generate secure JWT secrets if not changed
if grep -q "CHANGE-THIS-TO-A-SECURE-RANDOM-STRING-IN-PRODUCTION" .env; then
    echo -e "${YELLOW}🔐 Generating secure JWT secrets...${NC}"
    JWT_SECRET=$(openssl rand -base64 32)
    JWT_REFRESH_SECRET=$(openssl rand -base64 32)
    
    sed -i "s/CHANGE-THIS-TO-A-SECURE-RANDOM-STRING-IN-PRODUCTION/$JWT_SECRET/g" .env
    sed -i "s/CHANGE-THIS-TO-A-SECURE-RANDOM-STRING-IN-PRODUCTION/$JWT_REFRESH_SECRET/g" .env
    
    echo -e "${GREEN}✅ JWT secrets generated${NC}"
fi

# Note about ElevenLabs API key
echo -e "${BLUE}ℹ️  ElevenLabs API key will be configured via admin panel after deployment${NC}"

# Update domain in .env file
echo -e "${YELLOW}🌐 Updating domain configuration...${NC}"
sed -i "s/your-domain.com/${DOMAIN_NAME}/g" .env
sed -i "s/admin@your-domain.com/${EMAIL}/g" .env

# Check if SSL certificate already exists
CERT_PATH="/etc/letsencrypt/live/${DOMAIN_NAME}/fullchain.pem"
APACHE_SITES="${APACHE_SITES:-/etc/apache2/sites-available}"

# Escribir snippet de proxy (equivalente a nginx.conf.PROD)
write_apache_ewc_proxy_conf

if [ ! -f "$CERT_PATH" ]; then
    echo -e "${YELLOW}⚙️  Configuring Apache for Certbot and reverse proxy...${NC}"

    # VirtualHost :80 para validación Certbot. Usamos PROJECT_DIR como DocumentRoot para que
    # en Plesk (donde el dominio ya apunta a /var/www/vhosts/.../httpdocs) el reto se sirva desde ahí.
    $SUDO mkdir -p "${PROJECT_DIR}/.well-known/acme-challenge"
    $SUDO chown -R www-data:www-data "${PROJECT_DIR}/.well-known" 2>/dev/null || true
    $SUDO tee "${APACHE_SITES}/${PROJECT_NAME}.conf" > /dev/null <<EOF
<VirtualHost *:80>
    ServerName ${DOMAIN_NAME}
    DocumentRoot ${PROJECT_DIR}
    <Directory ${PROJECT_DIR}>
        Require all granted
    </Directory>
</VirtualHost>
EOF

    $SUDO a2ensite "${PROJECT_NAME}.conf" 2>/dev/null || true
    if ! $SUDO apache2ctl configtest 2>/dev/null && ! $SUDO apachectl configtest 2>/dev/null; then
        echo -e "${YELLOW}⚠️  Apache configtest falló (p. ej. otros vhosts o Plesk). Corrigiendo solo archivos del proyecto.${NC}"
        echo -e "${BLUE}   Si hay error en /etc/apache2/plesk.conf.d/modsecurity.conf, convierta finales de línea:${NC}"
        echo -e "${BLUE}   sed -i 's/\\r\$//' /etc/apache2/plesk.conf.d/modsecurity.conf${NC}"
    else
        $SUDO systemctl reload apache2 2>/dev/null || $SUDO systemctl reload httpd 2>/dev/null || true
    fi

    # Certificado con webroot: usar PROJECT_DIR para que en Plesk el reto se sirva desde el document root del dominio
    echo -e "${YELLOW}📜 Obtaining SSL certificate from Let's Encrypt (webroot mode)...${NC}"
    $SUDO certbot certonly --webroot -w "${PROJECT_DIR}" -d ${DOMAIN_NAME} --email ${EMAIL} --agree-tos --non-interactive

    # Crear vhost HTTPS (certbot --apache no se usa para evitar parsear config de Plesk)
    write_apache_ewc_ssl_vhost "${DOMAIN_NAME}"
    SSL_CONF="${APACHE_SITES}/${PROJECT_NAME}-le-ssl.conf"
    $SUDO a2ensite "$(basename "$SSL_CONF")" 2>/dev/null || true
    if $SUDO apache2ctl configtest 2>/dev/null || $SUDO apachectl configtest 2>/dev/null; then
        $SUDO systemctl reload apache2 2>/dev/null || $SUDO systemctl reload httpd 2>/dev/null || true
        echo -e "${GREEN}✅ Apache y SSL configurados${NC}"
    else
        echo -e "${YELLOW}⚠️  No se pudo recargar Apache (revisar otros configs, p. ej. modsecurity). Certificado obtenido correctamente.${NC}"
        echo -e "${BLUE}   Para corregir finales de línea en modsecurity: sed -i 's/\\r\$//' /etc/apache2/plesk.conf.d/modsecurity.conf${NC}"
    fi
else
    echo -e "${GREEN}✅ SSL certificate already exists. Skipping certificate request.${NC}"
    # Regenerar vhost TLS con la misma plantilla (paridad con nginx.conf.PROD)
    write_apache_ewc_ssl_vhost "${DOMAIN_NAME}"
    SSL_CONF="${APACHE_SITES}/${PROJECT_NAME}-le-ssl.conf"
    $SUDO a2ensite "$(basename "$SSL_CONF")" 2>/dev/null || true
    $SUDO systemctl reload apache2 2>/dev/null || $SUDO systemctl reload httpd 2>/dev/null || true
fi

# Security audit before deployment (solo si npm está instalado en el host; en servidores solo Docker suele no estar)
echo -e "${YELLOW}🔒 Verificando vulnerabilidades de seguridad antes del despliegue...${NC}"
if ! command -v npm &>/dev/null; then
    echo -e "${BLUE}   npm no instalado en el servidor (normal en producción). Omitiendo audit; se puede ejecutar en CI/desarrollo.${NC}"
    echo -e "${GREEN}✅ Verificación de seguridad omitida (sin npm)${NC}"
else
    # Check root directory
    echo -e "${BLUE}   Verificando vulnerabilidades en directorio raíz...${NC}"
    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

    # Check backend
    echo -e "${BLUE}   Verificando vulnerabilidades en backend...${NC}"
    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 ..

    # Check frontend
    echo -e "${BLUE}   Verificando vulnerabilidades en frontend...${NC}"
    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 ..

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

# Start the application
echo -e "${YELLOW}🚀 Starting the application...${NC}"
docker-compose --profile prod up -d --build

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

# Ensure database exists and run migrations
echo -e "${YELLOW}🗄️  Setting up database...${NC}"

# Wait for PostgreSQL to be fully ready
echo -e "${BLUE}⏳ Waiting for PostgreSQL to be ready...${NC}"
until docker exec ai-learning-platform-ewc-postgres 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}"

# Drop and recreate database (fresh deployment)
echo -e "${BLUE}🔍 Checking if database exists...${NC}"
if docker exec ai-learning-platform-ewc-postgres psql -U postgres -lqt | cut -d \| -f 1 | grep -qw ai_learning_platform; then
    echo -e "${YELLOW}🗑️  Database already exists, dropping and recreating for fresh deployment...${NC}"
    echo -e "${BLUE}   Cerrando conexiones activas a la base de datos...${NC}"
    docker exec ai-learning-platform-ewc-postgres psql -U postgres -c "SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = 'ai_learning_platform' AND pid <> pg_backend_pid();" > /dev/null 2>&1 || true
    sleep 2
    docker exec ai-learning-platform-ewc-postgres psql -U postgres -c "DROP DATABASE IF EXISTS ai_learning_platform;"
    echo -e "${GREEN}✅ Database dropped successfully${NC}"
fi

echo -e "${YELLOW}📊 Creating fresh database...${NC}"
docker exec ai-learning-platform-ewc-postgres psql -U postgres -c "CREATE DATABASE ai_learning_platform;"
echo -e "${GREEN}✅ Database created successfully${NC}"

# Run Prisma migrations to establish baseline
echo -e "${YELLOW}🔄 Setting up database schema with migrations...${NC}"
echo -e "${BLUE}ℹ️  Applying all migrations using common script...${NC}"

if ./scripts/migrate-database.sh; then
    echo -e "${GREEN}✅ All migrations applied successfully - baseline established${NC}"
    
    # Verify migrations were applied
    echo -e "${BLUE}ℹ️  Verifying migration status...${NC}"
    MIGRATION_STATUS=$(docker exec ai-learning-platform-ewc-backend npx prisma migrate status --schema=./prisma/schema.prisma 2>&1)
    if echo "$MIGRATION_STATUS" | grep -q "Database schema is up to date"; then
        echo -e "${GREEN}✅ Database schema is up to date${NC}"
    else
        echo -e "${YELLOW}⚠️  Migration status check:${NC}"
        echo "$MIGRATION_STATUS"
    fi
else
    echo -e "${RED}❌ Migration failed${NC}"
    echo -e "${YELLOW}Check the logs: docker logs ai-learning-platform-ewc-backend${NC}"
    echo -e "${BLUE}ℹ️  Migration status:${NC}"
    docker exec ai-learning-platform-ewc-backend npx prisma migrate status --schema=./prisma/schema.prisma 2>&1 || true
    exit 1
fi

# Run database seeding if enabled
if grep -q "RUN_SEED=1" .env; then
    echo -e "${YELLOW}🌱 Seeding database...${NC}"
    if docker exec ai-learning-platform-ewc-backend npx tsx src/prisma/seed.ts; then
        echo -e "${GREEN}✅ Database seeded successfully${NC}"
    else
        echo -e "${YELLOW}⚠️  Database seeding failed (this is not critical)${NC}"
    fi
else
    echo -e "${BLUE}ℹ️  Database seeding is disabled${NC}"
fi

# Check if services are running
if docker-compose ps | grep -q "Up"; then
    echo -e "${GREEN}✅ Application started successfully${NC}"
else
    echo -e "${RED}❌ Application failed to start. Check logs:${NC}"
    docker-compose logs
    exit 1
fi

# Setup firewall (solo si ufw está instalado; en Plesk/hosting suele gestionarlo el panel)
echo -e "${YELLOW}🔥 Configuring firewall...${NC}"
UFW_PATH=$($SUDO which ufw 2>/dev/null || true)
if [ -n "$UFW_PATH" ] && [ -x "$UFW_PATH" ]; then
    $SUDO ufw allow ssh 2>/dev/null || true
    $SUDO ufw allow 'Apache Full' 2>/dev/null || true
    $SUDO ufw --force enable 2>/dev/null || true
    echo -e "${GREEN}✅ Firewall (ufw) configurado${NC}"
else
    echo -e "${BLUE}   ufw no instalado; omitiendo. Si usas otro firewall, asegura que los puertos 80/443 y 22 estén permitidos.${NC}"
fi

# Create systemd service for auto-start (usa PROJECT_DIR para que funcione con root)
echo -e "${YELLOW}⚙️  Setting up auto-start service...${NC}"
$SUDO tee /etc/systemd/system/${PROJECT_NAME}.service > /dev/null <<EOF
[Unit]
Description=English World Center Chatbot
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=${PROJECT_DIR}
ExecStart=/usr/local/bin/docker-compose --profile prod up -d
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target
EOF

$SUDO systemctl daemon-reload
$SUDO systemctl enable ${PROJECT_NAME}

# Create backup script (BACKUP_DIR según si corre root o el usuario de despliegue)
if [ "$RUNNING_AS_ROOT" = true ]; then
    BACKUP_DIR_FOR_SCRIPT="/home/${DEPLOY_USER}/backups"
    CERTBOT_CMD="certbot"
    $SUDO mkdir -p "$BACKUP_DIR_FOR_SCRIPT"
else
    BACKUP_DIR_FOR_SCRIPT="/home/$USER/backups"
    CERTBOT_CMD="sudo certbot"
fi

echo -e "${YELLOW}💾 Creating backup script...${NC}"
tee backup.sh > /dev/null << EOF
#!/bin/bash
# Backup script for English World Center Chatbot

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

BACKUP_DIR="${BACKUP_DIR_FOR_SCRIPT}"
DATE=\$(date +%Y%m%d_%H%M%S)
DATE_FOLDER=\$(date +%Y%m%d)
BACKUP_DATE_DIR="\$BACKUP_DIR/\$DATE_FOLDER"

echo -e "\${BLUE}💾 Starting backup process...\${NC}"

# Create backup directory with date folder
mkdir -p \$BACKUP_DATE_DIR

# Backup database (run from project dir)
cd "${PROJECT_DIR}"
echo -e "\${YELLOW}📦 Backing up database...\${NC}"
if docker exec ai-learning-platform-ewc-postgres psql -U postgres -lqt | cut -d \\| -f 1 | grep -qw ai_learning_platform > /dev/null 2>&1; then
    if docker exec ai-learning-platform-ewc-postgres pg_dump -U postgres ai_learning_platform > \$BACKUP_DATE_DIR/db_backup_\$DATE.sql 2>/dev/null; then
        echo -e "\${GREEN}✅ Database backup completed\${NC}"
    else
        echo -e "\${RED}❌ Database backup failed\${NC}"
        exit 1
    fi
else
    echo -e "\${YELLOW}⚠️  Database 'ai_learning_platform' does not exist, skipping...\${NC}"
fi

# Backup uploads directory (only if it exists)
echo -e "\${YELLOW}📁 Backing up uploads directory...\${NC}"
if [ -d "backend/uploads" ] && [ "\$(ls -A backend/uploads 2>/dev/null)" ]; then
    if tar -czf \$BACKUP_DATE_DIR/uploads_backup_\$DATE.tar.gz backend/uploads/ 2>/dev/null; then
        echo -e "\${GREEN}✅ Uploads backup completed\${NC}"
    else
        echo -e "\${YELLOW}⚠️  Uploads backup failed (directory may be empty)\${NC}"
    fi
else
    echo -e "\${YELLOW}⚠️  Uploads directory not found or empty, skipping...\${NC}"
fi

# Backup logs from Docker volume
echo "📋 Backing up logs from Docker volume..."
if docker volume inspect ai-learning-platform-backend-logs > /dev/null 2>&1; then
    docker run --rm -v ai-learning-platform-backend-logs:/logs -v \$BACKUP_DATE_DIR:/backup alpine tar -czf /backup/logs_backup_\$DATE.tar.gz -C /logs . 2>/dev/null
    if [ \$? -eq 0 ] && [ -f "\$BACKUP_DATE_DIR/logs_backup_\$DATE.tar.gz" ]; then
        echo "✅ Logs backup completed"
    else
        echo "⚠️  Logs volume is empty, skipping..."
        rm -f \$BACKUP_DATE_DIR/logs_backup_\$DATE.tar.gz
    fi
else
    echo "⚠️  Logs volume not found, skipping..."
fi

# Keep only last 7 days of backups
echo -e "\${YELLOW}🧹 Cleaning up old backups...\${NC}"
find \$BACKUP_DIR -type d -name "20*" -mtime +7 -exec rm -rf {} + 2>/dev/null || true

echo -e "\${GREEN}✅ Backup completed: \$DATE\${NC}"
echo -e "\${BLUE}📁 Backup location: \$BACKUP_DATE_DIR\${NC}"

if [ -d "\$BACKUP_DIR" ]; then
    BACKUP_SIZE=\$(du -sh \$BACKUP_DIR | cut -f1)
    echo -e "\${BLUE}📊 Total backup size: \$BACKUP_SIZE\${NC}"
fi

echo -e "\${YELLOW}🔒 Renewing SSL certificate...\${NC}"
${CERTBOT_CMD} renew --quiet
EOF

chmod +x backup.sh

# Setup cron job for backups (ruta del script = PROJECT_DIR)
echo -e "${YELLOW}🕰️ Configuring cron job for backups and renewal...${NC}"
if [ "$RUNNING_AS_ROOT" = true ]; then
    (crontab -l 2>/dev/null | grep -v "${PROJECT_NAME}" || true; echo "0 2 * * * cd ${PROJECT_DIR} && ${PROJECT_DIR}/backup.sh") | crontab -
else
    (crontab -l 2>/dev/null | grep -v "${PROJECT_NAME}"; echo "0 2 * * * cd ${PROJECT_DIR} && ${PROJECT_DIR}/backup.sh") | crontab -
fi

echo ""
echo -e "${GREEN}🎉 Deployment completed successfully!${NC}"
echo ""
echo -e "${BLUE}📋 Next steps:${NC}"
echo -e "  1. Update your DNS to point ${DOMAIN_NAME} to this server's IP"
echo -e "  2. Wait for DNS propagation (5-30 minutes)"
echo -e "  3. Visit https://${DOMAIN_NAME} to access your application"
echo ""
echo -e "${BLUE}ℹ️  Usage: $0 [domain] [email]${NC}"
echo -e "  Default values: chat.englishworldcenter.com, operaciones+ewc@acceleralia.com"
echo ""
echo -e "${BLUE}🔧 Management commands:${NC}"
echo -e "  Start:   docker-compose --profile prod up -d"
echo -e "  Stop:    docker-compose down"
echo -e "  Logs:    docker-compose logs -f"
echo -e "  Status:  docker-compose ps"
echo -e "  Backup:  ./backup.sh"
echo -e "  DB Check: docker exec ai-learning-platform-ewc-postgres psql -U postgres -c '\\l'"
echo -e "  DB Migrate: docker exec ai-learning-platform-ewc-backend npx prisma migrate deploy"
echo ""
echo -e "${BLUE}📁 Important files:${NC}"
echo -e "  Config:  ${PROJECT_DIR}/.env"
echo -e "  Logs:    ${PROJECT_DIR}/logs/"
echo -e "  Backups: ${BACKUP_DIR_FOR_SCRIPT:-/home/$USER/backups}"
echo ""
echo -e "${GREEN}✅ Your English World Center Chatbot is now live!${NC}"
