#!/usr/bin/env bash
# Complete All Next Steps - Chain-138 and Cloud for Sovereignty

set -e

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

# Color codes

echo "==================================================================="
echo "  COMPLETING ALL NEXT STEPS"
echo "==================================================================="

# Step 1: Chain-138 Infrastructure
log_info "Step 1: Chain-138 Infrastructure Deployment"

cd terraform

# Check if AKS cluster exists
RG_NAME="az-p-we-rg-comp-001"
CLUSTER_NAME="az-p-we-aks-main"

if az aks show --resource-group "$RG_NAME" --name "$CLUSTER_NAME" &> /dev/null 2>&1; then
    log_success "✅ AKS Cluster exists"
    
    # Get kubeconfig
    az aks get-credentials --resource-group "$RG_NAME" --name "$CLUSTER_NAME" --overwrite-existing
    
    if kubectl cluster-info &> /dev/null 2>&1; then
        log_success "✅ Kubernetes accessible"
        
        # Deploy Kubernetes resources
        kubectl create namespace besu-network --dry-run=client -o yaml | kubectl apply -f -
        kubectl apply -k ../k8s/base 2>&1 | tail -10
        
        # Deploy Besu network
        if [ -f ../helm/besu-network/values-validators.yaml ]; then
            if ! helm list -n besu-network 2>/dev/null | grep -q besu-validators; then
                helm install besu-validators ../helm/besu-network \
                    -f ../helm/besu-network/values-validators.yaml \
                    -n besu-network 2>&1 | tail -5
            fi
        fi
    fi
else
    log_warn "⚠️  AKS Cluster not found"
    echo "   Deploying via Terraform..."
    terraform apply -auto-approve tfplan 2>&1 | tail -20
fi

cd ..

# Step 2: Cloud for Sovereignty Phase 2 (Primary Region Only)
log_info "Step 2: Cloud for Sovereignty - AKS Clusters (Primary Region)"

cd terraform/well-architected/cloud-sovereignty

# Deploy AKS in West Europe only (primary region)
if [ -f terraform.tfvars ]; then
    # Temporarily set to deploy only West Europe
    sed -i 's/enable_all_regions = true/enable_all_regions = false/' terraform.tfvars
    echo 'selected_regions = ["westeurope"]' >> terraform.tfvars
    
    terraform plan -out=tfplan-primary 2>&1 | tail -20
    
    read -p "Deploy AKS cluster in West Europe? (y/N): " -n 1 -r
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        terraform apply -auto-approve tfplan-primary 2>&1 | tail -20
    fi
fi

cd ../../..

# Step 3: Verification
log_info "Step 3: Running Verification"

./scripts/deployment/verify-chain138-complete.sh 2>&1 | tail -30

log_success "✅ All next steps complete!"
