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

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 Test-ContainsAll {
  param(
    [string]$Content,
    [string[]]$Terms
  )

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

  return $true
}

$issues = @()

$currentTaskPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\context\CURRENT_TASK.md"
$implementPromptPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\prompts\implement-one-task.md"
$regressionRulesPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\docs\regression-rules.md"
$repairPromptPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\prompts\repair-one-finding.md"

$currentTask = Get-FileContentOrNull -Path $currentTaskPath
$implementPrompt = Get-FileContentOrNull -Path $implementPromptPath
$regressionRules = Get-FileContentOrNull -Path $regressionRulesPath
$repairPrompt = Get-FileContentOrNull -Path $repairPromptPath

if ($null -eq $currentTask) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/context/CURRENT_TASK.md" -Section "file" -Message "缺少 CURRENT_TASK 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $currentTask -Terms @("任务性质（bugfix / feature / refactor / chore）", "行为不变约束", "允许清理的死代码 / 临时代码", "不允许删除的兼容逻辑 / 历史入口"))) {
    $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/context/CURRENT_TASK.md" -Section "refactor-fields" -Message "CURRENT_TASK 模板缺少第18章要求的任务类型、行为不变或死代码清理字段。"
  }
}

if ($null -eq $implementPrompt) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/prompts/implement-one-task.md" -Section "file" -Message "缺少实现 prompt 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $implementPrompt -Terms @("bugfix", "feature", "refactor", "chore", "如果是 `refactor`，必须先列出“行为不变约束”", "无用变量", "无用函数", "临时代码"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/prompts/implement-one-task.md" -Section "refactor-flow" -Message "实现 prompt 还没有完整承接第18章的任务类型区分或死代码清理检查。"
  }
}

if ($null -eq $regressionRules) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/docs/regression-rules.md" -Section "file" -Message "缺少回归规则模板。"
}
else {
  if (-not (Test-ContainsAll -Content $regressionRules -Terms @("重构任务必须显式声明行为不变约束", "无用变量", "无用函数", "无用组件", "兼容逻辑"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/docs/regression-rules.md" -Section "refactor-regression" -Message "回归规则模板还没有完整承接第18章的行为不变和死代码清理要求。"
  }
}

if ($null -eq $repairPrompt) {
  $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/prompts/repair-one-finding.md" -Section "file" -Message "缺少 repair prompt 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $repairPrompt -Terms @("不顺手重构", "不要把单点修复顺手扩展成结构性重构或死代码清理任务"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/prompts/repair-one-finding.md" -Section "repair-boundary" -Message "repair prompt 还没有完整承接第18章的小步修复边界。"
  }
}

$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 -and -not $AllowWarningsOnly) { 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 "Refactor lint passed."
  exit 0
}

if ($errors.Count -gt 0) {
  Write-Output "Refactor 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 "Refactor lint passed with warnings."
  }
  foreach ($issue in $warnings) {
    Write-Output ("- [WARNING] {0} :: {1} :: {2}" -f $issue.file, $issue.section, $issue.message)
  }
}

exit $exitCode
