# ============================================================
# Script : fix_encoding_gouvernance_fixed.ps1
# Objet  : Corrige encodage et supprime caracteres accentues
# Auteur : ChatGPT - GPT-5
# Date   : 11/10/2025
# ============================================================

$BasePath = "\\DS-918\chatgpt\ChatGPT-Gouvernance-Projets"
$ReportPath = Join-Path $BasePath "_registry\FIX_REPORT.txt"
$utf8NoBom = New-Object System.Text.UTF8Encoding($false)

Write-Host "[INFO] Correction des fichiers (encodage + 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)
}

[System.IO.File]::WriteAllText($ReportPath, "RAPPORT FIX - $(Get-Date -Format 'dd-MM-yyyy HH:mm')`r`nRacine: $BasePath`r`n", $utf8NoBom)

$files = Get-ChildItem -Path $BasePath -Recurse -Filter *.txt
$fixed = 0
foreach ($f in $files) {
    $enc = Detect-Encoding $f.FullName
    $raw = Get-Content -Path $f.FullName -Raw -Encoding UTF8
    $norm = Normalize-Ascii $raw
    if (($raw -ne $norm) -or ($enc -ne "UTF-8 sans BOM (normal)")) {
        [System.IO.File]::WriteAllText($f.FullName, $norm, $utf8NoBom)
        Add-Content -Path $ReportPath -Value ("[FIXED] $($f.FullName.Replace($BasePath,'')) | AncienEncodage=$enc")
        $fixed++
    }
}
Add-Content -Path $ReportPath -Value ("Total corriges: $fixed")

Write-Host "[OK] Correction terminee. Rapport : $ReportPath" -ForegroundColor Green
