$ErrorActionPreference = 'Stop'

$repo = Join-Path $env:USERPROFILE 'TibiaPilotNG'
$taskName = 'TibiaPilotNG-BBot-QA'
$action = New-ScheduledTaskAction `
    -Execute 'powershell.exe' `
    -Argument '-NoProfile -NonInteractive -ExecutionPolicy Bypass -File tools\Run-BBot-QA.ps1' `
    -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 "BBot QA exit code: $result"
            exit $result
        }
    }
    throw 'BBot QA timed out.'
}
finally {
    Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
    Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
    Start-ScheduledTask -TaskName 'TibiaPilotNG'
}
