# STEP 结构自检：引用完整性 / 括号配平 / 纯 ASCII / 头尾结构
# 用法: powershell -NoProfile -ExecutionPolicy Bypass -File tools\verify-step.ps1
param(
  [string]$StepDir = (Join-Path $PSScriptRoot '..\onb-sc\step')
)

$files = Get-ChildItem $StepDir -Filter '*.step' | Sort-Object Name
$errors = @()
$checked = 0

foreach ($f in $files) {
  $text = [System.IO.File]::ReadAllText($f.FullName)
  $checked++

  # 1. 头尾结构
  if (-not $text.StartsWith('ISO-10303-21;')) { $errors += "$($f.Name): 缺少 ISO-10303-21 头" }
  if (-not $text.TrimEnd().EndsWith('END-ISO-10303-21;')) { $errors += "$($f.Name): 缺少 END-ISO-10303-21 尾" }
  if ($text -notmatch '(?s)HEADER;.*?ENDSEC;.*?DATA;.*?ENDSEC;') { $errors += "$($f.Name): HEADER/DATA 段结构异常" }

  # 2. 引用完整性: 所有被引用的 #id 都已定义
  $defined = @{}
  foreach ($m in [regex]::Matches($text, '#(\d+)\s*=')) { $defined[[int]$m.Groups[1].Value] = $true }
  foreach ($m in [regex]::Matches($text, '#(\d+)')) {
    $id = [int]$m.Groups[1].Value
    if (-not $defined.ContainsKey($id)) { $errors += "$($f.Name): 引用了未定义的 #$id"; break }
  }

  # 3. 括号配平 (排除文本单引号内的内容后逐字符统计)
  $noStr = [regex]::Replace($text, "'[^']*'", "''")
  $open = ([regex]::Matches($noStr, '\(')).Count
  $close = ([regex]::Matches($noStr, '\)')).Count
  if ($open -ne $close) { $errors += "$($f.Name): 括号不配平 ($open/$close)" }

  # 4. 纯 ASCII (STEP 交换格式要求)
  foreach ($ch in $text.ToCharArray()) {
    if ([int]$ch -gt 127) { $errors += "$($f.Name): 存在非 ASCII 字符"; break }
  }

  # 5. 实体计数: 单杆 4x(36+7色) + 尾部14 = 186; 双杆 5x(36+7色) + 14 = 229
  $entityCount = ([regex]::Matches($text, '#\d+\s*=')).Count
  if ($entityCount -ne 186 -and $entityCount -ne 229) { $errors += "$($f.Name): 实体数异常 ($entityCount, 期望 186/229)" }
}

Write-Output "检查文件数: $checked"
if ($errors.Count -eq 0) {
  Write-Output "全部通过: 引用完整 / 括号配平 / 纯 ASCII / 结构正常"
} else {
  Write-Output "发现问题 $($errors.Count) 条:"
  $errors | ForEach-Object { Write-Output "  - $_" }
}
