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

$envExamplePath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\config\env.example"
$envCheckPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\config\env-check.ps1"
$envTemplatePath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\docs\env-and-deployment-template.md"
$newProjectUsagePath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\docs\new-project-usage.md"
$codexReadmePath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\config\codex-readme.md"
$currentTaskPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\context\CURRENT_TASK.md"

$envExample = Get-FileContentOrNull -Path $envExamplePath
$envCheck = Get-FileContentOrNull -Path $envCheckPath
$envTemplate = Get-FileContentOrNull -Path $envTemplatePath
$newProjectUsage = Get-FileContentOrNull -Path $newProjectUsagePath
$codexReadme = Get-FileContentOrNull -Path $codexReadmePath
$currentTask = Get-FileContentOrNull -Path $currentTaskPath

if ($null -eq $envExample) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/config/env.example" -Section "file" -Message "缺少 env.example 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $envExample -Terms @("OPENAI_API_KEY", "DATABASE_URL", "APP_BASE_URL"))) {
    $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/config/env.example" -Section "variables" -Message "env.example 模板缺少第16章要求的基础变量入口样例。"
  }
}

if ($null -eq $envCheck) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/config/env-check.ps1" -Section "file" -Message "缺少 env-check 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $envCheck -Terms @("RequiredCommands", "RequiredEnvVars", "Environment check passed.", "变量用途、环境差异、部署注入方式和回滚策略应记录"))) {
    $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/config/env-check.ps1" -Section "env-check-shape" -Message "env-check 模板缺少第16章要求的命令/变量检查或文档桥接说明。"
  }
}

if ($null -eq $envTemplate) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/docs/env-and-deployment-template.md" -Section "file" -Message "缺少环境变量与部署模板。"
}
else {
  if (-not (Test-ContainsAll -Content $envTemplate -Terms @("环境变量清单", "构建与运行命令", "CI / CD 入口", "健康检查与发布约束", "配置变更前必须说明"))) {
    $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/docs/env-and-deployment-template.md" -Section "env-deploy-sections" -Message "环境与部署模板缺少第16章要求的变量、构建、CI/CD、健康检查或回滚章节。"
  }
}

if ($null -eq $newProjectUsage) {
  $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/docs/new-project-usage.md" -Section "file" -Message "缺少新项目使用指南模板。"
}
else {
  if (-not (Test-ContainsAll -Content $newProjectUsage -Terms @("env-check.ps1", "doctor.ps1", "install-user.ps1", "init-project.ps1"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/docs/new-project-usage.md" -Section "setup-commands" -Message "新项目使用指南还没有完整承接第16章的环境/检查入口。"
  }
}

if ($null -eq $codexReadme) {
  $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/config/codex-readme.md" -Section "file" -Message "缺少 Codex 控制面说明。"
}
else {
  if (-not (Test-ContainsAll -Content $codexReadme -Terms @("config.toml", "hooks.json", "task-run-profile.json"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/config/codex-readme.md" -Section "config-surface" -Message "Codex 控制面说明还没有完整覆盖配置面。"
  }
}

if ($null -eq $currentTask) {
  $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/context/CURRENT_TASK.md" -Section "file" -Message "缺少 CURRENT_TASK 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $currentTask -Terms @("必需环境变量 / Secret", "受影响配置文件", "构建 / 部署影响", "回滚配置策略"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/context/CURRENT_TASK.md" -Section "config-fields" -Message "CURRENT_TASK 模板缺少第16章要求的配置/环境决策字段。"
  }
}

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

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

exit $exitCode
