#!/bin/bash

# Start script for Docker local development environment
# This script starts all Docker services for the application

set -e  # Exit on any error

# Simple Docker Compose setup for local development

# 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 "🚀 Starting Docker services for local development..."

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

# Check if .env.local exists
if [ ! -f ".env.local" ]; then
    print_error ".env.local file not found!"
    echo "Please run './infrastructure/setup_env.sh' first to set up the environment."
    exit 1
fi

# Load environment variables from .env.local
print_status "Loading environment variables from .env.local..."
set -a  # automatically export all variables
source .env.local
set +a  # stop automatically exporting

# Check if docker-compose.yml exists
if [ ! -f "infrastructure/docker/docker-compose.yml" ]; then
    print_error "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
BUILD_FLAG=""
DETACH_FLAG=""
SERVICES=""

while [[ $# -gt 0 ]]; do
    case $1 in
        --build|-b)
            BUILD_FLAG="--build"
            shift
            ;;
        --detach|-d)
            DETACH_FLAG="-d"
            shift
            ;;
        --db-only)
            SERVICES="postgres mailpit"
            shift
            ;;
        --minio-only)
            SERVICES="minio minio-setup"
            shift
            ;;
        --mailpit-only)
            SERVICES="mailpit"
            shift
            ;;
        --help|-h)
            echo "Usage: $0 [OPTIONS]"
            echo ""
            echo "Options:"
            echo "  --build, -b     Force rebuild of Docker images"
            echo "  --detach, -d    Run containers in background (detached mode)"
            echo "  --db-only       Start only database and email services (for local dev)"
            echo "  --minio-only    Start only MinIO file storage service"
            echo "  --mailpit-only  Start only Mailpit email testing service"
            echo "  --help, -h      Show this help message"
            echo ""
            echo "Examples:"
            echo "  $0                    # Start all services in foreground"
            echo "  $0 --build --detach  # Rebuild and start in background"
            echo "  $0 --db-only -d      # Start only DB services in background"
            echo "  $0 --minio-only -d   # Start only MinIO in background"
            echo "  $0 --mailpit-only -d # Start only Mailpit in background"
            exit 0
            ;;
        *)
            print_error "Unknown option: $1"
            echo "Use --help for usage information."
            exit 1
            ;;
    esac
done

# Stop any running containers first (to avoid conflicts)
print_status "Stopping any existing containers..."
docker compose --env-file .env.local -f infrastructure/docker/docker-compose.yml down 2>/dev/null || true

# Check for port conflicts
check_port() {
    local port=$1
    local service=$2
    if lsof -i :$port &> /dev/null; then
        print_warning "Port $port is already in use (needed for $service)"
        echo "You may need to stop the conflicting service or change the port in docker-compose.yml"
    fi
}

if [ -z "$SERVICES" ]; then
    check_port 3000 "Next.js app"
fi
check_port 5432 "PostgreSQL"
check_port 9000 "MinIO API"
check_port 9001 "MinIO Console"
check_port 8025 "Mailpit"

# Start the services
if [ -n "$SERVICES" ]; then
    if [[ "$SERVICES" == *"minio"* ]]; then
        print_status "Starting MinIO file storage service only..."
        print_status "MinIO Console: http://localhost:9001"
        print_status "MinIO API: http://localhost:9000"
    elif [[ "$SERVICES" == *"mailpit"* ]] && [[ "$SERVICES" != *"postgres"* ]]; then
        print_status "Starting Mailpit email testing service only..."
        print_status "Mailpit Web Interface: http://localhost:8025"
    elif [[ "$SERVICES" == *"postgres"* ]]; then
        print_status "Starting database and email services only..."
        print_status "You can run 'npm run dev' separately for faster development"
    fi
    CMD="docker compose --env-file .env.local -f infrastructure/docker/docker-compose.yml up $DETACH_FLAG $BUILD_FLAG $SERVICES"
else
    print_status "Starting all services (PostgreSQL + Next.js + MinIO + Mailpit)..."
    CMD="docker compose --env-file .env.local -f infrastructure/docker/docker-compose.yml up $DETACH_FLAG $BUILD_FLAG"
fi

print_status "Running: $CMD"
echo ""

# Execute the docker compose command
if eval $CMD; then
    echo ""
    print_success "Services started successfully! 🎉"
    echo ""
    echo "📋 Access your services:"
    
    if [ -z "$SERVICES" ]; then
        echo "  🌐 Application: http://localhost:3000"
        echo "  📧 Mailpit (Email Testing): http://localhost:8025"
        echo "  🗄️  PostgreSQL: localhost:5432"
        echo "  📁 MinIO Console: http://localhost:9001"
        echo "  📁 MinIO API: http://localhost:9000"
    elif [[ "$SERVICES" == *"minio"* ]]; then
        echo "  📁 MinIO Console: http://localhost:9001"
        echo "  📁 MinIO API: http://localhost:9000"
    elif [[ "$SERVICES" == *"mailpit"* ]] && [[ "$SERVICES" != *"postgres"* ]]; then
        echo "  📧 Mailpit (Email Testing): http://localhost:8025"
    elif [[ "$SERVICES" == *"postgres"* ]]; then
        echo "  🌐 Application: Run 'npm run dev' in another terminal"
        echo "  📧 Mailpit (Email Testing): http://localhost:8025"
        echo "  🗄️  PostgreSQL: localhost:5432"
    fi
    echo ""
    echo "📊 Useful commands:"
    echo "  docker compose --env-file .env.local -f infrastructure/docker/docker-compose.yml logs -f app      # View app logs"
    echo "  docker compose --env-file .env.local -f infrastructure/docker/docker-compose.yml logs -f postgres # View database logs"
    echo "  docker compose --env-file .env.local -f infrastructure/docker/docker-compose.yml ps               # Check service status"
    echo "  ./infrastructure/stop_docker.sh                # Stop all services"
    echo ""
    
    if [ -z "$DETACH_FLAG" ]; then
        print_status "Services are running in foreground. Press Ctrl+C to stop."
    else
        print_status "Services are running in background."
        echo "Use 'docker compose --env-file .env.local -f infrastructure/docker/docker-compose.yml logs -f' to view logs or './infrastructure/stop_docker.sh' to stop services."
    fi
else
    print_error "Failed to start services!"
    echo ""
    echo "🔧 Troubleshooting:"
    echo "  1. Check if Docker is running: docker info"
    echo "  2. Check for port conflicts: lsof -i :3000 -i :5432 -i :8025 -i :9000 -i :9001"
    echo "  3. View detailed logs: docker compose --env-file .env.local -f infrastructure/docker/docker-compose.yml logs"
    echo "  4. Try rebuilding: ./infrastructure/start_docker.sh --build"
    echo "  5. Reset everything: docker compose --env-file .env.local -f infrastructure/docker/docker-compose.yml down -v && ./infrastructure/start_docker.sh --build"
    exit 1
fi
