#!/bin/bash

# Inventory Management System Docker Build Script
# This script builds and deploys the complete inventory solution

set -e

echo "🚀 Building Inventory Management System..."

# Docker Compose wrapper function to handle threading errors
docker_compose_safe() {
    local max_attempts=3
    local attempt=1
    local cmd="$@"
    
    while [ $attempt -le $max_attempts ]; do
        echo "🔄 Docker Compose attempt $attempt/$max_attempts: $cmd"
        
        if docker-compose $cmd 2>/dev/null; then
            echo "✅ Docker Compose command succeeded"
            return 0
        else
            echo "⚠️  Docker Compose command failed (attempt $attempt/$max_attempts)"
            if [ $attempt -eq $max_attempts ]; then
                echo "🔧 Trying without stderr redirection..."
                if docker-compose $cmd; then
                    echo "✅ Docker Compose command succeeded on retry"
                    return 0
                else
                    echo "❌ Docker Compose command failed after $max_attempts attempts"
                    return 1
                fi
            fi
            sleep 2
            ((attempt++))
        fi
    done
    return 1
}

# Load environment variables from .env file
if [ -f .env ]; then
    echo "📝 Loading environment variables from .env..."
    export $(cat .env | grep -v '^#' | xargs)
else
    echo "❌ .env file not found. Please copy .env.example to .env and configure it."
    exit 1
fi

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo "❌ 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
    echo "❌ Docker Compose is not installed. Please install Docker Compose first."
    exit 1
fi

# Validate required environment variables
if [ -z "$DB_HOST" ] || [ "$DB_HOST" = "your-external-db-host" ]; then
    echo "❌ DB_HOST is not configured in .env. Please set your external database host."
    exit 1
fi

if [ -z "$DB_USER" ] || [ "$DB_USER" = "your-db-username" ]; then
    echo "❌ DB_USER is not configured in .env. Please set your database username."
    exit 1
fi

if [ -z "$DB_PASS" ] || [ "$DB_PASS" = "your-db-password" ]; then
    echo "❌ DB_PASS is not configured in .env. Please set your database password."
    exit 1
fi

# Create uploads and attachments directories if they don't exist
if [ ! -d uploads ]; then
    echo "📁 Creating uploads directory..."
    mkdir -p uploads
    chmod 755 uploads
fi

if [ ! -d attachments ]; then
    echo "📁 Creating attachments directory..."
    mkdir -p attachments
    chmod 755 attachments
fi

# Copy .env to backend/.env.local for PHP application
echo "📝 Copying environment variables to backend/.env.local..."
if [ -f .env ]; then
    cp .env backend/.env.local
    echo "✅ Environment variables copied to backend/.env.local"
else
    echo "❌ .env file not found. Cannot create backend/.env.local"
    exit 1
fi

# Check if Redis is already running on the specified port
REDIS_PORT=${REDIS_PORT:-6379}
REDIS_RUNNING=false
REDIS_HOST="localhost"

if command -v netstat &> /dev/null; then
    if netstat -tuln 2>/dev/null | grep -q ":$REDIS_PORT "; then
        echo "🔴 Redis is already running on port $REDIS_PORT"
        REDIS_RUNNING=true
        REDIS_HOST=$(netstat -tuln 2>/dev/null | grep ":$REDIS_PORT " | head -1 | awk '{print $4}' | cut -d':' -f1)
        if [ "$REDIS_HOST" = "0.0.0.0" ] || [ "$REDIS_HOST" = "::" ]; then
            REDIS_HOST="localhost"
        fi
    fi
elif command -v ss &> /dev/null; then
    if ss -tuln 2>/dev/null | grep -q ":$REDIS_PORT "; then
        echo "🔴 Redis is already running on port $REDIS_PORT"
        REDIS_RUNNING=true
        REDIS_HOST=$(ss -tuln 2>/dev/null | grep ":$REDIS_PORT " | head -1 | awk '{print $4}' | cut -d':' -f1)
        if [ "$REDIS_HOST" = "0.0.0.0" ] || [ "$REDIS_HOST" = "::" ]; then
            REDIS_HOST="localhost"
        fi
    fi
fi

# Display configuration summary
echo "📋 Configuration Summary:"
echo "   🌐 Frontend Port: ${FRONTEND_PORT:-80}"
echo "   🗄️  Database Host: $DB_HOST"
echo "   🗄️  Database Port: ${DB_PORT:-3306}"
echo "   🗄️  Database Name: ${DB_NAME:-inventory_db}"
echo "   🗄️  Database User: $DB_USER"
echo "   🔴 Redis Port: $REDIS_PORT ($([ "$REDIS_RUNNING" = true ] && echo "EXTERNAL" || echo "DOCKER"))"
echo ""

# Test environment variables and database connection inside container
echo "🧪 Testing environment variables and database connection..."
docker exec inventory-app php /var/www/html/test-env.php

# Fix incorrect image URLs in database
echo "🔧 Fixing incorrect image URLs in database..."
docker exec inventory-app php /var/www/html/fix_image_urls.php

# Run database migration script
echo "🔄 Running database migration script..."
docker-compose run --rm inventory-app php /var/www/html/migrate.php

