#!/usr/bin/env bash
# Deploy Cloud for Sovereignty Landing Zone Foundation

set -e

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

# Color codes

echo "==================================================================="
echo "  CLOUD FOR SOVEREIGNTY LANDING ZONE - FOUNDATION DEPLOYMENT"
echo "==================================================================="

# Load environment variables
if [ -f .env ]; then
    source .env 2>/dev/null || true
fi

# Set subscription
if [ -n "$AZURE_SUBSCRIPTION_ID" ]; then
    az account set --subscription "$AZURE_SUBSCRIPTION_ID"
    log_success "✅ Using subscription: $AZURE_SUBSCRIPTION_ID"
else
    log_error "❌ AZURE_SUBSCRIPTION_ID not set"
    exit 1
fi

cd terraform/well-architected/cloud-sovereignty

# Check if terraform.tfvars exists
if [ ! -f "terraform.tfvars" ]; then
    if [ -f "terraform.tfvars.example" ]; then
        log_warn "⚠️  Creating terraform.tfvars from example..."
        cp terraform.tfvars.example terraform.tfvars
        log_warn "⚠️  Please review terraform.tfvars before proceeding"
    else
        log_error "❌ terraform.tfvars.example not found"
        exit 1
    fi
fi

# Initialize Terraform
log_info "Initializing Terraform..."
terraform init

# Validate
log_info "Validating configuration..."
terraform validate

# Plan
log_info "Creating deployment plan..."
terraform plan -out=tfplan

log_warn "⚠️  REVIEW THE PLAN ABOVE"
echo "This will create:"
echo "  • Resource Groups in all selected regions"
echo "  • Virtual Networks"
echo "  • Key Vaults"
echo "  • Log Analytics Workspaces"
echo "  • Storage Accounts"
read -p "Apply Terraform plan? (y/N): " -n 1 -r

if [[ $REPLY =~ ^[Yy]$ ]]; then
    log_info "Applying Terraform plan..."
    terraform apply tfplan
    
    if [ $? -eq 0 ]; then
        log_success "✅ Foundation deployment complete!"
        echo "Next steps:"
        echo "  1. Review deployed resources"
        echo "  2. Configure AKS clusters (set deploy_aks_clusters = true)"
        echo "  3. Deploy Besu network (set deploy_besu_network = true)"
    else
        log_error "❌ Deployment failed"
        exit 1
    fi
else
    log_warn "⚠️  Deployment cancelled"
fi

cd ../../..
