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

set -e

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

# Color codes

echo "==================================================================="
echo "  CLOUD FOR SOVEREIGNTY LANDING ZONE - AUTOMATED 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

# Step 1: Initialize
log_info "Step 1: Initializing Terraform..."
terraform init

# Step 2: Validate
log_info "Step 2: Validating configuration..."
if terraform validate; then
    log_success "✅ Configuration valid"
else
    log_error "❌ Validation failed"
    exit 1
fi

# Step 3: Plan
log_info "Step 3: Creating deployment plan..."
terraform plan -out=tfplan > plan-output.txt 2>&1

PLAN_RESULT=$?

if [ $PLAN_RESULT -eq 0 ]; then
    log_success "✅ Plan created successfully"
    
    # Show summary
    echo "Plan Summary:"
    grep -E "(Plan:|to add|to change|to destroy)" plan-output.txt | head -5
    
    # Count resources
    ADD_COUNT=$(grep -oP '\d+(?= to add)' plan-output.txt | head -1 || echo "0")
    CHANGE_COUNT=$(grep -oP '\d+(?= to change)' plan-output.txt | head -1 || echo "0")
    
    echo "Resources to create: $ADD_COUNT"
    echo "Resources to modify: $CHANGE_COUNT"
    
    # Step 4: Apply (with confirmation)
    log_warn "⚠️  This will create resources across all configured regions"
    read -p "Apply Terraform plan? (y/N): " -n 1 -r
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        log_info "Step 4: Applying Terraform plan..."
        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
else
    log_error "❌ Plan creation failed"
    echo "Check plan-output.txt for details"
    exit 1
fi

cd ../../..
