#!/usr/bin/env bash
# Phase 2: Deploy Kubernetes Resources

set -e

cd "$(dirname "$0")/../.."

# Color codes

echo "==================================================================="
echo "  PHASE 2: KUBERNETES RESOURCES DEPLOYMENT"
echo "==================================================================="

# Check kubectl access
if ! kubectl cluster-info &> /dev/null; then
    log_error "❌ Kubernetes cluster not accessible"
    echo "  Configure with: az aks get-credentials --resource-group <rg> --name <cluster>"
    exit 1
fi

CLUSTER=$(kubectl config current-context 2>/dev/null || echo "Unknown")
log_success "✅ Connected to cluster: $CLUSTER"

# Create namespace
log_info "Creating namespace..."
if kubectl get namespace besu-network &> /dev/null; then
    log_success "✅ Namespace 'besu-network' already exists"
else
    kubectl create namespace besu-network
    log_success "✅ Namespace 'besu-network' created"
fi

# Apply base resources
log_info "Applying base Kubernetes resources..."
if [ -d "k8s/base" ]; then
    kubectl apply -k k8s/base
    log_success "✅ Base resources applied"
else
    log_warn "⚠️  k8s/base directory not found"
fi

# Wait for resources
log_info "Waiting for resources to be ready..."
kubectl wait --for=condition=ready pod --all -n besu-network --timeout=60s 2>/dev/null || echo "No pods to wait for yet"

log_success "✅ Phase 2 complete!"
echo "Next: Deploy Besu network components"
