# ============================================================
# Script : verify_encoding_gouvernance_fixed.ps1
# Objet  : Verifie encodage et presence de caracteres accentues
# Auteur : ChatGPT - GPT-5
# Date   : 11/10/2025
# ============================================================

$BasePath = "\\DS-918\chatgpt\ChatGPT-Gouvernance-Projets"
$ReportPath = Join-Path $BasePath "_registry\ENCODING_REPORT.txt"

Write-Host "[INFO] Verification de l'encodage et des accents..." -ForegroundColor Cyan

function Detect-Encoding($filePath) {
    $bytes = [System.IO.File]::ReadAllBytes($filePath)
    if ($bytes.Length -ge 3 -and $bytes[0] -eq 0xEF -and $bytes[1] -eq 0xBB -and $bytes[2] -eq 0xBF) { return "UTF-8 BOM" }
    elseif ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFF -and $bytes[1] -eq 0xFE) { return "UTF-16 LE" }
    elseif ($bytes.Length -ge 2 -and $bytes[0] -eq 0xFE -and $bytes[1] -eq 0xFF) { return "UTF-16 BE" }
    else { return "UTF-8 sans BOM (normal)" }
}

function Normalize-Ascii([string]$text) {
    $formD = $text.Normalize([Text.NormalizationForm]::FormD)
    $sb = New-Object System.Text.StringBuilder
    foreach ($ch in $formD.ToCharArray()) {
        $cat = [Globalization.CharUnicodeInfo]::GetUnicodeCategory($ch)
        if ($cat -ne [Globalization.UnicodeCategory]::NonSpacingMark) { [void]$sb.Append($ch) }
    }
    $s = $sb.ToString()
    $s = $s -replace "[\u2018\u2019]","'" -replace "[\u2013\u2014]","-" -replace "\u2026","..."
    return $s.Normalize([Text.NormalizationForm]::FormC)
}

$utf8NoBom = New-Object System.Text.UTF8Encoding($false)
[System.IO.File]::WriteAllText($ReportPath, "RAPPORT VERIFICATION - $(Get-Date -Format 'dd-MM-yyyy HH:mm')`r`nRacine: $BasePath`r`n", $utf8NoBom)

$files = Get-ChildItem -Path $BasePath -Recurse -Filter *.txt
foreach ($f in $files) {
    $enc = Detect-Encoding $f.FullName
    $raw = Get-Content -Path $f.FullName -Raw -Encoding UTF8
    $norm = Normalize-Ascii $raw
    $hasAccents = if ($raw -ne $norm) { "OUI" } else { "NON" }
    Add-Content -Path $ReportPath -Value ("$($f.FullName.Replace($BasePath,'')) | Encodage=$enc | AccentsDetectes=$hasAccents | Taille=$([math]::Round($f.Length/1024,2)) Ko")
}

Write-Host "[OK] Rapport cree : $ReportPath" -ForegroundColor Green
