param(
  [string]$ProjectRoot = "",
  [switch]$AsJson
)

Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"

if ([string]::IsNullOrWhiteSpace($ProjectRoot)) {
  $ProjectRoot = [System.IO.Path]::GetFullPath((Join-Path $PSScriptRoot "..\..\..\.."))
}

function New-Issue {
  param(
    [string]$Severity,
    [string]$File,
    [string]$Section,
    [string]$Message
  )

  [PSCustomObject]@{
    severity = $Severity
    file = $File
    section = $Section
    message = $Message
  }
}

function Get-FileContentOrNull {
  param([string]$Path)

  if (-not (Test-Path -LiteralPath $Path)) {
    return $null
  }

  Get-Content -LiteralPath $Path -Raw
}

function Resolve-FirstExistingPath {
  param([string[]]$Candidates)

  foreach ($candidate in $Candidates) {
    if (Test-Path -LiteralPath $candidate) {
      return $candidate
    }
  }

  return $null
}

function Test-ContainsAll {
  param(
    [string]$Content,
    [string[]]$Terms
  )

  foreach ($term in $Terms) {
    if ($Content -notmatch [regex]::Escape($term)) {
      return $false
    }
  }

  return $true
}

$issues = @()

$stage1PromptPath = Resolve-FirstExistingPath -Candidates @(
  (Join-Path $ProjectRoot ".codex\prompts\review-stage1-spec.md"),
  (Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\prompts\review-stage1-spec.md")
)
$stage2PromptPath = Resolve-FirstExistingPath -Candidates @(
  (Join-Path $ProjectRoot ".codex\prompts\review-stage2-quality.md"),
  (Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\prompts\review-stage2-quality.md")
)
$failureTriagePromptPath = Resolve-FirstExistingPath -Candidates @(
  (Join-Path $ProjectRoot ".codex\prompts\failure-triage.md"),
  (Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\prompts\failure-triage.md")
)
$repairPromptPath = Resolve-FirstExistingPath -Candidates @(
  (Join-Path $ProjectRoot ".codex\prompts\repair-one-finding.md"),
  (Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\prompts\repair-one-finding.md")
)
$traceSchemaPath = Resolve-FirstExistingPath -Candidates @(
  (Join-Path $ProjectRoot "docs\harness\trace.schema.json"),
  (Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\trace\trace.schema.json")
)
$driverPath = Resolve-FirstExistingPath -Candidates @(
  (Join-Path $ProjectRoot "tools\harness\codex-loop.ps1"),
  (Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\runtime\codex-loop.ps1")
)
$verifyPath = Resolve-FirstExistingPath -Candidates @(
  (Join-Path $ProjectRoot "tools\harness\verify.ps1"),
  (Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\runtime\verify.ps1")
)

$stage1Prompt = Get-FileContentOrNull -Path $stage1PromptPath
if ($null -eq $stage1Prompt -or -not (Test-ContainsAll -Content $stage1Prompt -Terms @("Verdict", "PASS", "NEEDS_REPAIR", "BLOCKED", "Repair Queue"))) {
  $issues += New-Issue -Severity "error" -File ".codex/prompts/review-stage1-spec.md" -Section "prompt" -Message "Stage 1 prompt 缺少结构化 verdict 或 repair queue 约束。"
}

$stage2Prompt = Get-FileContentOrNull -Path $stage2PromptPath
if ($null -eq $stage2Prompt -or -not (Test-ContainsAll -Content $stage2Prompt -Terms @("Verdict", "PASS", "NEEDS_REPAIR", "BLOCKED", "HUMAN_REVIEW_REQUIRED", "Repair Queue"))) {
  $issues += New-Issue -Severity "error" -File ".codex/prompts/review-stage2-quality.md" -Section "prompt" -Message "Stage 2 prompt 缺少结构化 verdict 或 repair queue 约束。"
}

$failureTriagePrompt = Get-FileContentOrNull -Path $failureTriagePromptPath
if ($null -eq $failureTriagePrompt -or -not (Test-ContainsAll -Content $failureTriagePrompt -Terms @("TEST_CODE_ISSUE", "PRODUCT_BUG", "REQUIREMENT_CHANGE", "ENV_OR_DATA_ISSUE", "FLAKY", "不直接修复代码"))) {
  $issues += New-Issue -Severity "error" -File ".codex/prompts/failure-triage.md" -Section "prompt" -Message "failure-triage prompt 缺少五类归因或只读分类约束。"
}

$repairPrompt = Get-FileContentOrNull -Path $repairPromptPath
if ($null -eq $repairPrompt -or -not (Test-ContainsAll -Content $repairPrompt -Terms @("你是 repair worker", "你只修复一个 finding", "不要修复其他 finding"))) {
  $issues += New-Issue -Severity "error" -File ".codex/prompts/repair-one-finding.md" -Section "prompt" -Message "repair prompt 缺少单 finding 修复边界。"
}

$traceSchema = Get-FileContentOrNull -Path $traceSchemaPath
if ($null -eq $traceSchema -or -not (Test-ContainsAll -Content $traceSchema -Terms @('"stage1_review"', '"stage2_review"', '"truth_sources_used"', '"impact_analysis_summary"', '"acceptance_matrix"', '"test_command"', '"test_result_summary"', '"remaining_risks"', '"files_changed"', '"failure_triage_summary"', '"evidence_gate_status"', '"repair_queue"'))) {
  $issues += New-Issue -Severity "error" -File "docs/harness/trace.schema.json" -Section "trace" -Message "trace schema 缺少 review、triage、evidence gate 或 repair queue 关键字段。"
}

$driver = Get-FileContentOrNull -Path $driverPath
if ($null -eq $driver -or -not (Test-ContainsAll -Content $driver -Terms @("Get-ReviewVerdict", "Get-EvidenceGateFindings", "Invoke-FailureTriage", "Save-Trace", "Write-ProgressEntry", "Set-TaskPassed"))) {
  $issues += New-Issue -Severity "error" -File "tools/harness/codex-loop.ps1" -Section "runtime" -Message "codex-loop 缺少 review/test/triage/trace/progress/task-pass 闭环关键步骤。"
}

$verify = Get-FileContentOrNull -Path $verifyPath
if ($null -eq $verify -or -not (Test-ContainsAll -Content $verify -Terms @("Invoke-ReviewEvidenceValidation", "review-evidence-lint.ps1"))) {
  $issues += New-Issue -Severity "error" -File "tools/harness/verify.ps1" -Section "verify" -Message "verify 没有接入 review-evidence-lint。"
}

$errors = @($issues | Where-Object { $_.severity -eq "error" })
$warnings = @($issues | Where-Object { $_.severity -eq "warning" })
$exitCode = if ($errors.Count -gt 0) { 1 } elseif ($warnings.Count -gt 0) { 2 } else { 0 }

if ($AsJson) {
  [PSCustomObject]@{
    ok = ($exitCode -eq 0)
    errors = $errors
    warnings = $warnings
  } | ConvertTo-Json -Depth 6
  exit $exitCode
}

if ($errors.Count -eq 0 -and $warnings.Count -eq 0) {
  Write-Output "Review evidence lint passed."
  exit 0
}

if ($errors.Count -gt 0) {
  Write-Output "Review evidence lint failed."
  foreach ($issue in $errors) {
    Write-Output ("- [ERROR] {0} :: {1} :: {2}" -f $issue.file, $issue.section, $issue.message)
  }
}

if ($warnings.Count -gt 0) {
  if ($errors.Count -eq 0) {
    Write-Output "Review evidence lint passed with warnings."
  }
  foreach ($issue in $warnings) {
    Write-Output ("- [WARNING] {0} :: {1} :: {2}" -f $issue.file, $issue.section, $issue.message)
  }
}

exit $exitCode
