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"
$designBriefPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\design\design-brief.md"
$frontendQualityPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\docs\frontend-quality-rules.md"
$prdPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\product\prd-lite.md"
$currentTaskPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\context\CURRENT_TASK.md"

$frontendArchitecture = Get-FileContentOrNull -Path $frontendArchitecturePath
$designBrief = Get-FileContentOrNull -Path $designBriefPath
$frontendQuality = Get-FileContentOrNull -Path $frontendQualityPath
$prd = Get-FileContentOrNull -Path $prdPath
$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 @('## 9. 性能预算', '列表行数', '首屏依赖', '图片 / 图标', 'client / server / virtualized'))) {
    $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/design/frontend-architecture.md" -Section "frontend-performance" -Message "frontend-architecture 模板缺少第15章要求的前端性能预算字段。"
  }
}

if ($null -eq $designBrief) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/design/design-brief.md" -Section "file" -Message "缺少 design-brief 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $designBrief -Terms @('## 11.1 性能预算', '首屏依赖', '列表 / 表格规模', '数据刷新频率'))) {
    $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/design/design-brief.md" -Section "design-performance" -Message "design-brief 模板缺少第15章要求的 UI 性能预算项。"
  }
}

if ($null -eq $frontendQuality) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/docs/frontend-quality-rules.md" -Section "file" -Message "缺少 frontend-quality-rules 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $frontendQuality -Terms @('## 8. 性能预算', '首屏依赖过多组件、图标、图表或动画库', '表格超过 100 行、复杂筛选、虚拟滚动或服务端分页需求', '性能风险检查结论'))) {
    $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/docs/frontend-quality-rules.md" -Section "ui-performance-rules" -Message "frontend-quality-rules 模板缺少第15章要求的前端性能风险与证据规则。"
  }
}

if ($null -eq $prd) {
  $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/product/prd-lite.md" -Section "file" -Message "缺少 PRD-Lite 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $prd -Terms @('| 性能 |', '| 安全 |', '| 可用性 |'))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/product/prd-lite.md" -Section "nfr-performance" -Message "PRD-Lite 模板还没有把性能作为明确的非功能需求入口。"
  }
}

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 @('前端性能预算', '后端性能策略（索引 / 缓存 / 分页 / N+1）', '弱网 / 离线 / 大数据量策略'))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/context/CURRENT_TASK.md" -Section "performance-fields" -Message "CURRENT_TASK 模板缺少第15章要求的性能决策字段。"
  }
}

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

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

exit $exitCode
