# raport_teste.ps1 - sinteza rularilor dintr-un folder de teste: afiseaza DOAR esecurile + un total.
# Regula din COMUN\docs\orchestrare-subagenti.md: orchestratorul nu citeste log-uri brute.
# Tabelul complet (-Tot) se citeste o singura data, la baseline.
#
#   powershell -ExecutionPolicy Bypass -File raport_teste.ps1 -Dir <folder> [-Tot] [-Baseline <fisier>]
#
# -Baseline: fisier salvat anterior cu -Tot; iesirea marcheaza NOU fata de baseline
#            (adica regresie) vs. esec preexistent.
param(
    [string]$Dir = (Join-Path $PSScriptRoot 'achizitie_import'),
    [switch]$Tot,
    [string]$Baseline
)

$vechi = @{}
if ($Baseline -and (Test-Path $Baseline)) {
    foreach ($ln in Get-Content $Baseline) {
        if ($ln -match '^\s*(\S+?)\s+PASS=(\d+)\s+FAIL=(\d+)') { $vechi[$Matches[1]] = [int]$Matches[3] }
    }
}

$rez = @()
foreach ($lg in (Get-ChildItem $Dir -Filter '*_log.txt' -Recurse -ErrorAction SilentlyContinue | Sort-Object Name)) {
    $t = Get-Content $lg.FullName -Encoding Default -ErrorAction SilentlyContinue
    if (-not $t) { continue }
    $nume = $lg.BaseName -replace '_log$', ''
    $pass = @($t | Select-String -Pattern '^\s*PASS').Count
    $fail = @($t | Select-String -Pattern '^\s*(FAIL|BUG)\b' | Where-Object { $_.Line -notmatch '^\s*FAIL asteptat' })
    $rez += [pscustomobject]@{
        Nume = $nume; Pass = $pass; Fail = $fail.Count
        Linii = $fail | ForEach-Object { $_.Line.Trim() }
        Varsta = [int]((Get-Date) - $lg.LastWriteTime).TotalMinutes
    }
}

$ok = @($rez | Where-Object { $_.Fail -eq 0 }).Count
$ko = @($rez | Where-Object { $_.Fail -gt 0 })

if ($Tot) {
    foreach ($r in $rez) { "{0,-34} PASS={1,-4} FAIL={2,-3} varsta={3}min" -f $r.Nume, $r.Pass, $r.Fail, $r.Varsta }
    ''
}

"$ok OK, $($ko.Count) FAIL (din $($rez.Count) rulari)"
foreach ($r in $ko) {
    $eticheta = ''
    if ($vechi.Count -gt 0) {
        if ($vechi.ContainsKey($r.Nume) -and $vechi[$r.Nume] -ge $r.Fail) { $eticheta = '  [preexistent]' }
        else { $eticheta = '  [NOU - REGRESIE]' }
    }
    "  {0} ({1} esecuri){2}" -f $r.Nume, $r.Fail, $eticheta
    foreach ($x in $r.Linii) { '      ' + $x }
}
if ($ko.Count -eq 0) { '  (nimic de raportat)' }
