param(
    [Parameter(Mandatory = $true)]
    [string]$Executable,

    [Parameter(Mandatory = $true)]
    [string]$Name,

    [string]$OutputDirectory = "C:\codex\screenshots",

    [string]$Arguments = "",

    [string]$WorkingDirectory = "",

    [string]$InitialKeys = "",

    [string]$ScreenshotTool = "",

    [ValidateRange(1, 60)]
    [int]$WaitSeconds = 8
)

$ErrorActionPreference = "Stop"
[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new()
$taskName = "CodexScreenshot"
$screenshotScript = Join-Path $PSScriptRoot "screenshotApp.ps1"
$resultPath = Join-Path $OutputDirectory "$Name.json"

New-Item -ItemType Directory -Force -Path $OutputDirectory | Out-Null
Remove-Item -Force -ErrorAction SilentlyContinue $resultPath, (Join-Path $OutputDirectory "$Name.png")

$taskArguments = @(
    "-NoProfile"
    "-ExecutionPolicy Bypass"
    "-File `"$screenshotScript`""
    "-Executable `"$Executable`""
    "-Name `"$Name`""
    "-OutputDirectory `"$OutputDirectory`""
    "-WaitSeconds $WaitSeconds"
)
if ($Arguments.Length -gt 0) {
    $escapedArguments = $Arguments.Replace('"', '\"')
    $taskArguments += "-Arguments `"$escapedArguments`""
}
if ($WorkingDirectory.Length -gt 0) {
    $taskArguments += "-WorkingDirectory `"$WorkingDirectory`""
}
if ($InitialKeys.Length -gt 0) {
    $taskArguments += "-InitialKeys `"$InitialKeys`""
}
if ($ScreenshotTool.Length -gt 0) {
    $taskArguments += "-ScreenshotTool `"$ScreenshotTool`""
}

$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument ($taskArguments -join " ")
$principal = New-ScheduledTaskPrincipal -UserId $env:USERNAME -LogonType Interactive -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -ExecutionTimeLimit (New-TimeSpan -Minutes 2) -AllowStartIfOnBatteries

Register-ScheduledTask -TaskName $taskName -Action $action -Principal $principal -Settings $settings -Force | Out-Null
try {
    Start-ScheduledTask -TaskName $taskName
    $deadline = (Get-Date).AddSeconds($WaitSeconds + 30)
    while (-not (Test-Path $resultPath) -and (Get-Date) -lt $deadline) {
        Start-Sleep -Milliseconds 500
    }

    if (-not (Test-Path $resultPath)) {
        throw "Screenshot task timed out."
    }

    Get-Content -Raw -Encoding UTF8 $resultPath
}
finally {
    Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
    Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -ErrorAction SilentlyContinue
}
