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

$frontendArchitecturePath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\design\frontend-architecture.md"
$verifyMatrixPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\testing\verify-matrix.md"
$evidenceProtocolPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\testing\EVIDENCE_PROTOCOL.md"
$currentTaskPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\context\CURRENT_TASK.md"

$frontendArchitecture = Get-FileContentOrNull -Path $frontendArchitecturePath
$verifyMatrix = Get-FileContentOrNull -Path $verifyMatrixPath
$evidenceProtocol = Get-FileContentOrNull -Path $evidenceProtocolPath
$currentTask = Get-FileContentOrNull -Path $currentTaskPath

if ($null -eq $frontendArchitecture) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/design/frontend-architecture.md" -Section "file" -Message "缺少 frontend-architecture 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $frontendArchitecture -Terms @("## 5. 状态管理", "可分享、可回退、影响查询结果的状态优先进入 URL", "同一业务条件只能有一个主状态来源", "## 5.1 缓存与失效策略", "写操作完成后，必须明确哪些列表、详情、统计或徽标需要失效或同步更新"))) {
    $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/design/frontend-architecture.md" -Section "state-governance" -Message "frontend-architecture 模板缺少第九章要求的状态分层、状态唯一来源或缓存失效策略。"
  }
}

if ($null -eq $verifyMatrix) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/testing/verify-matrix.md" -Section "file" -Message "缺少验证矩阵模板。"
}
else {
  if (-not (Test-ContainsAll -Content $verifyMatrix -Terms @("状态唯一来源检查", "缓存失效检查"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/testing/verify-matrix.md" -Section "state-checks" -Message "验证矩阵模板还没有显式列出状态唯一来源或缓存失效检查。"
  }
}

if ($null -eq $evidenceProtocol) {
  $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/testing/EVIDENCE_PROTOCOL.md" -Section "file" -Message "缺少证据协议模板。"
}
else {
  if (-not (Test-ContainsAll -Content $evidenceProtocol -Terms @("cache_observation", "state_source_snapshot"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/testing/EVIDENCE_PROTOCOL.md" -Section "state-evidence" -Message "证据协议模板还没有把状态来源和缓存观察作为独立证据类型。"
  }
}

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 @("类似状态管理", "当前状态分层决策", "哪些状态禁止重复存放", "缓存失效或刷新规则"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/context/CURRENT_TASK.md" -Section "state-fields" -Message "CURRENT_TASK 模板缺少状态分层、禁止重复存放或缓存失效决策字段。"
  }
}

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

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

exit $exitCode
