$ErrorActionPreference = 'Stop'

$source = Split-Path -Parent $MyInvocation.MyCommand.Path
$target = Join-Path $env:LOCALAPPDATA 'DarenWorkbench\WorkerApp'
$stateFile = Join-Path $env:LOCALAPPDATA 'DarenWorkbench\Worker\worker-state.json'
$startup = [Environment]::GetFolderPath('Startup')

New-Item -ItemType Directory -Force -Path $target | Out-Null
$targetNode = (Join-Path $target 'node.exe').ToLowerInvariant()
Get-CimInstance Win32_Process -Filter "Name='node.exe'" -ErrorAction SilentlyContinue |
  Where-Object { $_.ExecutablePath -and $_.ExecutablePath.ToLowerInvariant() -eq $targetNode -and $_.CommandLine -match 'worker\.js' } |
  ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
Start-Sleep -Milliseconds 500

Copy-Item -LiteralPath (Join-Path $source 'worker.js') -Destination $target -Force
Copy-Item -LiteralPath (Join-Path $source 'page-tasks.js') -Destination $target -Force
Copy-Item -LiteralPath (Join-Path $source 'setup.cmd') -Destination $target -Force
Copy-Item -LiteralPath (Join-Path $source 'start-worker.cmd') -Destination $target -Force
if ((Test-Path (Join-Path $source 'node.exe')) -and -not (Test-Path (Join-Path $target 'node.exe'))) {
  Copy-Item -LiteralPath (Join-Path $source 'node.exe') -Destination $target -Force
}

$shortcutPath = Join-Path $startup 'Daren Browser Worker.lnk'
$shell = New-Object -ComObject WScript.Shell
$shortcut = $shell.CreateShortcut($shortcutPath)
$shortcut.TargetPath = Join-Path $target 'start-worker.cmd'
$shortcut.WorkingDirectory = $target
$shortcut.Save()

Write-Host "Worker installed at: $target"
if (Test-Path $stateFile) {
  Write-Host 'Existing pairing found. Restarting the worker without setup.'
  Start-Process -FilePath (Join-Path $target 'start-worker.cmd')
} else {
  Write-Host 'No pairing found. Starting first-time setup.'
  Start-Process -FilePath (Join-Path $target 'setup.cmd')
}
