#!/usr/bin/env bash
# Fix Resource Group Naming Conventions

set -e

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

# Color codes

echo "==================================================================="
echo "  FIXING RESOURCE GROUP NAMING CONVENTIONS"
echo "==================================================================="

# Expected naming convention: {cloud}-{env}-{region}-rg-{type}-{instance}
# Example: az-p-we-rg-comp-001

EXPECTED_PATTERN="^az-[pdt]-[a-z]+-rg-(net|comp|stor|sec|mon|tfstate)-[0-9]{3}$"

log_info "Current Resource Groups:"

az group list --query "[].name" -o tsv | while read -r rg; do
    if [[ "$rg" =~ $EXPECTED_PATTERN ]]; then
        log_success "✅ $rg (correct)"
    else
        log_warn "⚠️  $rg (needs review)"
    fi
done

log_info "Checking Terraform configuration..."

# Check terraform.tfvars
if [ -f terraform/terraform.tfvars ]; then
    RG_NAME=$(grep -E "^resource_group_name" terraform/terraform.tfvars | head -1 | sed 's/.*= *"\([^"]*\)".*/\1/' | tr -d ' ')
    
    if [ -n "$RG_NAME" ] && [ "$RG_NAME" != "" ]; then
        if [[ "$RG_NAME" =~ $EXPECTED_PATTERN ]]; then
            log_success "✅ terraform.tfvars resource_group_name: $RG_NAME"
        else
            log_warn "⚠️  terraform.tfvars resource_group_name: $RG_NAME"
            echo "  Expected pattern: az-p-we-rg-comp-001"
        fi
    else
        log_success "✅ terraform.tfvars uses default naming (empty)"
    fi
fi

log_info "Standard naming convention:"
echo "  Format: {cloud}-{env}-{region}-rg-{type}-{instance}"
echo "  Example: az-p-we-rg-comp-001"
echo "  Where:"
echo "    cloud = az (Azure)"
echo "    env   = p (prod), d (dev), t (test), s (staging)"
echo "    region = we (westeurope), ne (northeurope), etc."
echo "    type  = comp (compute), net (network), stor (storage), sec (security), mon (monitoring), tfstate (terraform state)"
echo "    instance = 001, 002, etc."
