param(
  [Parameter(Mandatory = $true)]
  [string]$Package
)
$ErrorActionPreference = 'Stop'

$packagePath = (Resolve-Path -LiteralPath $Package).Path
$tempRoot = Join-Path ([IO.Path]::GetTempPath()) "SmartCut64-package-test-$PID"
if (Test-Path -LiteralPath $tempRoot) { throw "Temporary validation path already exists: $tempRoot" }
New-Item -ItemType Directory -Path $tempRoot | Out-Null
try {
  Expand-Archive -LiteralPath $packagePath -DestinationPath $tempRoot
  $installRoot = Join-Path $tempRoot ([IO.Path]::GetFileNameWithoutExtension($packagePath))
  if (-not (Test-Path -LiteralPath $installRoot)) { throw "Package root was not installed: $installRoot" }
  $bin = Join-Path $installRoot 'bin'
  $cli = Join-Path $bin 'smartcut-cli.exe'
  $worker = Join-Path $bin 'smartcut-worker.exe'
  $gui = Join-Path $bin 'smartcut-gui.exe'
  foreach ($file in @($cli, $worker, $gui)) {
    if (-not (Test-Path -LiteralPath $file)) { throw "Installed package is missing: $file" }
  }

  $previousPath = $env:PATH
  $previousQpa = $env:QT_QPA_PLATFORM
  $env:PATH = "$env:SystemRoot\System32;$env:SystemRoot"
  try {
    $cliRun = Start-Process -FilePath $cli -ArgumentList '--versions' -WorkingDirectory $bin -Wait -PassThru -NoNewWindow
    if ($cliRun.ExitCode -ne 0) { throw "Installed CLI failed with exit code $($cliRun.ExitCode)" }
    $env:QT_QPA_PLATFORM = 'offscreen'
    $guiRun = Start-Process -FilePath $gui -ArgumentList '--version' -WorkingDirectory $bin -Wait -PassThru -NoNewWindow
  } finally {
    $env:PATH = $previousPath
    $env:QT_QPA_PLATFORM = $previousQpa
  }
  if ($guiRun.ExitCode -ne 0) { throw "Installed GUI version check failed with exit code $($guiRun.ExitCode)" }

  Write-Host "Package install test passed: extracted, launched, and validated $installRoot"
} finally {
  if (Test-Path -LiteralPath $tempRoot) { Remove-Item -LiteralPath $tempRoot -Recurse -Force }
}
