param(
    [string]$TaskDirectory = "",
    [string]$RunLabel = "background",
    [string]$Implementer = "",
    [string[]]$Reviewers = @(),
    [switch]$DisableCodexMaster,
    [switch]$DisableAutoFix
)

. (Join-Path $PSScriptRoot "Common.ps1")

$ralphRoot = Get-RalphRoot
$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$stdoutLog = Join-Path $ralphRoot ("logs\ralph-" + $timestamp + ".out.log")
$stderrLog = Join-Path $ralphRoot ("logs\ralph-" + $timestamp + ".err.log")
$stateFile = Join-Path $ralphRoot "state\last_background_run.json"

$autopilotScript = Join-Path $PSScriptRoot "Start-RalphAutopilot.ps1"
$argumentParts = @(
    "-ExecutionPolicy Bypass",
    ('-File "{0}"' -f $autopilotScript),
    ('-RunLabel "{0}"' -f $RunLabel)
)

if (-not [string]::IsNullOrWhiteSpace($TaskDirectory)) {
    $argumentParts += ('-TaskDirectory "{0}"' -f $TaskDirectory)
}
if (-not [string]::IsNullOrWhiteSpace($Implementer)) {
    $argumentParts += ('-Implementer "{0}"' -f $Implementer)
}
foreach ($reviewer in $Reviewers) {
    $argumentParts += ('-Reviewers "{0}"' -f $reviewer)
}
if ($DisableCodexMaster) {
    $argumentParts += '-UseCodexMaster:$false'
}
if ($DisableAutoFix) {
    $argumentParts += '-AutoFix:$false'
}

$argumentList = $argumentParts -join ' '

$process = Start-Process `
    -FilePath "powershell.exe" `
    -ArgumentList $argumentList `
    -WorkingDirectory (Get-RepoRoot) `
    -WindowStyle Hidden `
    -RedirectStandardOutput $stdoutLog `
    -RedirectStandardError $stderrLog `
    -PassThru

$state = [ordered]@{
    pid = $process.Id
    started_at = (Get-Date).ToString("o")
    stdout_log = $stdoutLog
    stderr_log = $stderrLog
    run_label = $RunLabel
    status = "started"
}

Write-JsonFile -Path $stateFile -Object $state
Add-RalphEvent -RunId ("background-" + $timestamp) -Stage "background" -Status "started" -Actor "launcher" -Message "Background Ralph process launched" -Data @{
    pid = $process.Id
    run_label = $RunLabel
    stdout_log = $stdoutLog
    stderr_log = $stderrLog
}
Get-Content -Raw -Path $stateFile
