$ErrorActionPreference = 'Stop'
$projectRoot = 'D:\work\projects\360id'
$outputRoot = Join-Path $projectRoot 'out_v4'
$reportRoot = 'D:\ai-deck\reports\360id-scanner-4.0.0-TRUSS'
$zipPath = Join-Path $outputRoot 'TRUSS-scanner-v4.0.0-TRUSS.zip'

if (Test-Path -LiteralPath $reportRoot) { throw "Refusing to overwrite $reportRoot" }
New-Item -ItemType Directory -Path $reportRoot | Out-Null
New-Item -ItemType Directory -Path (Join-Path $reportRoot 'source') | Out-Null
New-Item -ItemType Directory -Path (Join-Path $reportRoot 'vendor') | Out-Null

$topFiles = @(
  'TRUSS_dual_mid360_scanner_v4.0.0.FCStd',
  'TRUSS_dual_mid360_scanner_v4.0.0.step',
  'TRUSS_dual_mid360_scanner_v4.0.0.stl',
  'BOM.csv','design-manifest.json','interference-report.json','verification.json','SHA256SUMS.txt','REPORT.md','index.html',
  'browser-overview.png','browser-hinge-closeup.png','browser-lidar-60deg.png','browser-public-oa.png',
  'section-thread-boss-x190.png','section-sensor-pyramid-y0.png','section-thin-wall-y-100.png'
)
foreach ($name in $topFiles) {
  $source = Join-Path $outputRoot $name
  if (-not (Test-Path -LiteralPath $source)) { throw "Missing required release file: $source" }
  Copy-Item -LiteralPath $source -Destination (Join-Path $reportRoot $name)
}
Copy-Item -LiteralPath (Join-Path $outputRoot 'parts') -Destination $reportRoot -Recurse
Copy-Item -LiteralPath (Join-Path $outputRoot 'viewer_meshes') -Destination $reportRoot -Recurse
Copy-Item -LiteralPath (Join-Path $outputRoot 'viewer') -Destination $reportRoot -Recurse
Copy-Item -LiteralPath (Join-Path $projectRoot 'vendor\livox-mid360-official.stp') -Destination (Join-Path $reportRoot 'vendor\livox-mid360-official.stp')

$sourceFiles = @('build_scanner_v4.py','run_v4_trace.py','validate_real_outputs.py','mcp-validate-request.jsonl','mcp-section-request.jsonl','package_release.ps1')
foreach ($name in $sourceFiles) {
  Copy-Item -LiteralPath (Join-Path $projectRoot "v4\$name") -Destination (Join-Path $reportRoot "source\$name")
}

if (Test-Path -LiteralPath $zipPath) { Remove-Item -LiteralPath $zipPath -Force }
Compress-Archive -Path (Join-Path $reportRoot '*') -DestinationPath $zipPath -CompressionLevel Optimal
Copy-Item -LiteralPath $zipPath -Destination (Join-Path $reportRoot 'TRUSS-scanner-v4.0.0-TRUSS.zip')
$hash = (Get-FileHash -LiteralPath $zipPath -Algorithm SHA256).Hash.ToLowerInvariant()
$line = "$hash  TRUSS-scanner-v4.0.0-TRUSS.zip`r`n"
Set-Content -LiteralPath (Join-Path $outputRoot 'PACKAGE-SHA256.txt') -Value $line -Encoding ascii
Set-Content -LiteralPath (Join-Path $reportRoot 'PACKAGE-SHA256.txt') -Value $line -Encoding ascii

[pscustomobject]@{
  Version='4.0.0-TRUSS'
  ReportRoot=$reportRoot
  Zip=$zipPath
  ZipBytes=(Get-Item $zipPath).Length
  ZipSHA256=$hash
  ReportFiles=(Get-ChildItem $reportRoot -File -Recurse).Count
}|ConvertTo-Json
