#!/bin/bash
# Production Docker Compose Management Script
# Manages Docker containers in production macOS build

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
APP_SUPPORT="$HOME/Library/Application Support/Archipelago"
COMPOSE_FILE="$SCRIPT_DIR/docker-compose.yml"

# Ensure data directory exists
mkdir -p "$APP_SUPPORT/data"
mkdir -p "$APP_SUPPORT/logs"

echo "🐳 Archipelago Docker Manager"
echo ""

# Check if Docker is available
if ! command -v docker >/dev/null 2>&1; then
    echo "❌ Docker not found!"
    echo "   Install Docker Desktop: https://www.docker.com/products/docker-desktop"
    exit 1
fi

if ! docker info >/dev/null 2>&1; then
    echo "❌ Docker daemon not running!"
    echo "   Please start Docker Desktop"
    exit 1
fi

COMMAND="${1:-start}"

case "$COMMAND" in
    start)
        echo "🚀 Starting containers..."
        docker-compose -f "$COMPOSE_FILE" up -d
        echo ""
        echo "✅ Containers started!"
        echo "   View status: docker-compose -f \"$COMPOSE_FILE\" ps"
        ;;
    
    stop)
        echo "🛑 Stopping containers..."
        docker-compose -f "$COMPOSE_FILE" down
        echo "✅ Containers stopped!"
        ;;
    
    restart)
        echo "🔄 Restarting containers..."
        docker-compose -f "$COMPOSE_FILE" restart
        echo "✅ Containers restarted!"
        ;;
    
    status)
        docker-compose -f "$COMPOSE_FILE" ps
        ;;
    
    logs)
        SERVICE="${2:-}"
        if [ -z "$SERVICE" ]; then
            docker-compose -f "$COMPOSE_FILE" logs --tail=100
        else
            docker-compose -f "$COMPOSE_FILE" logs -f "$SERVICE"
        fi
        ;;
    
    clean)
        echo "🧹 Cleaning up containers and volumes..."
        docker-compose -f "$COMPOSE_FILE" down -v
        echo "✅ Cleanup complete!"
        ;;
    
    *)
        echo "Usage: $0 {start|stop|restart|status|logs|clean}"
        echo ""
        echo "Commands:"
        echo "  start   - Start all containers"
        echo "  stop    - Stop all containers"
        echo "  restart - Restart all containers"
        echo "  status  - Show container status"
        echo "  logs    - Show container logs (optional: service name)"
        echo "  clean   - Stop containers and remove volumes"
        exit 1
        ;;
esac
