#!/bin/bash
# Development Container Environment Setup
# Checks container runtime availability and provides helper commands

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

echo "🐳 Archipelago Development Container Environment"
echo ""

# Check for Podman
PODMAN_AVAILABLE=false
if command -v podman >/dev/null 2>&1; then
    PODMAN_VERSION=$(podman --version)
    echo "✅ Podman found: $PODMAN_VERSION"
    if podman info >/dev/null 2>&1; then
        PODMAN_AVAILABLE=true
        echo "   Podman daemon is running"
    else
        echo "   ⚠️  Podman daemon not running"
        if [[ "$OSTYPE" == "darwin"* ]]; then
            echo "   Start with: podman machine start"
        fi
    fi
else
    echo "❌ Podman not found"
fi

# Check for Docker
DOCKER_AVAILABLE=false
if command -v docker >/dev/null 2>&1; then
    DOCKER_VERSION=$(docker --version)
    echo "✅ Docker found: $DOCKER_VERSION"
    if docker info >/dev/null 2>&1; then
        DOCKER_AVAILABLE=true
        echo "   Docker daemon is running"
    else
        echo "   ⚠️  Docker daemon not running"
        echo "   Start Docker Desktop or: sudo systemctl start docker"
    fi
else
    echo "❌ Docker not found"
fi

echo ""

# Determine runtime
RUNTIME="auto"
if [ "$PODMAN_AVAILABLE" = true ]; then
    RUNTIME="podman"
    echo "🎯 Using Podman (preferred)"
elif [ "$DOCKER_AVAILABLE" = true ]; then
    RUNTIME="docker"
    echo "🎯 Using Docker (fallback)"
else
    echo "❌ No container runtime available!"
    echo "   Install Podman: https://podman.io/getting-started/installation"
    echo "   Or install Docker: https://docs.docker.com/get-docker/"
    exit 1
fi

echo ""
echo "📋 Helper Commands:"
echo ""
echo "List containers:"
echo "  $RUNTIME ps -a"
echo ""
echo "View container logs:"
echo "  $RUNTIME logs <container-name>"
echo ""
echo "Stop all archipelago containers:"
echo "  $RUNTIME ps -a --filter 'name=archipelago-' --format '{{.Names}}' | xargs -r $RUNTIME stop"
echo ""
echo "Remove all archipelago containers:"
echo "  $RUNTIME ps -a --filter 'name=archipelago-' --format '{{.Names}}' | xargs -r $RUNTIME rm -f"
echo ""
echo "Clean up dev data:"
echo "  rm -rf /tmp/archipelago-dev"
echo ""
echo "Start backend with containers:"
echo "  cd $PROJECT_ROOT/core"
echo "  ARCHIPELAGO_DEV_MODE=true \\"
echo "  ARCHIPELAGO_CONTAINER_RUNTIME=$RUNTIME \\"
echo "  ARCHIPELAGO_PORT_OFFSET=10000 \\"
echo "  ARCHIPELAGO_BITCOIN_SIMULATION=mock \\"
echo "  cargo run --bin archipelago"
echo ""
