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 = @()

$architectureConstraintsPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\docs\architecture-constraints.md"
$currentTaskPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\context\CURRENT_TASK.md"
$devPlanPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\context\dev-plan.md"
$projectAgentsTemplatePath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\docs\project-agents-template.md"

$architectureConstraints = Get-FileContentOrNull -Path $architectureConstraintsPath
$currentTask = Get-FileContentOrNull -Path $currentTaskPath
$devPlan = Get-FileContentOrNull -Path $devPlanPath
$projectAgentsTemplate = Get-FileContentOrNull -Path $projectAgentsTemplatePath

if ($null -eq $architectureConstraints) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/docs/architecture-constraints.md" -Section "file" -Message "缺少架构约束包模板。"
}
else {
  if (-not (Test-ContainsAll -Content $architectureConstraints -Terms @("## 4.1 Backend Layering And Error Boundary", "controller_policy", "service_policy", "repository_policy_detail", "error_handling_policy", "transaction_boundary", "idempotency_policy"))) {
    $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/docs/architecture-constraints.md" -Section "backend-boundary" -Message "architecture-constraints 模板缺少第11章要求的后端分层、异常处理、事务或幂等约束。"
  }
}

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 @("Controller / Handler 边界", "Service 边界", "Repository / DAO 边界", "事务 / 幂等策略", "异常处理与错误码策略"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/context/CURRENT_TASK.md" -Section "backend-fields" -Message "CURRENT_TASK 模板缺少第11章要求的后端分层和异常/事务决策字段。"
  }
}

if ($null -eq $devPlan) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/context/dev-plan.md" -Section "file" -Message "缺少 DEV-PLAN 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $devPlan -Terms @("Backend layering check", "事务 / 幂等验证", "异常处理 / 错误码验证", "Controller / Service / Repository 边界未声明", "事务、幂等或异常处理策略未声明"))) {
    $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/context/dev-plan.md" -Section "backend-plan-gates" -Message "DEV-PLAN 模板缺少第11章要求的后端验证矩阵或 BLOCKED 条件。"
  }
}

if ($null -eq $projectAgentsTemplate) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/docs/project-agents-template.md" -Section "file" -Message "缺少 project AGENTS 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $projectAgentsTemplate -Terms @("Controller 只处理请求和响应", "Service 处理业务逻辑", "Repository/DAO 处理数据库", "DTO 处理输入输出结构"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/docs/project-agents-template.md" -Section "backend-sample" -Message "project AGENTS 模板还没有完整覆盖第11章的后端分层样板。"
  }
}

$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 "Backend lint passed."
  exit 0
}

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

exit $exitCode
