# Generate downloads/releases.json from archived build manifests in evidence.
param(
    [string]$EvidenceDir = "",
    [string]$OutputPath = "",
    [int]$MaxReleases = 3
)

$ErrorActionPreference = "Stop"
$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$uploadRoot = Join-Path $repoRoot "dist\nexus-laptop-poc\upload\downloads"
if (-not $EvidenceDir) {
    $EvidenceDir = Join-Path $repoRoot "docs\evidence\nexus-auto-update-readiness-v1"
}
if (-not $OutputPath) {
    $OutputPath = Join-Path $repoRoot "deployment\coolify\nexus-downloads\www\downloads\releases.json"
}

$manifestFiles = Get-ChildItem -LiteralPath $EvidenceDir -Filter "latest-manifest-build-*.json" -File -ErrorAction SilentlyContinue
if (-not $manifestFiles -or $manifestFiles.Count -eq 0) {
    throw "No latest-manifest-build-*.json files found in $EvidenceDir"
}

$releaseList = New-Object System.Collections.Generic.List[object]
foreach ($file in $manifestFiles) {
    $m = Get-Content -LiteralPath $file.FullName -Raw | ConvertFrom-Json
    $distManifest = Join-Path $uploadRoot "releases\$($m.version)\manifest.json"
    if (Test-Path $distManifest) {
        $live = Get-Content -LiteralPath $distManifest -Raw | ConvertFrom-Json
        if ($live.sha256) { $m.sha256 = $live.sha256 }
        if ($live.sizeBytes) { $m.sizeBytes = $live.sizeBytes }
        if ($live.packageUrl) { $m.packageUrl = $live.packageUrl }
        if ($live.publishedAt) { $m.publishedAt = $live.publishedAt }
        if ($live.installerSha256) { $m.installerSha256 = $live.installerSha256 }
        if ($live.installerSizeBytes) { $m.installerSizeBytes = $live.installerSizeBytes }
    }
    $releaseList.Add([ordered]@{
        build              = [int]$m.build
        version            = [string]$m.version
        publishedAt        = [string]$m.publishedAt
        packageUrl         = [string]$m.packageUrl
        sha256Url          = if ($m.sha256Url) { [string]$m.sha256Url } else { $null }
        sha256             = [string]$m.sha256
        sizeBytes          = [long]$m.sizeBytes
        installerUrl       = if ($m.installerUrl) { [string]$m.installerUrl } else { $null }
        installerSha256    = if ($m.installerSha256) { [string]$m.installerSha256 } else { $null }
        installerSizeBytes = if ($m.installerSizeBytes) { [long]$m.installerSizeBytes } else { $null }
        notes              = @($m.notes)
        releaseNotes       = @($m.releaseNotes)
        manifestPath       = "/downloads/releases/$($m.version)/manifest.json"
    }) | Out-Null
}
$releases = $releaseList | Sort-Object -Property build -Descending | Select-Object -First $MaxReleases

$payload = [ordered]@{
    product      = "Ninja Nexus"
    channel      = "poc"
    generatedAt  = (Get-Date).ToUniversalTime().ToString("o")
    latestJson   = "/downloads/latest.json"
    releases     = $releases
}

$dir = Split-Path -Parent $OutputPath
if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null }
$json = $payload | ConvertTo-Json -Depth 8
[System.IO.File]::WriteAllText($OutputPath, $json, (New-Object System.Text.UTF8Encoding $false))
Write-Host "Wrote $($releases.Count) releases to $OutputPath" -ForegroundColor Green
return $OutputPath
