param(
    [Parameter(Mandatory = $true)][string]$TaskDirectory,
    [Parameter(Mandatory = $true)][string]$RunDirectory,
    [Parameter(Mandatory = $true)][string]$OutputFile,
    [Parameter(Mandatory = $true)][string]$RunStatus,
    [string]$WorkingDirectory = "",
    [string[]]$ExtraSections = @()
)

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

if ([string]::IsNullOrWhiteSpace($WorkingDirectory)) {
    $WorkingDirectory = Get-RepoRoot
}

$taskPack = Read-TaskPack -TaskDirectory $TaskDirectory
$ralphRoot = Get-RalphRoot
$promptPath = Join-Path $RunDirectory "prompts\codex_next_task.md"

$sections = @(
    "## PREVIOUS RUN DIRECTORY`n$RunDirectory",
    "## PREVIOUS RUN STATUS`n$RunStatus"
)
foreach ($section in $ExtraSections) {
    $sections += $section
}

New-PromptDocument `
    -TemplatePath (Join-Path $ralphRoot "templates\CODEX_NEXT_TASK_PROMPT.md") `
    -TaskPack $taskPack `
    -OutputPath $promptPath `
    -ExtraSections $sections

& (Join-Path $PSScriptRoot "Invoke-CodexMaster.ps1") `
    -PromptFile $promptPath `
    -OutputFile $OutputFile `
    -WorkingDirectory $WorkingDirectory `
    -SkipVerdictParse | Out-Null

if (-not (Test-Path $OutputFile)) {
    throw "Codex next-task generation did not produce output: $OutputFile"
}

Get-Content -Raw -Path $OutputFile
