$ErrorActionPreference = 'Stop'

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

Remove-Item (Join-Path $repo '.use-ladder-result.json') -Force -ErrorAction SilentlyContinue
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 250
        if (Test-Path (Join-Path $repo '.use-ladder-result.json')) { break }
    }
    Get-Content (Join-Path $repo '.use-ladder-result.json') -Raw
}
finally {
    Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
    Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
}
