$ErrorActionPreference = 'Stop'

$repo = Join-Path $env:USERPROFILE 'TibiaPilotNG'
$taskName = 'TibiaPilotNG-Runtime-Diagnostic'
$action = New-ScheduledTaskAction `
    -Execute (Join-Path $repo '.venv\Scripts\pythonw.exe') `
    -Argument 'tools\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

$pythonPrefix = Join-Path $repo '.venv\Scripts\python'
Stop-ScheduledTask -TaskName 'TibiaPilotNG' -ErrorAction SilentlyContinue
Get-CimInstance Win32_Process | Where-Object {
    $_.ExecutablePath -like "$pythonPrefix*.exe" -and $_.CommandLine -match 'main\.py'
} | ForEach-Object {
    Invoke-CimMethod -InputObject $_ -MethodName Terminate | Out-Null
}

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