# Test environment variables and database connectivity
echo "🔍 Testing environment variables and database connectivity..."
echo "ℹ️  Note: If you see Docker Compose threading errors, they can be safely ignored"
if ! timeout 30 docker-compose run --rm inventory-app php /var/www/html/test-env.php 2>/dev/null; then
    echo "❌ Environment variables or database connection test failed."
    echo "💡 Make sure:"
    echo "   - Environment variables are properly set in .env"
    echo "   - Database server is running and accessible"
    echo "   - Database '$DB_NAME' exists"
    echo "   - User '$DB_USER' has proper permissions"
    echo "   - Network allows connection from Docker container"
    echo ""
    echo "🔍 Debug: Check container logs for detailed error information"
    docker-compose logs inventory-app | tail -20 2>/dev/null || echo "Could not fetch logs"
    exit 1
fi

# Build and start the application
echo "🔨 Building Docker containers..."
echo "ℹ️  Note: Docker Compose threading errors can be safely ignored during build"
if [ "$REDIS_RUNNING" = true ]; then
    echo "🔴 Skipping Redis build (external Redis detected)"
    docker-compose build inventory-app 2>/dev/null || docker-compose build inventory-app
else
    echo "🔨 Building all containers including Redis..."
    docker-compose build 2>/dev/null || docker-compose build
fi

echo "🚀 Starting application..."
if [ "$REDIS_RUNNING" = true ]; then
    echo "🔴 Starting application without Redis (using external Redis at $REDIS_HOST:$REDIS_PORT)"
    docker-compose up -d inventory-app 2>/dev/null || docker-compose up -d inventory-app
else
    echo "🚀 Starting application with Redis..."
    docker-compose up -d 2>/dev/null || docker-compose up -d
fi

# Wait a moment for services to start
echo "⏳ Waiting for services to start..."
sleep 10

# Check if containers are running
echo "🔍 Checking container status..."
docker-compose ps 2>/dev/null || echo "⚠️  Could not get container status (Docker Compose threading error)"

# Show logs
echo "📋 Showing application logs..."
docker-compose logs inventory-app 2>/dev/null || echo "⚠️  Could not fetch logs (Docker Compose threading error)"

# Clean up unnecessary Docker images
echo "🧹 Cleaning up unnecessary Docker images..."
echo "🔍 Removing dangling images..."
DANGLING_IMAGES=$(docker images -f "dangling=true" -q)
if [ -n "$DANGLING_IMAGES" ]; then
    echo "🗑️  Removing $(echo "$DANGLING_IMAGES" | wc -l) dangling images..."
    docker rmi $DANGLING_IMAGES 2>/dev/null || true
else
    echo "✅ No dangling images found"
fi

echo "🔍 Removing unused build cache..."
docker builder prune -f --keep-storage 1GB 2>/dev/null || true

echo "🔍 Removing unused images (keeping last 24 hours)..."
# Remove images older than 24 hours that are not being used
UNUSED_IMAGES=$(docker images --format "table {{.Repository}}:{{.Tag}}\t{{.CreatedAt}}\t{{.ID}}" | grep -v "REPOSITORY" | awk '$2 < "'$(date -d '24 hours ago' '+%Y-%m-%d %H:%M:%S')'" {print $3}' | head -10)
if [ -n "$UNUSED_IMAGES" ]; then
    echo "🗑️  Removing old unused images..."
    echo "$UNUSED_IMAGES" | xargs docker rmi 2>/dev/null || true
else
    echo "✅ No old unused images found"
fi

# Show cleanup results
echo ""
echo "📊 Docker cleanup summary:"
echo "   📦 Images remaining: $(docker images -q | wc -l)"
echo "   💾 Space used: $(docker system df --format "table {{.Type}}\t{{.TotalCount}}\t{{.Size}}" | grep -E "Images|Local Volumes" | awk '{printf "   %-15s %3s %10s\n", $1, $2, $3}')"

echo ""
echo "✅ Build complete!"
echo ""
echo "🌐 Application is available at: http://localhost:${FRONTEND_PORT:-80}"
echo "🔧 API endpoints are available at: http://localhost:${FRONTEND_PORT:-80}/api"
echo "🗄️  Connected to database: $DB_HOST:${DB_PORT:-3306}/$DB_NAME"
if [ "$REDIS_RUNNING" = true ]; then
    echo "🔴 Using external Redis: $REDIS_HOST:$REDIS_PORT"
else
    echo "🔴 Using Docker Redis: localhost:$REDIS_PORT"
fi
echo ""
echo "📝 Management Commands:"
echo "   🛑 Stop application: docker-compose down"
echo "   📋 View logs: docker-compose logs -f"
echo "   🔄 Rebuild: docker-compose build --no-cache"
echo "   🐚 Access container: docker-compose exec inventory-app bash"
echo "   🧹 Full cleanup: docker system prune -a"
if [ "$REDIS_RUNNING" = true ]; then
    echo "   🔴 Redis management: Use your external Redis tools"
else
    echo "   🔴 Redis access: docker-compose exec redis redis-cli"
fi
