$ErrorActionPreference="Stop"
Add-Type -AssemblyName PresentationFramework
$Root=Join-Path $env:LOCALAPPDATA "kir0Qual"
$Engine=Join-Path $Root "Engine"
$Payload=Join-Path $PSScriptRoot "engine_payload.zip"
$Vbs=Join-Path $Root "start-engine.vbs"
$Startup=Join-Path $env:APPDATA "Microsoft\Windows\Start Menu\Programs\Startup\kir0Qual Engine.lnk"

function Msg($m){ [System.Windows.MessageBox]::Show($m,"kir0Qual Setup","OK","Information")|Out-Null }
function Err($m){ [System.Windows.MessageBox]::Show($m,"kir0Qual Setup","OK","Error")|Out-Null }

try{
 New-Item -ItemType Directory -Force -Path $Root|Out-Null
 try{
  Get-NetTCPConnection -LocalPort 8788 -State Listen -ErrorAction SilentlyContinue|ForEach-Object{
   if($_.OwningProcess){Stop-Process -Id $_.OwningProcess -Force -ErrorAction SilentlyContinue}
  }
 }catch{}

 Remove-Item $Engine -Recurse -Force -ErrorAction SilentlyContinue
 New-Item -ItemType Directory -Force -Path $Engine|Out-Null
 Expand-Archive -Path $Payload -DestinationPath $Engine -Force

 if(!(Test-Path (Join-Path $Engine "package.json")) -or !(Test-Path (Join-Path $Engine "server.js"))){
   throw "kir0Qual Engine files were not extracted correctly."
 }

 $node=Get-Command node.exe -ErrorAction SilentlyContinue
 if(-not $node){
  $winget=Get-Command winget.exe -ErrorAction SilentlyContinue
  if(-not $winget){throw "Node.js is required, but Windows Package Manager is unavailable."}
  Msg "kir0Qual needs Node.js LTS once. Setup will install it automatically."
  $p=Start-Process $winget.Source -ArgumentList @("install","OpenJS.NodeJS.LTS","--silent","--accept-package-agreements","--accept-source-agreements") -Wait -PassThru
  if($p.ExitCode -ne 0){throw "Automatic Node.js installation failed."}
  $env:Path=[Environment]::GetEnvironmentVariable("Path","Machine")+";"+[Environment]::GetEnvironmentVariable("Path","User")
  $node=Get-Command node.exe -ErrorAction SilentlyContinue
  if(-not $node -and (Test-Path "C:\Program Files\nodejs\node.exe")){$node=Get-Item "C:\Program Files\nodejs\node.exe"}
  if(-not $node){throw "Node.js installed but Windows has not refreshed PATH yet. Restart Windows and run Setup once more."}
 }

 $npm=Get-Command npm.cmd -ErrorAction SilentlyContinue
 if(-not $npm){
  $cand=Join-Path (Split-Path $node.Source -Parent) "npm.cmd"
  if(Test-Path $cand){$npm=Get-Item $cand}
 }
 if(-not $npm){throw "npm could not be found."}

 $stdout=Join-Path $Root "npm-install-out.log"
 $stderr=Join-Path $Root "npm-install-err.log"
 $np=Start-Process $npm.Source -ArgumentList @("install","--omit=dev","--no-audit","--no-fund") -WorkingDirectory $Engine -Wait -PassThru -WindowStyle Hidden -RedirectStandardOutput $stdout -RedirectStandardError $stderr
 if($np.ExitCode -ne 0){
  $detail=""
  try{$detail=((Get-Content $stderr -Tail 10 -ErrorAction SilentlyContinue)+(Get-Content $stdout -Tail 10 -ErrorAction SilentlyContinue)) -join "`n"}catch{}
  throw "kir0Qual Engine dependencies failed to install.`n`n$detail"
 }

 $nodeExe=$node.Source.Replace('"','""')
 $script=(Join-Path $Engine "server.js").Replace('"','""')
 $dir=$Engine.Replace('"','""')
 @"
Set s = CreateObject("WScript.Shell")
s.CurrentDirectory = "$dir"
s.Run Chr(34) & "$nodeExe" & Chr(34) & " " & Chr(34) & "$script" & Chr(34), 0, False
"@|Set-Content $Vbs -Encoding ASCII

 $ws=New-Object -ComObject WScript.Shell
 $lnk=$ws.CreateShortcut($Startup)
 $lnk.TargetPath="$env:WINDIR\System32\wscript.exe"
 $lnk.Arguments='"'+$Vbs+'"'
 $lnk.WorkingDirectory=$Root
 $lnk.Description="kir0Qual local GPU engine"
 $lnk.Save()

 Start-Process "$env:WINDIR\System32\wscript.exe" -ArgumentList ('"'+$Vbs+'"')

 $ok=$false
 for($i=0;$i -lt 24;$i++){
  Start-Sleep -Milliseconds 500
  try{
   $r=Invoke-RestMethod "http://127.0.0.1:8788/health" -TimeoutSec 2
   if($r.localProcessing -eq $true){$ok=$true;break}
  }catch{}
 }
 if(-not $ok){throw "Engine files installed, but localhost:8788 did not answer. Close this window and run kir0Qual HQ Setup once more. If it still fails, send the setup window/error to ChatGPT."}

 Msg "DONE! kir0Qual Engine is installed and running silently.`n`nYou do NOT need to run Setup again for normal use.`n`nNext: load the 'extension' folder in Chrome."
}catch{
 Err $_.Exception.Message
 exit 1
}
