#!/usr/bin/env bash
# Phase 3: Deploy Besu Network

set -e

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

# Color codes

echo "==================================================================="
echo "  PHASE 3: BESU NETWORK DEPLOYMENT"
echo "==================================================================="

# Check kubectl access
if ! kubectl cluster-info &> /dev/null; then
    log_error "❌ Kubernetes cluster not accessible"
    exit 1
fi

# Check namespace
if ! kubectl get namespace besu-network &> /dev/null; then
    log_error "❌ Namespace 'besu-network' not found"
    echo "  Run Phase 2 first: ./scripts/deployment/deploy-infrastructure-phase2.sh"
    exit 1
fi

# Deploy validators
log_info "Deploying Besu validators..."
if [ -f "helm/besu-network/values-validators.yaml" ]; then
    if helm list -n besu-network | grep -q besu-validators; then
        log_success "✅ Validators already deployed"
    else
        helm install besu-validators ./helm/besu-network \
            -f helm/besu-network/values-validators.yaml \
            -n besu-network
        log_success "✅ Validators deployed"
    fi
else
    log_warn "⚠️  Validators values file not found"
fi

# Deploy sentries
log_info "Deploying Besu sentries..."
if [ -f "helm/besu-network/values-sentries.yaml" ]; then
    if helm list -n besu-network | grep -q besu-sentries; then
        log_success "✅ Sentries already deployed"
    else
        helm install besu-sentries ./helm/besu-network \
            -f helm/besu-network/values-sentries.yaml \
            -n besu-network
        log_success "✅ Sentries deployed"
    fi
else
    log_warn "⚠️  Sentries values file not found"
fi

# Deploy RPC nodes
log_info "Deploying Besu RPC nodes..."
if [ -f "helm/besu-network/values-rpc.yaml" ]; then
    if helm list -n besu-network | grep -q besu-rpc; then
        log_success "✅ RPC nodes already deployed"
    else
        helm install besu-rpc ./helm/besu-network \
            -f helm/besu-network/values-rpc.yaml \
            -n besu-network
        log_success "✅ RPC nodes deployed"
    fi
else
    log_warn "⚠️  RPC values file not found"
fi

# Wait for pods
log_info "Waiting for pods to be ready..."
kubectl wait --for=condition=ready pod -l app=besu-validator -n besu-network --timeout=300s 2>/dev/null || echo "Validators not ready yet"
kubectl wait --for=condition=ready pod -l app=besu-sentry -n besu-network --timeout=300s 2>/dev/null || echo "Sentries not ready yet"
kubectl wait --for=condition=ready pod -l app=besu-rpc -n besu-network --timeout=300s 2>/dev/null || echo "RPC nodes not ready yet"

# Show status
log_info "Pod Status:"
kubectl get pods -n besu-network

log_success "✅ Phase 3 complete!"
echo "Next: Deploy monitoring and explorer"
