#!/bin/bash

# Check Azure resource naming conventions
# Identifies resources that don't follow the standard naming pattern
#
# REFACTORED VERSION - Uses common libraries

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/../lib/init.sh"

# Initialize
SUBSCRIPTION_ID="$(get_subscription_id)"
ensure_azure_cli || exit 1
set_subscription "$SUBSCRIPTION_ID" || true

log_section "CHECKING AZURE RESOURCE NAMING CONVENTIONS"

# Check function for standard pattern
check_naming() {
    local name=$1
    local resource_type=$2
    local location=$3
    
    # Standard pattern should start with az-p-, az-d-, or az-we- (dev environment)
    if [[ ! "$name" =~ ^az-[pdwe]- ]]; then
        return 1
    fi
    
    # Should contain dashes (not legacy format without dashes)
    if [[ "$name" =~ ^az[pd][a-z]+ ]]; then
        return 1
    fi
    
    # Should follow pattern: az-{env}-{code}-{type}-{purpose}-{instance}
    # Region code should be exactly 3 characters for standard format
    # Or: az-{env}-{type}-{purpose}-{instance} (for dev/main resources)
    # Or: az-{env}-{code}-aks-{purpose} (for dev AKS clusters)
    # Basic validation - check for 3-char region code pattern
    if [[ "$name" =~ ^az-[pdwe]-[a-z]{3}-[a-z]+- ]] || [[ "$name" =~ ^az-[we]-[a-z]+- ]] || [[ "$name" =~ ^az-[we]-[a-z]+-aks- ]]; then
        return 0
    fi
    
    return 1
}

log_subsection "KEY VAULTS"

KEY_VAULTS=$(az keyvault list --query "[].{Name:name, RG:resourceGroup, Location:location}" -o tsv 2>/dev/null || true)
STANDARD_COUNT=0
LEGACY_COUNT=0
OTHER_COUNT=0

if [ -n "$KEY_VAULTS" ]; then
    while IFS=$'\t' read -r name rg location; do
        if [ -z "$name" ]; then
            continue
        fi
        
        if check_naming "$name" "keyvault" "$location"; then
            log_success "$name (RG: $rg)"
            STANDARD_COUNT=$((STANDARD_COUNT + 1))
        elif [[ "$name" =~ ^azp[a-z]+kvsecrets001$ ]]; then
            echo -e "${YELLOW}⚠${NC} $name (RG: $rg) - Legacy format (no dashes)"
            LEGACY_COUNT=$((LEGACY_COUNT + 1))
        else
            log_failure "$name (RG: $rg) - Non-standard format"
            OTHER_COUNT=$((OTHER_COUNT + 1))
        fi
    done <<< "$KEY_VAULTS"
else
    log_warn "No Key Vaults found"
fi

log_subsection "RESOURCE GROUPS"

RESOURCE_GROUPS=$(az group list --query "[].{Name:name, Location:location}" -o tsv 2>/dev/null || true)
RG_STANDARD=0
RG_LEGACY=0
RG_OTHER=0

if [ -n "$RESOURCE_GROUPS" ]; then
    while IFS=$'\t' read -r name location; do
        if [ -z "$name" ]; then
            continue
        fi
        
        # Skip Azure-managed resource groups
        if [[ "$name" =~ ^NetworkWatcherRG|^cloud-shell-storage|^DefaultResourceGroup ]]; then
            echo -e "${CYAN}ℹ${NC} $name (Azure-managed)"
            continue
        fi
        
        if check_naming "$name" "resourcegroup" "$location"; then
            log_success "$name"
            RG_STANDARD=$((RG_STANDARD + 1))
        elif [[ "$name" =~ ^azp[a-z]+rg[a-z]+001$ ]]; then
            echo -e "${YELLOW}⚠${NC} $name - Legacy format (no dashes)"
            RG_LEGACY=$((RG_LEGACY + 1))
        else
            log_failure "$name - Non-standard format"
            RG_OTHER=$((RG_OTHER + 1))
        fi
    done <<< "$RESOURCE_GROUPS"
else
    log_warn "No Resource Groups found"
fi

log_subsection "AKS CLUSTERS"

AKS_CLUSTERS=$(az aks list --query "[].{Name:name, RG:resourceGroup, Location:location}" -o tsv 2>/dev/null || true)
AKS_STANDARD=0
AKS_OTHER=0

if [ -n "$AKS_CLUSTERS" ]; then
    while IFS=$'\t' read -r name rg location; do
        if [ -z "$name" ]; then
            continue
        fi
        
        if check_naming "$name" "aks" "$location"; then
            log_success "$name (RG: $rg)"
            AKS_STANDARD=$((AKS_STANDARD + 1))
        elif [[ "$name" =~ ^az-(we|d)-.*-aks- ]] || [[ "$name" =~ ^az-we-aks- ]] || [[ "$name" =~ ^az-we-rg-dev- ]]; then
            echo -e "${CYAN}ℹ${NC} $name (RG: $rg) - Dev environment (acceptable)"
            AKS_STANDARD=$((AKS_STANDARD + 1))  # Count as acceptable
        else
            log_failure "$name (RG: $rg) - Non-standard format"
            AKS_OTHER=$((AKS_OTHER + 1))
        fi
    done <<< "$AKS_CLUSTERS"
else
    log_warn "No AKS clusters found"
fi

log_section "SUMMARY"

echo "Key Vaults:"
echo "  ✓ Standard format: $STANDARD_COUNT"
echo "  ⚠ Legacy format: $LEGACY_COUNT"
echo "  ✗ Non-standard: $OTHER_COUNT"
echo ""
echo "Resource Groups:"
echo "  ✓ Standard format: $RG_STANDARD"
echo "  ⚠ Legacy format: $RG_LEGACY"
echo "  ✗ Non-standard: $RG_OTHER"
echo ""
echo "AKS Clusters:"
echo "  ✓ Standard format: $AKS_STANDARD"
echo "  ✗ Non-standard: $AKS_OTHER"
echo ""

if [ "$OTHER_COUNT" -gt 0 ] || [ "$RG_OTHER" -gt 0 ] || [ "$AKS_OTHER" -gt 0 ]; then
    log_warn "Some resources use non-standard naming conventions"
    echo ""
    echo "Recommendations:"
    echo "  1. Use standard format: az-p-{code}-{type}-{purpose}-{instance}"
    echo "  2. Legacy resources cannot be renamed (Azure limitation)"
    echo "  3. Create new resources with standard naming when possible"
    echo "  4. See docs/NAMING_CONVENTIONS.md for details"
else
    log_success "All resources follow naming conventions"
fi

