#!/bin/bash

# Stop script for Docker local development environment
# This script stops all Docker services and optionally cleans up

set -e  # Exit on any error

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

# Function to print colored output
print_status() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

echo "🛑 Stopping Docker services..."

# Load environment variables from .env.local if it exists
if [ -f ".env.local" ]; then
    print_status "Loading environment variables from .env.local..."
    set -a  # automatically export all variables
    source .env.local
    set +a  # stop automatically exporting
fi

# Check if Docker is running
if ! docker info &> /dev/null; then
    print_error "Docker daemon is not running."
    exit 1
fi

# Check if docker-compose.yml exists
if [ ! -f "infrastructure/docker/docker-compose.yml" ]; then
    print_error "infrastructure/docker/docker-compose.yml not found!"
    echo "Make sure you're running this script from the project root directory."
    exit 1
fi

# Parse command line arguments
REMOVE_VOLUMES=""
REMOVE_IMAGES=""
FORCE_CLEANUP=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --volumes|-v)
            REMOVE_VOLUMES="-v"
            shift
            ;;
        --images|-i)
            REMOVE_IMAGES="true"
            shift
            ;;
        --clean|-c)
            REMOVE_VOLUMES="-v"
            REMOVE_IMAGES="true"
            FORCE_CLEANUP="true"
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --volumes, -v   Remove volumes (⚠️  deletes all database data)"
            echo "  --images, -i    Remove built images to free up space"
            echo "  --clean, -c     Complete cleanup (volumes + images + containers)"
            echo "  --help, -h      Show this help message"
            echo ""
            echo "Examples:"
            echo "  $0              # Stop services, keep data"
            echo "  $0 --volumes    # Stop services and delete database data"
            echo "  $0 --clean      # Complete cleanup (removes everything)"
            echo ""
            echo "⚠️  Warning: Using --volumes or --clean will delete all database data!"
            exit 0
            ;;
        *)
            print_error "Unknown option: $1"
            echo "Use --help for usage information."
            exit 1
            ;;
    esac
done

# Warn about data loss
if [ -n "$REMOVE_VOLUMES" ]; then
    print_warning "⚠️  This will delete all database data!"
    if [ -z "$FORCE_CLEANUP" ]; then
        read -p "Are you sure you want to continue? (y/N): " -n 1 -r
        echo
        if [[ ! $REPLY =~ ^[Yy]$ ]]; then
            print_status "Operation cancelled."
            exit 0
        fi
    fi
fi

# Stop and remove containers
print_status "Stopping Docker services..."
if docker compose --env-file .env.local -f infrastructure/docker/docker-compose.yml down $REMOVE_VOLUMES; then
    print_success "Services stopped successfully"
else
    print_error "Failed to stop some services"
    # Continue with cleanup even if some services failed to stop
fi

# Remove images if requested
if [ -n "$REMOVE_IMAGES" ]; then
    print_status "Removing built images..."
    
    # Get the project name for image cleanup
    PROJECT_NAME=$(basename "$PWD" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9]//g')
    
    # Remove project-specific images
    if docker images | grep -q "$PROJECT_NAME"; then
        docker images | grep "$PROJECT_NAME" | awk '{print $3}' | xargs -r docker rmi -f 2>/dev/null || true
        print_success "Project images removed"
    fi
    
    # Remove dangling images
    if docker images -f "dangling=true" -q | grep -q .; then
        docker images -f "dangling=true" -q | xargs -r docker rmi 2>/dev/null || true
        print_success "Dangling images cleaned up"
    fi
fi

# Additional cleanup if requested
if [ -n "$FORCE_CLEANUP" ]; then
    print_status "Performing additional cleanup..."
    
    # Remove unused networks (but keep default ones)
    docker network prune -f 2>/dev/null || true
    
    # Remove build cache
    docker builder prune -f 2>/dev/null || true
    
    print_success "Additional cleanup completed"
fi

# Show current status
echo ""
print_status "Current Docker status:"
if docker compose --env-file .env.local -f infrastructure/docker/docker-compose.yml ps 2>/dev/null | grep -q "Up"; then
    print_warning "Some services are still running:"
    docker compose --env-file .env.local -f infrastructure/docker/docker-compose.yml ps
else
    print_success "All services are stopped"
fi

# Show disk space info
if [ -n "$REMOVE_IMAGES" ] || [ -n "$FORCE_CLEANUP" ]; then
    echo ""
    print_status "Docker disk usage:"
    docker system df 2>/dev/null || true
fi

echo ""
print_success "Stop operation completed! 🎉"
echo ""
echo "📋 Next steps:"
echo "  ./infrastructure/start_docker.sh       # Start services again"
echo "  ./infrastructure/setup_env.sh       # Re-setup environment if needed"
echo "  docker compose --env-file .env.local -f infrastructure/docker/docker-compose.yml ps       # Check service status"
echo "  docker system df        # Check Docker disk usage"

if [ -n "$REMOVE_VOLUMES" ]; then
    echo ""
    print_warning "Database data has been deleted. Next startup will create a fresh database."
fi
