param(
  [string]$ProjectRoot = (Resolve-Path -LiteralPath (Join-Path $PSScriptRoot "..")).Path,
  [string]$OcrWorkers = $env:GAA_OCR_WORKERS
)

$ErrorActionPreference = "Stop"

function Quote-ProcessArgument([string]$Value) {
  return '"' + $Value.Replace('"', '\"') + '"'
}

try {
  $project = (Resolve-Path -LiteralPath $ProjectRoot).Path
  $script = Join-Path $PSScriptRoot "dev-admin-start.ps1"
  $powershellExe = Join-Path $env:SystemRoot "System32\WindowsPowerShell\v1.0\powershell.exe"
  $arguments = @(
    "-NoProfile",
    "-ExecutionPolicy Bypass",
    "-NoExit",
    "-File $(Quote-ProcessArgument $script)",
    "-ProjectRoot $(Quote-ProcessArgument $project)"
  ) -join " "
  if ($OcrWorkers) {
    $arguments += " -OcrWorkers $(Quote-ProcessArgument $OcrWorkers)"
  }

  Start-Process -FilePath $powershellExe -ArgumentList $arguments -WorkingDirectory $project -Verb RunAs -WindowStyle Normal -ErrorAction Stop

  Write-Host ""
  Write-Host "UAC-Abfrage gestartet. Bitte bestaetigen - danach oeffnet sich ein neues Administrator-Fenster mit npm run dev." -ForegroundColor Green
  Write-Host "Dieses Fenster kann geschlossen werden; das eigentliche Programm laeuft im neuen Administrator-Fenster."
} catch {
  Write-Host ""
  Write-Host "Admin-Start fehlgeschlagen oder UAC-Abfrage abgelehnt:" -ForegroundColor Red
  Write-Host $_.Exception.Message -ForegroundColor Red
  exit 1
}
