param(
    [int]$PollSeconds = 15,
    [string]$Implementer = "",
    [string[]]$Reviewers = @(),
    [switch]$DisableCodexMaster,
    [switch]$DisableAutoFix,
    [switch]$DryRun
)

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

$ralphRoot = Get-RalphRoot
$timestamp = Get-Date -Format "yyyyMMdd-HHmmss"
$stdoutLog = Join-Path $ralphRoot ("logs\ralph-inbox-" + $timestamp + ".out.log")
$stderrLog = Join-Path $ralphRoot ("logs\ralph-inbox-" + $timestamp + ".err.log")
$stateFile = Join-Path $ralphRoot "state\last_inbox_background.json"
$daemonScript = Join-Path $PSScriptRoot "Start-RalphInboxDaemon.ps1"

$argumentParts = @(
    "-ExecutionPolicy Bypass",
    ('-File "{0}"' -f $daemonScript),
    ('-PollSeconds {0}' -f $PollSeconds)
)

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

$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
    poll_seconds = $PollSeconds
    dry_run = [bool]$DryRun
    status = "started"
}

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

Get-Content -Raw -Path $stateFile
