# 一键编译发布 (M3): 校验数据包 → 编译客户版 exe (数据内置) → 生成光盘/USB 目录 + 增量更新包
# 用法: powershell -NoProfile -ExecutionPolicy Bypass -File tools\publish.ps1 [-Opc 数据包.opc] [-Version 2026.08]
param(
  [string]$Opc = (Join-Path $PSScriptRoot '..\sample\OnebotCatalog_2026.08.opc'),
  [string]$Version = '2026.08'
)

$root = Split-Path $PSScriptRoot -Parent
$exeDev = Join-Path $root 'bin\OnebotCatalog.exe'
$exeCus = Join-Path $root 'bin\OnebotCatalog-Customer.exe'
$selftestLog = Join-Path (Split-Path $Opc -Parent) 'selftest.log'

# 1) 数据包校验 (校验不过不允许发布)
if (-not (Test-Path $Opc)) { Write-Output "数据包不存在: $Opc"; exit 1 }
if (-not (Test-Path $exeDev)) { Write-Output "开发版不存在, 请先 build.ps1"; exit 1 }
Start-Process -FilePath $exeDev -ArgumentList @('--selftest', $Opc) -Wait | Out-Null
if (-not (Test-Path $selftestLog)) { Write-Output "自测日志缺失, 发布中止"; exit 1 }
$log = Get-Content $selftestLog -Raw -Encoding UTF8
if ($log -match '结果: (\d+) 通过, (\d+) 失败') {
  $failCount = [int]$Matches[2]
  if ($failCount -gt 0) { Write-Output "自测未通过 ($failCount 失败), 发布中止"; exit 1 }
  Write-Output ("[1/4] 数据包自测通过: " + $Matches[1] + " 项")
} else { Write-Output "自测日志格式异常, 发布中止"; exit 1 }

# 2) 编译客户版 (CUSTOMER_BUILD + 嵌入数据 + 图标)
& powershell -NoProfile -ExecutionPolicy Bypass -File (Join-Path $PSScriptRoot 'build.ps1') -Customer -Opc $Opc
if (-not (Test-Path $exeCus)) { Write-Output "客户版编译失败"; exit 1 }
Write-Output "[2/4] 客户版编译完成"

# 3) 发布目录 (光盘/USB 结构)
$relDir = Join-Path $root ("release\OnebotCatalog_" + $Version)
New-Item -ItemType Directory -Force -Path $relDir | Out-Null
Copy-Item $exeCus (Join-Path $relDir 'OnebotCatalog.exe') -Force
Copy-Item $Opc (Join-Path $relDir 'catalog.opc') -Force
# 开源 3D 渲染库 Helix Toolkit DLL (窗口内直渲 STL 网格用)
Get-ChildItem (Join-Path $root 'lib\*.dll') -ErrorAction SilentlyContinue | ForEach-Object { Copy-Item $_.FullName $relDir -Force }
if (Test-Path (Join-Path $root 'assets\icon.ico')) { Copy-Item (Join-Path $root 'assets\icon.ico') $relDir -Force }
[System.IO.File]::WriteAllText((Join-Path $relDir 'autorun.inf'),
  "[autorun]`r`nopen=OnebotCatalog.exe`r`nicon=OnebotCatalog.exe,0`r`n", [System.Text.Encoding]::ASCII)
[System.IO.File]::WriteAllText((Join-Path $relDir 'README_zh.txt'),
  "欧霓博气动元件电子目录 " + $Version + "`r`n`r`n双击 OnebotCatalog.exe 运行 (Win10/11 免安装)。`r`nWin10/11 默认禁用自动播放, 请手动双击运行。`r`n`r`n目录更新: 用新版本 catalog.opc 替换本目录中的同名文件即可。`r`n`r`n常见问题: 若杀毒软件拦截, 请将程序加入白名单 (本软件无签名)。`r`n", (New-Object System.Text.UTF8Encoding($true)))
