[CmdletBinding()]
param()

Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$UpdaterVersion = '3.4.0'

function Get-CanonicalPackageRoot {
  $candidate = Join-Path -Path $PSScriptRoot -ChildPath '..\..'
  $resolved = Resolve-Path -LiteralPath $candidate -ErrorAction Stop
  $fullPath = [System.IO.Path]::GetFullPath($resolved.ProviderPath)
  if ([string]::IsNullOrWhiteSpace($fullPath)) {
    throw 'Der kanonische Vendoo-Paketpfad ist leer.'
  }
  if (-not (Test-Path -LiteralPath $fullPath -PathType Container)) {
    throw "Der kanonische Vendoo-Paketpfad existiert nicht: $fullPath"
  }
  return $fullPath.TrimEnd([System.IO.Path]::DirectorySeparatorChar,[System.IO.Path]::AltDirectorySeparatorChar)
}

$PackageRoot = Get-CanonicalPackageRoot
$logDirectory = Join-Path -Path $PackageRoot -ChildPath 'logs'
$logFile = Join-Path -Path $logDirectory -ChildPath 'updater-preflight.log'

function Write-PreflightLog([string]$Level,[string]$Message) {
  [System.IO.Directory]::CreateDirectory($logDirectory) | Out-Null
  $line = "$(Get-Date -Format 'yyyy-MM-dd HH:mm:ss.fff') [$Level] $Message$([Environment]::NewLine)"
  [System.IO.File]::AppendAllText($logFile,$line,(New-Object System.Text.UTF8Encoding($false)))
}

function Show-PreflightError([string]$Message) {
  try {
    Add-Type -AssemblyName PresentationFramework
    [System.Windows.MessageBox]::Show(
      "Der Vendoo Production Updater konnte die PowerShell-Startprüfung nicht bestehen.`n`n$Message`n`nProtokoll:`n$logFile",
      'Vendoo Updater – Startprüfung fehlgeschlagen',
      [System.Windows.MessageBoxButton]::OK,
      [System.Windows.MessageBoxImage]::Error
    ) | Out-Null
  } catch {}
}

try {
  Write-PreflightLog 'INFO' "Production Updater $UpdaterVersion – kanonischer Paketpfad: $PackageRoot"
  if ($PackageRoot.IndexOfAny([System.IO.Path]::GetInvalidPathChars()) -ge 0) {
    throw "Der kanonische Paketpfad enthält unzulässige Zeichen: $PackageRoot"
  }

  $scripts = @(
    (Join-Path $PackageRoot 'scripts\updater\Vendoo.Updater.Preflight.ps1'),
    (Join-Path $PackageRoot 'scripts\update-vendoo-gui.ps1'),
    (Join-Path $PackageRoot 'scripts\updater\Vendoo.Updater.UI.ps1'),
    (Join-Path $PackageRoot 'scripts\updater\Vendoo.Updater.Host.ps1'),
    (Join-Path $PackageRoot 'scripts\updater\Vendoo.Updater.Worker34.ps1')
  )

  Write-PreflightLog 'INFO' 'Echte Windows-PowerShell-Parserprüfung gestartet.'
  $allErrors = New-Object System.Collections.Generic.List[string]
  foreach ($scriptPath in $scripts) {
    if (-not (Test-Path -LiteralPath $scriptPath -PathType Leaf)) {
      $allErrors.Add("Pflichtskript fehlt: $scriptPath")
      continue
    }
    $tokens = $null
    $errors = $null
    [void][System.Management.Automation.Language.Parser]::ParseFile($scriptPath,[ref]$tokens,[ref]$errors)
    if ($errors -and $errors.Count -gt 0) {
      foreach ($parseError in $errors) {
        $allErrors.Add(("{0}:{1}:{2} {3}" -f $parseError.Extent.File,$parseError.Extent.StartLineNumber,$parseError.Extent.StartColumnNumber,$parseError.Message))
      }
    } else {
      Write-PreflightLog 'OK' "Parserprüfung erfolgreich: $scriptPath"
    }
  }

  if ($allErrors.Count -gt 0) {
    $message = @($allErrors) -join [Environment]::NewLine
    Write-PreflightLog 'FATAL' $message
    Show-PreflightError $message
    exit 21
  }

  Write-PreflightLog 'OK' 'Alle Updater-Skripte wurden vom echten Windows-PowerShell-Parser akzeptiert.'
  exit 0
} catch {
  $message = $_.Exception.ToString()
  try { Write-PreflightLog 'FATAL' $message } catch {}
  Show-PreflightError $message
  exit 22
}
