$ErrorActionPreference = 'Stop'

$repo = Join-Path $env:USERPROFILE 'TibiaPilotNG'
$launcher = Join-Path $env:LOCALAPPDATA 'Tibia\Tibia.exe'
$taskName = 'TibiaPilotNG-Client'
$startedAt = Get-Date

& (Join-Path $repo 'tools\Stop-TibiaPilotNG.ps1')
Stop-Process -Name client -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 2

$action = New-ScheduledTaskAction `
    -Execute $launcher `
    -WorkingDirectory (Split-Path $launcher)
$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
Start-ScheduledTask -TaskName $taskName

for ($attempt = 0; $attempt -lt 45; $attempt++) {
    Start-Sleep -Seconds 1
    $client = Get-Process client -ErrorAction SilentlyContinue |
        Where-Object StartTime -gt $startedAt |
        Select-Object -First 1
    if ($client) {
        Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
        Write-Host "Tibia client ready: $($client.Id)"
        exit 0
    }
}

throw 'Tibia client did not start.'
