#!/usr/bin/env bash
# Standardize Resource Group Naming

set -e

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

# Color codes

echo "==================================================================="
echo "  STANDARDIZING RESOURCE GROUP NAMING"
echo "==================================================================="

# Load environment
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 "✅ Set subscription to: $AZURE_SUBSCRIPTION_ID"
else
    log_warn "⚠️  AZURE_SUBSCRIPTION_ID not set in .env"
fi

log_info "Current Resource Groups:"

# Get all resource groups
az group list --query "[].{Name:name, Location:location}" -o table

log_info "Expected Naming Convention:"
echo "  Format: az-{env}-{region}-rg-{type}-{instance}"
echo "  Example: az-p-we-rg-comp-001"

# Check terraform.tfvars
if [ -f terraform/terraform.tfvars ]; then
    log_info "Checking terraform.tfvars..."
    
    # Check if resource_group_name is set
    RG_NAME=$(grep -E "^resource_group_name" terraform/terraform.tfvars | head -1 | sed 's/.*= *"\([^"]*\)".*/\1/' | tr -d ' ')
    
    if [ -n "$RG_NAME" ] && [ "$RG_NAME" != "" ]; then
        echo "  Current: $RG_NAME"
        
        # Check if it follows convention
        if [[ "$RG_NAME" =~ ^az-[pdt]-[a-z]+-rg-(net|comp|stor|sec|mon|tfstate)-[0-9]{3}$ ]]; then
            echo -e "  ${GREEN}✅ Follows naming convention${NC}"
        else
            echo -e "  ${YELLOW}⚠️  Does not follow naming convention${NC}"
            echo "  Recommended: Leave empty to use default (az-p-we-rg-comp-001)"
        fi
    else
        echo -e "  ${GREEN}✅ Using default naming (empty)${NC}"
        echo "  Will use: az-p-we-rg-comp-001 (from locals.tf)"
    fi
fi

log_info "Recommendations:"
echo "1. Ensure terraform.tfvars resource_group_name is empty (uses default)"
echo "2. Use Well-Architected Framework for multi-RG deployment:"
echo "   - az-p-we-rg-net-001 (network)"
echo "   - az-p-we-rg-comp-001 (compute)"
echo "   - az-p-we-rg-stor-001 (storage)"
echo "   - az-p-we-rg-sec-001 (security)"
echo "   - az-p-we-rg-mon-001 (monitoring)"
echo "3. For existing non-standard RGs, consider:"
echo "   - Migrating resources to properly named RGs"
echo "   - Or updating terraform.tfvars to match existing names"
