#!/bin/bash

# ============================================
# Mawidi Docker Manager
# Comprehensive Docker management script
# Version: 2.2.0
# Updated: January 2025
# ============================================

set -e

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

# Change to project root
cd "$(dirname "$0")" || exit 1

# Detect docker compose command
if command -v docker-compose &> /dev/null; then
    COMPOSE_CMD="docker-compose"
else
    COMPOSE_CMD="docker compose"
fi

# Function to print colored output
print_color() {
    echo -e "${1}${2}${NC}"
}

# Function to show usage
show_usage() {
    echo "Mawidi Docker Manager"
    echo "Usage: $0 [command] [options]"
    echo ""
    echo "Commands:"
    echo "  build       Build Docker images"
    echo "  update      Rebuild images and restart services"
    echo "  up          Start services"
    echo "  down        Stop services"
    echo "  restart     Restart services"
    echo "  logs        Show logs"
    echo "  status      Show container status"
    echo "  clean       Clean up containers and volumes"
    echo "  prune       Remove unused Docker resources"
    echo "  shell       Open shell in container"
    echo "  test        Run tests in container"
    echo "  deploy      Deploy to production"
    echo ""
    echo "Options:"
    echo "  --dev       Use development profile"
    echo "  --prod      Use production profile (default)"
    echo "  --preview   Use preview profile"
    echo "  --all       Apply to all services"
    echo "  --no-cache  Build without cache"
    echo ""
    echo "Examples:"
    echo "  $0 build --dev            Build development image"
    echo "  $0 up --prod              Start production service"
    echo "  $0 logs --dev             Show development logs"
    echo "  $0 shell --dev            Open shell in dev container"
}

# Parse command
COMMAND=${1:-help}
shift || true

# Parse options
PROFILE="prod"
SERVICE=""
BUILD_ARGS=""
COMPOSE_ARGS=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --dev)
            PROFILE="dev"
            SERVICE="mawidi-dev"
            COMPOSE_ARGS="--profile dev"
            shift
            ;;
        --prod)
            PROFILE="prod"
            SERVICE="mawidi-app"
            COMPOSE_ARGS=""
            shift
            ;;
        --preview)
            PROFILE="preview"
            SERVICE="mawidi-app-preview"
            COMPOSE_ARGS="--profile preview"
            shift
            ;;
        --all)
            SERVICE=""
            COMPOSE_ARGS=""
            shift
            ;;
        --no-cache)
            BUILD_ARGS="--no-cache"
            shift
            ;;
        *)
            shift
            ;;
    esac
done

