$ErrorActionPreference = 'Stop'

$repo = Join-Path $env:USERPROFILE 'TibiaPilotNG'
$taskName = 'TibiaPilotNG-Primary-Diagnostic'
$action = New-ScheduledTaskAction `
    -Execute (Join-Path $repo '.venv\Scripts\pythonw.exe') `
    -Argument 'tools\Primary-Runtime-Diagnostic.py' `
    -WorkingDirectory $repo
$principal = New-ScheduledTaskPrincipal `
    -UserId $env:USERNAME `
    -LogonType Interactive `
    -RunLevel Highest

Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
Register-ScheduledTask -TaskName $taskName -Action $action -Principal $principal | Out-Null

try {
    Start-ScheduledTask -TaskName $taskName
    for ($attempt = 0; $attempt -lt 40; $attempt++) {
        Start-Sleep -Milliseconds 500
        $task = Get-ScheduledTask -TaskName $taskName
        if ($task.State -ne 'Running') {
            $result = (Get-ScheduledTaskInfo -TaskName $taskName).LastTaskResult
            Write-Output "Primary diagnostic exit code: $result"
            exit $result
        }
    }
    throw 'Primary diagnostic timed out.'
}
finally {
    Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
    Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
}
