# 实验: 给极简 STEP 注入 STYLED_ITEM 颜色实体 (测试 occt-import-js 对无颜色模型的兼容性)
# 用法: powershell -NoProfile -ExecutionPolicy Bypass -File tools\inject-colors.ps1 -In x.step -Out y.step
param([string]$In, [string]$Out)
$text = [System.IO.File]::ReadAllText($In)
$maxId = 0
foreach ($m in [regex]::Matches($text, '#(\d+)\s*=')) { $id = [int]$m.Groups[1].Value; if ($id -gt $maxId) { $maxId = $id } }
$next = $maxId + 1

# 收集实体 (保持文件顺序: 插入到 ENDSEC 前)
$solids = @()
foreach ($m in [regex]::Matches($text, '#(\d+)=MANIFOLD_SOLID_BREP')) { $solids += [int]$m.Groups[1].Value }

$newEntities = @()
$styledIds = @()
foreach ($s in $solids) {
  $newEntities += "#$next=COLOUR_RGB('',0.65,0.72,0.85);"
  $newEntities += "#$($next+1)=FILL_AREA_STYLE_COLOUR('',#$next);"
  $newEntities += "#$($next+2)=SURFACE_STYLE_FILL_AREA(#$($next+1));"
  $newEntities += "#$($next+3)=SURFACE_SIDE_STYLE('',(#$($next+2)));"
  $newEntities += "#$($next+4)=SURFACE_STYLE_USAGE(.BOTH.,#$($next+3));"
  $newEntities += "#$($next+5)=PRESENTATION_STYLE_ASSIGNMENT((#$($next+4)));"
  $newEntities += "#$($next+6)=STYLED_ITEM('',(#$($next+5)),#$s);"
  $styledIds += "#$($next+6)"
  $next += 7
}

# 把 STYLED_ITEM 追加进 SHAPE_REPRESENTATION 的 items 列表
$shapeRe = [regex]::Match($text, '#\d+=SHAPE_REPRESENTATION\('''',\(([^)]*)\),#\d+\);')
if (-not $shapeRe.Success) { Write-Output "未找到 SHAPE_REPRESENTATION"; exit 1 }
$oldItems = $shapeRe.Groups[2].Value
$newItems = $oldItems + ',' + ($styledIds -join ',')
$text = $text.Remove($shapeRe.Groups[2].Index, $shapeRe.Groups[2].Length).Insert($shapeRe.Groups[2].Index, $newItems)

$insert = ($newEntities -join "`r`n") + "`r`n"
$ends = $text.IndexOf('ENDSEC;', $text.IndexOf('ENDSEC;') + 7)   # 第二个 ENDSEC (DATA 结束)
$text = $text.Insert($ends, $insert)
[System.IO.File]::WriteAllText($Out, $text, (New-Object System.Text.UTF8Encoding($false)))
Write-Output ("已注入颜色: " + $solids.Count + " 个实体 → " + $Out)