[System.IO.File]::WriteAllText((Join-Path $relDir 'README_en.txt'),
  "ONEBOT Pneumatic Catalog " + $Version + "`r`n`r`nDouble-click OnebotCatalog.exe to run (no installation, Win10/11).`r`nAutoplay is disabled by default on Win10/11 - run the exe manually.`r`n`r`nUpdate: replace catalog.opc with the new version.`r`n`r`nNote: unsigned software may trigger antivirus warnings - add to allow list if needed.`r`n", (New-Object System.Text.UTF8Encoding($true)))
Write-Output "[3/4] 发布目录: $relDir"

# 3.5) 附带本机 3D 查看器组件 (真实数模浏览器预览用; 剔除 samples/uploads/step 非必要目录, ~8MB)
$vSrc = Join-Path $root 'viewer\STEPViewer'
if (Test-Path $vSrc) {
  $vDst = Join-Path $relDir 'viewer\STEPViewer'
  New-Item -ItemType Directory -Force -Path $vDst | Out-Null
  Copy-Item (Join-Path $vSrc '*.html'), (Join-Path $vSrc '*.js'), (Join-Path $vSrc '*.css'), (Join-Path $vSrc '*.ico'), (Join-Path $vSrc '*.txt') $vDst -Force -ErrorAction SilentlyContinue
  foreach ($sub in @('icons', 'libs', 'api')) {
    Copy-Item (Join-Path $vSrc $sub) $vDst -Recurse -Force -ErrorAction SilentlyContinue
  }
  Write-Output "      查看器组件已附带 (~$([Math]::Round((Get-ChildItem $vDst -Recurse -File | Measure-Object Length -Sum).Sum / 1MB, 1)) MB)"
}

# 4) 增量更新包 (仅数据包)
$updDir = Join-Path $root ("release\update_" + $Version)
New-Item -ItemType Directory -Force -Path $updDir | Out-Null
Copy-Item $Opc (Join-Path $updDir 'catalog.opc') -Force
Write-Output "[4/5] 增量更新包: $updDir (仅替换 catalog.opc 即可升级)"

# 5) 在线发布 (静态站点): 解包 .opc 数据 + 前端页面 → 整目录上传即上线
# 发布前必须先停 serve-web (占用站点目录文件句柄); 删除带重试, 防句柄未释放的竞态
Add-Type -AssemblyName System.IO.Compression.FileSystem
$webDir = Join-Path $root ("release\web_" + $Version)
for ($try = 0; $try -lt 6 -and (Test-Path $webDir); $try++) {
  try { Remove-Item -Recurse -Force $webDir -ErrorAction Stop }
  catch { Start-Sleep -Seconds 2 }
}
if (Test-Path $webDir) { Write-Output "站点目录删除失败 (被占用), 请关闭预览服务器/浏览器后重试"; exit 1 }
New-Item -ItemType Directory -Force -Path $webDir | Out-Null
[System.IO.Compression.ZipFile]::ExtractToDirectory($Opc, $webDir)
Copy-Item (Join-Path $root 'web\*') $webDir -Recurse -Force
Write-Output "[5/5] 在线站点: $webDir (整目录上传到网站根目录即上线; 本地预览: tools\serve-web.ps1)"

# 6) 网格预览侧车 (窗口内 3D 开源 Helix 渲染用): 源 onebot-data\catalog\mesh → 开发包旁 sample\mesh + 客户目录 mesh\
$meshSrc = Join-Path $root 'onebot-data\catalog\mesh'
if (Test-Path $meshSrc) {
  $meshDev = Join-Path (Split-Path $Opc -Parent) 'mesh'
  robocopy $meshSrc $meshDev /MIR /NJH /NJS /NFL /NDL | Out-Null
  $meshRel = Join-Path $relDir 'mesh'
  robocopy $meshSrc $meshRel /MIR /NJH /NJS /NFL /NDL | Out-Null
  Write-Output ("[6/6] 网格预览侧车已同步 (窗口内 3D): mesh\ " + (Get-ChildItem $meshSrc -File).Count + " 文件")
}

Get-ChildItem $relDir | ForEach-Object { Write-Output ("  " + $_.Name + "  " + [Math]::Round($_.Length / 1KB) + " KB") }
Write-Output "发布完成 ✔ (离线 + 增量 + 在线三份产物)"
