$ErrorActionPreference = 'Stop'
$repo = Join-Path $env:USERPROFILE 'TibiaPilotNG'
$taskName = 'TibiaPilotNG-Chat-Off-Live'
$result = Join-Path $repo '.chat-off-live.json'
Remove-Item $result -Force -ErrorAction SilentlyContinue
$action = New-ScheduledTaskAction `
    -Execute (Join-Path $repo '.venv\Scripts\python.exe') `
    -Argument 'tools\Set-Chat-Off-Live.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 20; $attempt++) {
        Start-Sleep -Milliseconds 500
        if (Test-Path $result) {
            Get-Content $result -Raw
            exit 0
        }
    }
    throw 'Chat-Off live task timed out.'
}
finally {
    Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
    Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
}
