$ErrorActionPreference = 'Stop'

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

Remove-Item $result -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 30; $attempt++) {
        Start-Sleep -Milliseconds 500
        if (Test-Path $result) {
            Get-Content $result -Raw
            exit 0
        }
    }
    throw 'Minimap zoom timed out.'
}
finally {
    Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
    Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
}
