[CmdletBinding()]
param(
  [string]$ReportPath = ''
)

Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$root = Split-Path -Parent $PSScriptRoot
$excludedParts = @('\node_modules\','\.git\','\runtime\','\logs\','\data\','\backups\')
$files = Get-ChildItem -LiteralPath $root -Recurse -File | Where-Object {
  $_.Extension -in @('.ps1','.psm1','.psd1')
} | Where-Object {
  $full = $_.FullName
  -not (@($excludedParts | Where-Object { $full.IndexOf($_,[StringComparison]::OrdinalIgnoreCase) -ge 0 }).Count)
} | Sort-Object FullName

$failures = New-Object System.Collections.Generic.List[string]
foreach ($file in $files) {
  $tokens = $null
  $errors = $null
  [void][System.Management.Automation.Language.Parser]::ParseFile($file.FullName,[ref]$tokens,[ref]$errors)
  foreach ($parseError in @($errors)) {
    $relative = $file.FullName.Substring($root.Length).TrimStart('\')
    $failures.Add(("{0}:{1}:{2} {3}" -f $relative,$parseError.Extent.StartLineNumber,$parseError.Extent.StartColumnNumber,$parseError.Message))
  }
}

if ($failures.Count -gt 0) {
  $report = "Windows-PowerShell-Parser-Gate fehlgeschlagen ($($failures.Count) Fehler):$([Environment]::NewLine)$(@($failures) -join [Environment]::NewLine)"
} else {
  $report = "OK: Windows PowerShell $($PSVersionTable.PSVersion) hat $($files.Count) PowerShell-Dateien ohne Parserfehler akzeptiert."
}

if (-not [string]::IsNullOrWhiteSpace($ReportPath)) {
  $parent = Split-Path -Parent $ReportPath
  if ($parent) { New-Item -ItemType Directory -Path $parent -Force | Out-Null }
  [IO.File]::WriteAllText($ReportPath,$report,(New-Object Text.UTF8Encoding($false)))
}

if ($failures.Count -gt 0) {
  [Console]::Error.WriteLine($report)
  exit 1
}

Write-Host $report
exit 0
