#!/bin/bash
# Deploy all components in parallel where possible
# Full parallel deployment script

set -e

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

echo "=== Sankofa Phoenix - Parallel Deployment ==="
echo ""

# Color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Function to run command and capture output
run_parallel() {
    local name=$1
    shift
    local cmd="$@"
    
    echo -e "${YELLOW}[$name]${NC} Starting..."
    if eval "$cmd" > "/tmp/deploy_${name}.log" 2>&1; then
        echo -e "${GREEN}[$name]${NC} ✓ Completed"
        return 0
    else
        echo -e "${RED}[$name]${NC} ✗ Failed (check /tmp/deploy_${name}.log)"
        return 1
    fi
}

# Check prerequisites
echo "Checking prerequisites..."
MISSING_DEPS=()

if ! command -v kubectl &> /dev/null; then MISSING_DEPS+=("kubectl"); fi
if ! command -v go &> /dev/null; then MISSING_DEPS+=("go"); fi
if ! command -v docker &> /dev/null; then 
    echo "⚠ Docker not found, will skip Docker builds"
fi

if [ ${#MISSING_DEPS[@]} -gt 0 ]; then
    echo "✗ Missing dependencies: ${MISSING_DEPS[*]}"
    exit 1
fi

echo "✓ All prerequisites met"
echo ""

# Step 1: Build provider (can run independently)
echo "=== Step 1: Building Crossplane Provider ==="
"$SCRIPT_DIR/build-crossplane-provider.sh" &
BUILD_PID=$!

# Step 2: Deploy Keycloak (can run independently)
echo "=== Step 2: Deploying Keycloak ==="
"$SCRIPT_DIR/deploy-keycloak.sh" &
KEYCLOAK_PID=$!

# Wait for builds to complete
echo ""
echo "Waiting for parallel tasks to complete..."
wait $BUILD_PID && echo "✓ Provider build complete" || echo "✗ Provider build failed"
wait $KEYCLOAK_PID && echo "✓ Keycloak deployment complete" || echo "✗ Keycloak deployment failed"

# Step 3: Deploy provider (requires build to complete)
echo ""
echo "=== Step 3: Deploying Crossplane Provider ==="
"$SCRIPT_DIR/deploy-crossplane-provider.sh"

# Step 4: Test connectivity
echo ""
echo "=== Step 4: Testing Proxmox Connectivity ==="
if "$SCRIPT_DIR/test-proxmox-connectivity.sh"; then
    echo "✓ Proxmox connectivity verified"
else
    echo "⚠ Proxmox connectivity test failed (may be expected if instances are not reachable)"
fi

echo ""
echo "=== Deployment Summary ==="
echo ""
echo "Keycloak:"
kubectl get pods -n keycloak 2>/dev/null || echo "  Not deployed"

echo ""
echo "Crossplane Provider:"
kubectl get providers 2>/dev/null || echo "  Not deployed"
kubectl get pods -n crossplane-system -l app=crossplane-provider-proxmox 2>/dev/null || echo "  Not deployed"

echo ""
echo "=== Next Steps ==="
echo "1. Configure Keycloak clients (see deploy-keycloak.sh output)"
echo "2. Create ProviderConfig with Proxmox credentials"
echo "3. Test VM provisioning via Crossplane"
echo ""
echo "For detailed logs, check: /tmp/deploy_*.log"

