param(
    [switch]$NoPause
)

$ErrorActionPreference = "Stop"

$root = Split-Path -Parent $MyInvocation.MyCommand.Path
$startup = [Environment]::GetFolderPath("Startup")
$shortcutPath = Join-Path $startup "ComputePool Worker.lnk"
$targetScript = Join-Path $root "start-local-worker.ps1"
$targetExe = Join-Path $root "dist\ComputePool-Worker.exe"

if (!(Test-Path -LiteralPath $targetExe) -and -not (Get-Command node -ErrorAction SilentlyContinue)) {
    Write-Host "Node.js is required before running ComputePool Worker." -ForegroundColor Yellow
    Write-Host "Install Node.js LTS, then run this installer again." -ForegroundColor Yellow
    if (-not $NoPause) { Read-Host "Press Enter to exit" }
    exit 1
}

$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut($shortcutPath)
$shortcut.TargetPath = if (Test-Path -LiteralPath $targetExe) { $targetExe } else { "powershell.exe" }
$shortcut.Arguments = if (Test-Path -LiteralPath $targetExe) { "" } else { "-ExecutionPolicy Bypass -WindowStyle Hidden -File `"$targetScript`"" }
$shortcut.WorkingDirectory = $root
$shortcut.IconLocation = if (Test-Path -LiteralPath $targetExe) { $targetExe } else { "powershell.exe,0" }
$shortcut.Save()

if (Test-Path -LiteralPath $targetExe) {
    Start-Process -FilePath $targetExe -WindowStyle Hidden -WorkingDirectory $root
} else {
    Start-Process powershell.exe -WindowStyle Hidden -WorkingDirectory $root -ArgumentList @(
        "-ExecutionPolicy", "Bypass",
        "-File", $targetScript
    )
}

Write-Host "ComputePool Worker installed and started." -ForegroundColor Green
Write-Host "Return to the website and click Detect Worker, Prepare AI Model, then Start Compute." -ForegroundColor Cyan
if (-not $NoPause) { Read-Host "Press Enter to close" }
