# Classify errors from api_errors_final.txt
$lines = Get-Content 'd:\ylrz\saasadminui\api_errors_final.txt' -Encoding UTF8

$err404 = [System.Collections.ArrayList]::new()
$err500 = [System.Collections.ArrayList]::new()
$errTimeout = [System.Collections.ArrayList]::new()
$err403 = [System.Collections.ArrayList]::new()
$errOther = [System.Collections.ArrayList]::new()

foreach ($line in $lines) {
    if ($line -match '^404\|') { [void]$err404.Add($line) }
    elseif ($line -match '^500\|') { [void]$err500.Add($line) }
    elseif ($line -match '^0\|') { [void]$errTimeout.Add($line) }
    elseif ($line -match '^403\|') { [void]$err403.Add($line) }
    elseif ($line -match '^\d+\|') { [void]$errOther.Add($line) }
}

Write-Host "=== ERROR SUMMARY ==="
Write-Host "404 NOT FOUND: $($err404.Count)"
Write-Host "500 SERVER ERROR: $($err500.Count)"
Write-Host "0 TIMEOUT/CONNECTION: $($errTimeout.Count)"
Write-Host "403 FORBIDDEN: $($err403.Count)"
Write-Host "OTHER: $($errOther.Count)"
Write-Host ""

# Extract unique URL prefixes from 404 errors
Write-Host "=== 404 URL PREFIX GROUPS ==="
$prefix404 = $err404 | ForEach-Object {
    if ($_ -match '404\|(/[^/]+/[^/]+)') { $matches[1] }
    elseif ($_ -match '404\|(/[^/]+)') { $matches[1] }
} | Group-Object | Sort-Object Count -Descending
$prefix404 | Format-Table Name, Count -AutoSize

# Extract unique URL prefixes from TIMEOUT errors
Write-Host "=== TIMEOUT URL PREFIX GROUPS ==="
$prefixTimeout = $errTimeout | ForEach-Object {
    if ($_ -match '0\|([^/|]+)') { '/' + $matches[1] }
} | Group-Object | Sort-Object Count -Descending
$prefixTimeout | Format-Table Name, Count -AutoSize

# Group 500 errors by type
Write-Host "=== 500 ERROR TYPES ==="
$err500Types = $err500 | ForEach-Object {
    if ($_ -match "Request method 'GET' not supported") { 'GET_NOT_SUPPORTED' }
    elseif ($_ -match 'Failed to convert.*NumberFormatException') { 'PATH_PARAM_CONFLICT' }
    elseif ($_ -match 'Unknown column') { 'SQL_COLUMN_MISSING' }
    elseif ($_ -match 'Required request parameter') { 'MISSING_PARAM' }
    elseif ($_ -match 'bad SQL grammar') { 'SQL_ERROR' }
    else { 'OTHER' }
} | Group-Object | Sort-Object Count -Descending
$err500Types | Format-Table Name, Count -AutoSize

# Write 404 list
Write-Host "=== ALL 404 ERRORS ==="
$err404 | ForEach-Object { Write-Host $_ }

# Write 500 list
Write-Host "`n=== ALL 500 ERRORS ==="
$err500 | ForEach-Object { Write-Host $_ }

# Write timeout list
Write-Host "`n=== ALL TIMEOUT ERRORS ==="
$errTimeout | ForEach-Object { Write-Host $_ }
