#!/bin/bash

# Infrastructure Optimization Deployment Script
# For ENI-72: CRITICAL Infrastructure Optimization - Scale to 1000+ Concurrent Users

set -e

echo "🚀 CBTAPPS Infrastructure Optimization Deployment"
echo "================================================"
echo ""

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

# Function to print colored output
print_status() {
    echo -e "${GREEN}✓${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}⚠${NC} $1"
}

print_error() {
    echo -e "${RED}✗${NC} $1"
}

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    print_error "Docker is not installed. Please install Docker first."
    exit 1
fi

# Check if Docker Compose is installed
if ! command -v docker-compose &> /dev/null; then
    print_error "Docker Compose is not installed. Please install Docker Compose first."
    exit 1
fi

print_status "Docker and Docker Compose are installed"

# Verify configuration files exist
echo ""
echo "📋 Verifying configuration files..."

CONFIG_FILES=(
    "docker/php-fpm.conf"
    "docker/nginx.conf"
    "docker/postgresql.conf"
    "docker-compose.prod.yml"
    "Dockerfile"
)

for file in "${CONFIG_FILES[@]}"; do
    if [ -f "$file" ]; then
        print_status "Found: $file"
    else
        print_error "Missing: $file"
        exit 1
    fi
done

# Check environment file
echo ""
echo "📋 Checking environment configuration..."

if [ ! -f ".env" ]; then
    print_warning ".env file not found. Creating from .env.prod..."
    cp .env.prod .env
    print_status "Created .env from .env.prod"
else
    print_status ".env file exists"
fi

# Verify critical environment variables
echo ""
echo "📋 Verifying critical environment variables..."

source .env

CRITICAL_VARS=(
    "DB_CONNECTION"
    "DB_HOST"
    "DB_DATABASE"
    "DB_USERNAME"
    "DB_PASSWORD"
)

ALL_VARS_SET=true
for var in "${CRITICAL_VARS[@]}"; do
    if [ -z "${!var}" ]; then
        print_warning "$var is not set"
        ALL_VARS_SET=false
    else
        print_status "$var is set"
    fi
done

if [ "$ALL_VARS_SET" = false ]; then
    print_error "Some critical environment variables are not set. Please update .env file."
    exit 1
fi

# Verify optimization variables
echo ""
echo "📋 Verifying optimization configuration..."

OPTIMIZATION_VARS=(
    "DB_MAX_CONNECTIONS=200"
    "REDIS_MAX_CONNECTIONS=100"
)

for var_config in "${OPTIMIZATION_VARS[@]}"; do
    var_name=$(echo $var_config | cut -d'=' -f1)
    expected_value=$(echo $var_config | cut -d'=' -f2)
    actual_value="${!var_name}"

    if [ "$actual_value" = "$expected_value" ]; then
        print_status "$var_name=$actual_value (optimized)"
    else
        print_warning "$var_name=$actual_value (expected: $expected_value)"
    fi
done

# Build Docker images
echo ""
echo "🔨 Building Docker images..."

print_status "Building PHP-FPM image..."
docker build -t cbtapps:optimized .

if [ $? -eq 0 ]; then
    print_status "Docker image built successfully"
else
    print_error "Docker image build failed"
    exit 1
fi

# Start services
echo ""
echo "🚀 Starting optimized services..."

print_status "Stopping any existing services..."
docker-compose -f docker-compose.prod.yml down 2>/dev/null || true

print_status "Starting services with optimized configuration..."
docker-compose -f docker-compose.prod.yml up -d

# Wait for services to be healthy
echo ""
echo "⏳ Waiting for services to be healthy..."

sleep 10

# Check service status
echo ""
echo "📊 Service Status:"
docker-compose -f docker-compose.prod.yml ps

# Run health checks
echo ""
echo "🏥 Running health checks..."

# Check nginx
if docker-compose -f docker-compose.prod.yml exec -T nginx wget --quiet --tries=1 --spider http://localhost/health 2>/dev/null; then
    print_status "Nginx is responding"
else
    print_warning "Nginx health check failed (this is normal if Laravel is not fully initialized)"
fi

# Check PostgreSQL
if docker-compose -f docker-compose.prod.yml exec -T postgres pg_isready -U ${DB_USERNAME} -d ${DB_DATABASE} &>/dev/null; then
    print_status "PostgreSQL is ready"
else
    print_error "PostgreSQL health check failed"
    exit 1
fi

# Check Redis
if docker-compose -f docker-compose.prod.yml exec -T redis redis-cli ping &>/dev/null; then
    print_status "Redis is responding"
else
    print_error "Redis health check failed"
    exit 1
fi

# Display logs
echo ""
echo "📋 Recent logs:"
docker-compose -f docker-compose.prod.yml logs --tail=20

# Display connection information
echo ""
echo "🔗 Connection Information:"
echo "==========================="
echo "Nginx (HTTP):    http://localhost:80"
echo "PostgreSQL:      ${DB_HOST}:${DB_PORT:-5432}"
echo "Redis:           localhost:${REDIS_PORT:-6379}"
echo ""

# Display PHP-FPM configuration
echo "🔧 PHP-FPM Configuration:"
echo "========================="
docker-compose -f docker-compose.prod.yml exec -T php-fpm php -r "
echo 'PHP Version: ' . PHP_VERSION . PHP_EOL;
echo 'OPcache: ' . (function_exists('opcache_get_status') ? 'Enabled' : 'Disabled') . PHP_EOL;
echo 'Memory Limit: ' . ini_get('memory_limit') . PHP_EOL;
echo 'Max Execution Time: ' . ini_get('max_execution_time') . 's' . PHP_EOL;
"

# Display PostgreSQL configuration
echo ""
echo "🔧 PostgreSQL Configuration:"
echo "==========================="
docker-compose -f docker-compose.prod.yml exec -T postgres psql -U ${DB_USERNAME} -d ${DB_DATABASE} -c "
SHOW max_connections;
SHOW shared_buffers;
SHOW effective_cache_size;
"

# Display Redis configuration
echo ""
echo "🔧 Redis Configuration:"
echo "======================"
docker-compose -f docker-compose.prod.yml exec -T redis redis-cli CONFIG GET maxclients
docker-compose -f docker-compose.prod.yml exec -T redis redis-cli CONFIG GET maxmemory

# Next steps
echo ""
echo "✅ Deployment completed successfully!"
echo ""
echo "📋 Next Steps:"
echo "1. Run smoke tests: docker-compose -f docker-compose.prod.yml exec php-fpm php artisan test"
echo "2. Run load tests: k6 run loadtest.yml --vus 1000 --duration 10m"
echo "3. Monitor logs: docker-compose -f docker-compose.prod.yml logs -f"
echo "4. Check metrics: docker-compose -f docker-compose.prod.yml exec php-fpm php-fpm-status"
echo ""
echo "📚 For more information, see: INFRASTRUCTURE_OPTIMIZATION_REPORT.md"
echo ""
echo "🎯 Ready for testing! System is configured for 1000+ concurrent users."
echo ""
