param(
    [switch]$Full
)

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

$codexConfig = Get-CodexConfig
$preferredCmd = Join-Path $env:APPDATA "npm\codex.cmd"
$preferredPs1 = Join-Path $env:APPDATA "npm\codex.ps1"
$codexPath = $null
if (Test-Path $preferredCmd) {
    $codexPath = $preferredCmd
}
elseif (Test-Path $preferredPs1) {
    $codexPath = $preferredPs1
}
else {
    $codexCommand = Get-Command codex -ErrorAction SilentlyContinue
    if ($null -ne $codexCommand) {
        $codexPath = $codexCommand.Source
    }
}

$result = [ordered]@{
    ok = $false
    binary_found = $false
    binary_path = $codexPath
    session_id = [string]$codexConfig.session_id
    model = [string]$codexConfig.model
    help_ok = $false
    full_ok = $false
    output = ""
}

if ([string]::IsNullOrWhiteSpace($codexPath)) {
    $result.output = "codex executable not found"
}
else {
    $result.binary_found = $true
    $helpOutput = & $codexPath exec resume --help 2>&1
    if ($LASTEXITCODE -eq 0) {
        $result.help_ok = $true
    }
    $result.output = (@($helpOutput) -join [Environment]::NewLine)

    if ($Full) {
        $tempPromptPath = Join-Path ([System.IO.Path]::GetTempPath()) ("ralph-codex-smoke-" + [guid]::NewGuid().ToString("N") + ".md")
        $tempOutput = Join-Path ([System.IO.Path]::GetTempPath()) ("ralph-codex-smoke-" + [guid]::NewGuid().ToString("N") + ".json")
        $tempPrompt = @'
You are Codex.
Return exactly one JSON object and nothing else.
Use this exact payload:
{"verdict":"pass","acceptance_passed":true,"fix_required":false,"summary":"smoke","highest_risk_issues":[],"next_sprint_needed":false,"next_sprint_brief":""}
'@
        try {
            Write-Utf8File -Path $tempPromptPath -Content ($tempPrompt.Trim() + "`n")
            $verdict = & (Join-Path $PSScriptRoot "Invoke-CodexMaster.ps1") -PromptFile $tempPromptPath -OutputFile $tempOutput
            $result.output = ($result.output + [Environment]::NewLine + ($verdict | ConvertTo-Json -Depth 20)).Trim()
            if ($null -ne $verdict -and [string]$verdict.verdict -eq "pass" -and [bool]$verdict.acceptance_passed) {
                $result.full_ok = $true
            }
        }
        catch {
            $result.output = ($result.output + [Environment]::NewLine + $_.Exception.Message).Trim()
        }
        finally {
            if (Test-Path $tempPromptPath) {
                Remove-Item -LiteralPath $tempPromptPath -Force -ErrorAction SilentlyContinue
            }
            if (Test-Path $tempOutput) {
                Remove-Item -LiteralPath $tempOutput -Force -ErrorAction SilentlyContinue
            }
        }
    }
}

$result.ok = [bool]($result.binary_found -and $result.help_ok -and ((-not $Full) -or $result.full_ok))
$outputPath = Join-Path (Get-RalphRoot) "state\codex_smoke.json"
Write-Utf8File -Path $outputPath -Content ((@($result) | ConvertTo-Json -Depth 20) + "`n")
Get-Content -Raw -Path $outputPath
