# ============================================================
# Script : run_encoding_maintenance.ps1
# Objet  : Lance verification + correction + re-verification
# Auteur : ChatGPT - GPT-5
# Date   : 11/10/2025
# ============================================================

$BasePath = "\\DS-918\chatgpt\ChatGPT-Gouvernance-Projets"
$ToolsPath = Join-Path $BasePath "00_DOCUMENTATION\scripts_utilitaires"
$VerifyScript = Join-Path $ToolsPath "verify_encoding_gouvernance_fixed.ps1"
$FixScript    = Join-Path $ToolsPath "fix_encoding_gouvernance_fixed.ps1"
$ReportVerify = Join-Path $BasePath "_registry\ENCODING_REPORT.txt"
$ReportFix    = Join-Path $BasePath "_registry\FIX_REPORT.txt"
$NowStamp = Get-Date -Format "dd-MM-yyyy HH:mm"

Write-Host "============================================" -ForegroundColor Cyan
Write-Host "[RUN] Maintenance d'encodage - $NowStamp" -ForegroundColor Cyan
Write-Host "============================================`n"

# --- Fonction utilitaire ---
function Run-Script($scriptPath, $label) {
    if (Test-Path $scriptPath) {
        Write-Host "[INFO] Execution de $label ..." -ForegroundColor Yellow
        & $scriptPath
        Write-Host ""
    } else {
        Write-Host "[ERREUR] Script manquant : $scriptPath" -ForegroundColor Red
        exit 1
    }
}

# --- Etape 1 : Verification initiale ---
Run-Script $VerifyScript "Verification initiale"

# --- Lecture du rapport ---
$needFix = $false
if (Test-Path $ReportVerify) {
    $reportText = Get-Content -Path $ReportVerify -Raw -Encoding UTF8
    if ($reportText -match "AccentsDetectes=OUI" -or $reportText -match "UTF-16" -or $reportText -match "BOM") {
        $needFix = $true
        Write-Host "[ALERTE] Anomalies detectees dans les fichiers." -ForegroundColor Yellow
    } else {
        Write-Host "[CHECK] Aucun probleme d'encodage detecte." -ForegroundColor Green
    }
} else {
    Write-Host "[WARN] Rapport introuvable apres verification initiale." -ForegroundColor Yellow
}

# --- Etape 2 : Correction si necessaire ---
if ($needFix) {
    Run-Script $FixScript "Correction automatique"
} else {
    Write-Host "[INFO] Etape de correction sautee (aucune anomalie)." -ForegroundColor Cyan
}

# --- Etape 3 : Re-verification ---
Run-Script $VerifyScript "Re-verification finale"

# --- Etape 4 : Affichage du resultat ---
if (Test-Path $ReportVerify) {
    Write-Host "`n[OK] Rapport final : $ReportVerify" -ForegroundColor Green
    Start-Process notepad.exe $ReportVerify
} else {
    Write-Host "[WARN] Aucun rapport de verification final trouve." -ForegroundColor Yellow
}

Write-Host "`n[END] Maintenance complete." -ForegroundColor Cyan
