#!/usr/bin/env bash
# Apply Cloud for Sovereignty Landing Zone Deployment

set -e

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

# Color codes

echo "==================================================================="
echo "  APPLYING CLOUD FOR SOVEREIGNTY LANDING ZONE"
echo "==================================================================="

cd terraform/well-architected/cloud-sovereignty

# Check if plan exists
if [ ! -f "tfplan" ]; then
    log_error "❌ Terraform plan not found"
    echo "Run: terraform plan -out=tfplan"
    exit 1
fi

# Show plan summary
log_info "Plan Summary:"
grep -E "(Plan:|to add|to change|to destroy)" plan-output.txt 2>/dev/null | head -5 || echo "Review plan-output.txt"

log_warn "⚠️  This will create ~528 resources across 44 regions"
read -p "Apply Terraform plan? (y/N): " -n 1 -r

if [[ $REPLY =~ ^[Yy]$ ]]; then
    log_info "Applying Terraform plan..."
    echo "This may take 30-60 minutes..."
    
    terraform apply -auto-approve tfplan
    
    if [ $? -eq 0 ]; then
        log_success "✅ Deployment complete!"
        echo "Next steps:"
        echo "  1. Verify resources in Azure Portal"
        echo "  2. Review resource groups per region"
        echo "  3. Configure AKS clusters (Phase 2)"
        echo "  4. Deploy Besu network (Phase 3)"
    else
        log_error "❌ Deployment failed"
        exit 1
    fi
else
    log_warn "⚠️  Deployment cancelled"
    echo "Plan saved to: tfplan"
    echo "Apply later with: terraform apply tfplan"
fi

cd ../../..