# Execute command
case $COMMAND in
    build)
        print_color "$BLUE" "📦 Building Docker images..."
        $COMPOSE_CMD $COMPOSE_ARGS build $BUILD_ARGS $SERVICE
        print_color "$GREEN" "✅ Build complete!"
        ;;

    update)
        print_color "$BLUE" "🔄 Updating Codex services..."
        if ! $COMPOSE_CMD $COMPOSE_ARGS build $BUILD_ARGS $SERVICE; then
            print_color "$RED" "❌ Build failed - aborting update."
            exit 1
        fi

        print_color "$YELLOW" "🛑 Recreating containers with latest images..."
        if ! $COMPOSE_CMD $COMPOSE_ARGS up -d --force-recreate $SERVICE; then
            print_color "$RED" "❌ Failed to restart services."
            exit 1
        fi

        if [ "$PROFILE" = "dev" ]; then
            print_color "$GREEN" "✅ Development server refreshed: http://localhost:3000"
        elif [ "$PROFILE" = "preview" ]; then
            print_color "$GREEN" "✅ Preview server refreshed: http://localhost:9150"
        else
            print_color "$GREEN" "✅ Production server refreshed: http://localhost:9000"
        fi

        print_color "$BLUE" "📊 Container status:"
        $COMPOSE_CMD $COMPOSE_ARGS ps
        ;;

    up|start)
        print_color "$BLUE" "🚀 Starting services..."
        $COMPOSE_CMD $COMPOSE_ARGS up -d $SERVICE

        # Show URLs based on profile
        if [ "$PROFILE" = "dev" ]; then
            print_color "$GREEN" "✅ Development server: http://localhost:3000"
        elif [ "$PROFILE" = "preview" ]; then
            print_color "$GREEN" "✅ Preview server: http://localhost:9150"
        else
            print_color "$GREEN" "✅ Production server: http://localhost:9000"
        fi
        ;;

    down|stop)
        print_color "$YELLOW" "🛑 Stopping services..."
        $COMPOSE_CMD $COMPOSE_ARGS down
        print_color "$GREEN" "✅ Services stopped!"
        ;;

    restart)
        print_color "$YELLOW" "🔄 Restarting services..."
        $COMPOSE_CMD $COMPOSE_ARGS restart $SERVICE
        print_color "$GREEN" "✅ Services restarted!"
        ;;

    logs)
        print_color "$BLUE" "📋 Showing logs (Ctrl+C to exit)..."
        $COMPOSE_CMD $COMPOSE_ARGS logs -f $SERVICE
        ;;

    status|ps)
        print_color "$BLUE" "📊 Container status:"
        $COMPOSE_CMD $COMPOSE_ARGS ps
        echo ""
        print_color "$BLUE" "🏥 Health status:"
        for container in $($COMPOSE_CMD $COMPOSE_ARGS ps -q); do
            name=$($COMPOSE_CMD ps | grep $container | awk '{print $1}')
            health=$(docker inspect --format='{{.State.Health.Status}}' $container 2>/dev/null || echo "none")
            if [ "$health" = "healthy" ]; then
                print_color "$GREEN" "  $name: healthy ✅"
            elif [ "$health" = "unhealthy" ]; then
                print_color "$RED" "  $name: unhealthy ❌"
            else
                print_color "$YELLOW" "  $name: no health check"
            fi
        done
        ;;

    clean)
        print_color "$YELLOW" "🧹 Cleaning up containers and volumes..."
        $COMPOSE_CMD $COMPOSE_ARGS down -v
        print_color "$GREEN" "✅ Cleanup complete!"
        ;;

    prune)
        print_color "$YELLOW" "🗑️ Pruning unused Docker resources..."
        docker system prune -af --volumes
        print_color "$GREEN" "✅ Prune complete!"
        ;;

    shell)
        if [ "$PROFILE" = "dev" ]; then
            CONTAINER="mawidi-nextjs-dev"
        elif [ "$PROFILE" = "preview" ]; then
            CONTAINER="mawidi-nextjs-preview"
        else
            CONTAINER="mawidi-nextjs-prod"
        fi

        print_color "$BLUE" "🐚 Opening shell in $CONTAINER..."
        docker exec -it $CONTAINER /bin/sh
        ;;

    test)
        print_color "$BLUE" "🧪 Running tests..."
        if [ "$PROFILE" = "dev" ]; then
            docker exec mawidi-nextjs-dev npm test
        else
            print_color "$RED" "❌ Tests can only run in development profile"
            exit 1
        fi
        ;;

    deploy)
        print_color "$BLUE" "🚀 Deploying to production..."

        # Build production image
        print_color "$BLUE" "Building production image..."
        $COMPOSE_CMD build --no-cache mawidi-app

        # Stop existing container
        print_color "$YELLOW" "Stopping existing container..."
        $COMPOSE_CMD stop mawidi-app

        # Backup existing container (optional)
        if docker ps -a | grep -q mawidi-nextjs-prod; then
            print_color "$YELLOW" "Creating backup..."
            docker commit mawidi-nextjs-prod mawidi-nextjs:backup-$(date +%Y%m%d-%H%M%S)
        fi

        # Remove old container
        $COMPOSE_CMD rm -f mawidi-app

        # Start new container
        print_color "$GREEN" "Starting new container..."
        $COMPOSE_CMD up -d mawidi-app

        # Wait for health check
        print_color "$BLUE" "Waiting for health check..."
        sleep 10

        # Check health
        if docker inspect --format='{{.State.Health.Status}}' mawidi-nextjs-prod | grep -q healthy; then
            print_color "$GREEN" "✅ Deployment successful!"
            print_color "$GREEN" "🌐 Production server: http://localhost:9000"
        else
            print_color "$RED" "❌ Deployment failed - check logs"
            $COMPOSE_CMD logs --tail=50 mawidi-app
            exit 1
        fi
        ;;

    help|--help|-h)
        show_usage
        ;;

    *)
        print_color "$RED" "❌ Unknown command: $COMMAND"
        echo ""
        show_usage
        exit 1
        ;;
esac
