# Publish a Nexus POC update build to the CDN via Coolify.
# Never prints API tokens or secrets.
param(
  [Parameter(Mandatory = $true)]
  [int]$Build,
  [Parameter(Mandatory = $true)]
  [string]$Version,
  [string]$DownloadBaseUrl = "",
  [switch]$SkipUpload,
  [switch]$SkipGatewayDeploy,
  [switch]$DryRun,
  [switch]$Json
)

$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent $PSScriptRoot
$scriptsRoot = Join-Path $repoRoot "scripts\nexus-laptop-poc"
$evidenceDir = Join-Path $repoRoot "docs\evidence\nexus-auto-update-readiness-v1"
New-Item -ItemType Directory -Path $evidenceDir -Force | Out-Null

if (-not $DownloadBaseUrl) {
  $DownloadBaseUrl = if ($env:NEXUS_DOWNLOAD_BASE_URL) {
    $env:NEXUS_DOWNLOAD_BASE_URL.TrimEnd('/')
  } else {
    "https://nexus.ninjakernen.info/downloads"
  }
}

Write-Host "=== Nexus Update Publish (build $Build / $Version) ===" -ForegroundColor Cyan

$buildReport = & (Join-Path $scriptsRoot "build-installer.ps1") `
  -Version $Version -Build $Build -DownloadBaseUrl $DownloadBaseUrl

$distRoot = Join-Path $repoRoot "dist\nexus-laptop-poc"
$latestPath = Join-Path $distRoot "upload\downloads\latest.json"
if (-not (Test-Path $latestPath)) { throw "Build did not produce $latestPath" }

$manifest = Get-Content $latestPath -Raw | ConvertFrom-Json
$receipt = [ordered]@{
  scope           = "nexus_auto_update_publish"
  version         = $Version
  build           = $Build
  sha256Prefix    = ([string]$manifest.sha256).Substring(0, 12)
  sizeBytes       = $manifest.sizeBytes
  downloadBaseUrl = $DownloadBaseUrl
  builtAt         = (Get-Date).ToUniversalTime().ToString("o")
  uploadStatus    = "pending"
}

if (-not $SkipUpload) {
  $publishArgs = @{
    DistRoot         = $distRoot
    DownloadBaseUrl  = $DownloadBaseUrl
  }
  if ($DryRun) { $publishArgs.DryRun = $true }
  if ($Json) { $publishArgs.Json = $true }

  $publishReport = & (Join-Path $scriptsRoot "publish-coolify.ps1") @publishArgs
  $receipt.uploadStatus = $publishReport.uploadStatus
  $receipt.verify       = $publishReport.verify
  $receipt.deployUuid   = $publishReport.deployUuid
} else {
  $receipt.uploadStatus = "skipped"
}

if (-not $SkipGatewayDeploy -and -not $DryRun -and -not $SkipUpload) {
  $gatewayScript = Join-Path $repoRoot "scripts\coolify\deploy-nexus-downloads.ps1"
  if (Test-Path $gatewayScript) {
    Write-Host "Refreshing nexus-downloads nginx gateway..." -ForegroundColor Cyan
    try {
      & $gatewayScript -SkipPublish | Out-Null
      $receipt.gatewayDeploy = "triggered"
    } catch {
      $receipt.gatewayDeploy = "failed"
      $receipt.gatewayError = $_.Exception.Message
    }
  }
}

$receiptPath = Join-Path $evidenceDir "publish-receipt-build-$Build.json"
($receipt | ConvertTo-Json -Depth 8) | Set-Content -LiteralPath $receiptPath -Encoding UTF8
Copy-Item -LiteralPath $latestPath -Destination (Join-Path $evidenceDir "latest-manifest-build-$Build.json") -Force

Write-Host "Receipt: $receiptPath" -ForegroundColor Green
if ($Json) { $receipt | ConvertTo-Json -Depth 8 } else { $receipt | Format-List }
return $receipt
