#!/bin/bash
# Test a prepackaged container
# Usage: ./test-container.sh <app-id> <package-dir>

set -e

if [ $# -lt 2 ]; then
    echo "Usage: $0 <app-id> <package-dir>"
    echo ""
    echo "Example:"
    echo "  $0 k484 ./k484-package"
    exit 1
fi

APP_ID="$1"
PACKAGE_DIR="$2"

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

echo "🧪 Testing container: $APP_ID"
echo "📦 Package directory: $PACKAGE_DIR"
echo ""

# Check if package directory exists
if [ ! -d "$PACKAGE_DIR" ]; then
    echo "❌ Package directory not found: $PACKAGE_DIR"
    exit 1
fi

# Determine container runtime
RUNTIME="auto"
if command -v podman >/dev/null 2>&1 && podman info >/dev/null 2>&1; then
    RUNTIME="podman"
elif command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
    RUNTIME="docker"
else
    echo "❌ No container runtime available!"
    exit 1
fi

echo "🐳 Using runtime: $RUNTIME"
echo ""

# Check for Dockerfile
if [ ! -f "$PACKAGE_DIR/Dockerfile" ]; then
    echo "❌ Dockerfile not found in $PACKAGE_DIR"
    exit 1
fi

# Build container image
IMAGE_NAME="${APP_ID}:dev"
echo "🔨 Building container image: $IMAGE_NAME"
$RUNTIME build -t "$IMAGE_NAME" "$PACKAGE_DIR" || {
    echo "❌ Failed to build container image"
    exit 1
}
echo "✅ Image built successfully"
echo ""

# Create test manifest
MANIFEST_DIR="$PROJECT_ROOT/apps/$APP_ID"
mkdir -p "$MANIFEST_DIR"

MANIFEST_FILE="$MANIFEST_DIR/manifest.yml"
cat > "$MANIFEST_FILE" <<EOF
app:
  id: $APP_ID
  name: $(echo "$APP_ID" | tr '[:lower:]' '[:upper:]')
  version: dev
  description: Development test container for $APP_ID
  
  container:
    image: $IMAGE_NAME
    pull_policy: never  # Use local image
    
  resources:
    cpu_limit: 1
    memory_limit: 512Mi
    
  ports:
    - host: 8080
      container: 8080
      protocol: tcp
      
  volumes:
    - type: bind
      source: /tmp/archipelago-dev/$APP_ID
      target: /data
      options: [rw]
EOF

echo "📝 Created test manifest: $MANIFEST_FILE"
echo ""

# Check if backend is running
BACKEND_URL="${BACKEND_URL:-http://localhost:5959}"
if ! curl -s "$BACKEND_URL/health" >/dev/null 2>&1; then
    echo "⚠️  Backend not running at $BACKEND_URL"
    echo "   Start backend first:"
    echo "   cd $PROJECT_ROOT/core"
    echo "   ARCHIPELAGO_DEV_MODE=true cargo run --bin archipelago"
    echo ""
    echo "   Or install via RPC manually:"
    echo "   curl -X POST $BACKEND_URL/rpc/v1 \\"
    echo "     -H 'Content-Type: application/json' \\"
    echo "     -d '{\"method\":\"container-install\",\"params\":{\"manifest_path\":\"$MANIFEST_FILE\"}}'"
    exit 0
fi

# Install via RPC
echo "📥 Installing container via RPC..."
RESPONSE=$(curl -s -X POST "$BACKEND_URL/rpc/v1" \
    -H "Content-Type: application/json" \
    -d "{\"method\":\"container-install\",\"params\":{\"manifest_path\":\"$MANIFEST_FILE\"}}")

if echo "$RESPONSE" | grep -q '"error"'; then
    echo "❌ Installation failed:"
    echo "$RESPONSE" | jq '.' 2>/dev/null || echo "$RESPONSE"
    exit 1
fi

CONTAINER_NAME=$(echo "$RESPONSE" | jq -r '.result' 2>/dev/null || echo "")
echo "✅ Container installed: $CONTAINER_NAME"
echo ""

# Start container
echo "🚀 Starting container..."
curl -s -X POST "$BACKEND_URL/rpc/v1" \
    -H "Content-Type: application/json" \
    -d "{\"method\":\"container-start\",\"params\":{\"app_id\":\"$APP_ID\"}}" >/dev/null

sleep 2

# Check status
echo "📊 Container status:"
STATUS=$(curl -s -X POST "$BACKEND_URL/rpc/v1" \
    -H "Content-Type: application/json" \
    -d "{\"method\":\"container-status\",\"params\":{\"app_id\":\"$APP_ID\"}}")

echo "$STATUS" | jq '.' 2>/dev/null || echo "$STATUS"
echo ""

# Get logs
echo "📋 Container logs (last 20 lines):"
LOGS=$(curl -s -X POST "$BACKEND_URL/rpc/v1" \
    -H "Content-Type: application/json" \
    -d "{\"method\":\"container-logs\",\"params\":{\"app_id\":\"$APP_ID\",\"lines\":20}}")

echo "$LOGS" | jq -r '.[]' 2>/dev/null || echo "$LOGS"
echo ""

echo "✅ Test complete!"
echo ""
echo "To clean up:"
echo "  curl -X POST $BACKEND_URL/rpc/v1 \\"
echo "    -H 'Content-Type: application/json' \\"
echo "    -d '{\"method\":\"container-remove\",\"params\":{\"app_id\":\"$APP_ID\"}}'"
echo "  $RUNTIME rmi $IMAGE_NAME"
