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
}

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

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

  return $false
}

$issues = @()

$directoryTemplatePath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\docs\directory-structure-template.md"
$repoMapPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\context\repo-map.md"
$currentTaskPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\context\CURRENT_TASK.md"
$projectAgentsTemplatePath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\docs\project-agents-template.md"

$directoryTemplate = Get-FileContentOrNull -Path $directoryTemplatePath
$repoMap = Get-FileContentOrNull -Path $repoMapPath
$currentTask = Get-FileContentOrNull -Path $currentTaskPath
$projectAgentsTemplate = Get-FileContentOrNull -Path $projectAgentsTemplatePath

if ($null -eq $directoryTemplate) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/docs/directory-structure-template.md" -Section "file" -Message "缺少目录结构模板，无法承载第四章目录规范。"
}
else {
  if (-not (Test-ContainsAll -Content $directoryTemplate -Terms @("新文件放置规则", "禁止新增的目录名", "新增目录前必须回答", "业务域组织规则"))) {
    $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/docs/directory-structure-template.md" -Section "directory-rules" -Message "目录结构模板缺少文件放置规则、禁止目录名、目录新增理由或业务域组织规则。"
  }
}

if ($null -eq $repoMap) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/context/repo-map.md" -Section "file" -Message "缺少 repo-map 模板，无法索引目录规则。"
}
else {
  if (-not (Test-ContainsAll -Content $repoMap -Terms @("关键目录", "子目录规则索引"))) {
    $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/context/repo-map.md" -Section "directory-index" -Message "repo-map 模板缺少关键目录或子目录规则索引。"
  }
}

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 "directory-decision-fields" -Message "CURRENT_TASK 模板缺少目录变更相关的模块归属或复用决策字段。"
  }
}

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-ContainsAny -Content $projectAgentsTemplate -Terms @("禁止新增 utils2、common2、helper2", "目录独有的模块职责", '子目录 `AGENTS.md`'))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/docs/project-agents-template.md" -Section "directory-guidance" -Message "project AGENTS 模板对目录结构问题的约束仍不够直给。"
  }
}

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

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

exit $exitCode
