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

$traceFormatPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\docs\trace-format.md"
$traceSchemaPath = Join-Path $ProjectRoot "docs\codex-harness-engineering\templates\trace\trace.schema.json"
$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"

$traceFormat = Get-FileContentOrNull -Path $traceFormatPath
$traceSchema = Get-FileContentOrNull -Path $traceSchemaPath
$evidenceProtocol = Get-FileContentOrNull -Path $evidenceProtocolPath
$currentTask = Get-FileContentOrNull -Path $currentTaskPath

if ($null -eq $traceFormat) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/docs/trace-format.md" -Section "file" -Message "缺少 trace-format 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $traceFormat -Terms @("可观测性最低要求", "请求 ID", "用户 ID / actor", "接口路径或业务入口", "失败原因", "耗时", "审计记录", "告警或失败通知"))) {
    $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/docs/trace-format.md" -Section "observability-fields" -Message "trace-format 模板缺少第17章要求的日志与可观测性最低字段。"
  }
}

if ($null -eq $traceSchema) {
  $issues += New-Issue -Severity "error" -File "docs/codex-harness-engineering/templates/trace/trace.schema.json" -Section "file" -Message "缺少 trace schema 模板。"
}
else {
  if (-not (Test-ContainsAll -Content $traceSchema -Terms @("qa_evidence", "failure_repro", "events_file", "log_files", "evidence_files"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/trace/trace.schema.json" -Section "trace-shape" -Message "trace schema 模板还没有完整暴露可观测性相关证据面。"
  }
}

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 @("request_trace_sample", "alert_evidence", "audit_log"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/testing/EVIDENCE_PROTOCOL.md" -Section "observability-evidence" -Message "证据协议模板缺少第17章要求的请求追踪、告警或审计证据类型。"
  }
}

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 @("日志 / trace 字段要求", "观测指标 / 告警策略"))) {
    $issues += New-Issue -Severity "warning" -File "docs/codex-harness-engineering/templates/context/CURRENT_TASK.md" -Section "observability-fields" -Message "CURRENT_TASK 模板缺少第17章要求的日志或告警决策字段。"
  }
}

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

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

exit $exitCode
