# Publish only the Ninja Nexus Dev Pack and download page/chrome to nexus-downloads.
param(
    [switch]$Json,
    [switch]$DryRun,
    [switch]$SkipBuild,
    [switch]$SkipWebsite
)

$ErrorActionPreference = "Stop"
Write-Host "=== publish-dev-pack-coolify ===" -ForegroundColor Cyan

. (Join-Path (Split-Path -Parent $PSScriptRoot) "coolify\_lib\CoolifyApi.ps1")
Initialize-CoolifyEnv -AllowSecretScript

$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$deployDir = Join-Path $repoRoot "deployment\coolify\nexus-downloads"
$devPackScript = Join-Path $PSScriptRoot "build-dev-pack.ps1"
$devPackDir = Join-Path $repoRoot "dist\nexus-dev-pack\upload\downloads\dev-pack"
$domainUrl = Get-NexusDomainUrl

if (-not $SkipBuild) {
    & $devPackScript -DownloadBaseUrl "$domainUrl/downloads" | Out-Null
}

$zipPath = Join-Path $devPackDir "ninja-nexus-dev-pack.zip"
$manifestPath = Join-Path $devPackDir "dev-pack.json"
$shaPath = Join-Path $devPackDir "sha256.txt"
foreach ($path in @($zipPath, $manifestPath, $shaPath)) {
    if (-not (Test-Path -LiteralPath $path)) {
        throw "Missing dev pack artifact: $path"
    }
}

$downloads = Get-CoolifyApplicationByName -Name "nexus-downloads"
if (-not $downloads) { throw "nexus-downloads app not found in Coolify." }

$report = [ordered]@{
    scope     = "publish_dev_pack"
    dryRun    = [bool]$DryRun
    appUuid   = $downloads.uuid
    domain    = $env:NEXUS_DOMAIN
    devPack   = Get-Content -LiteralPath $manifestPath -Raw | ConvertFrom-Json
}

if ($DryRun) {
    if ($Json) { $report | ConvertTo-Json -Depth 8 } else { $report | Format-List }
    return $report
}

$nginx = Get-Content (Join-Path $deployDir "nginx.conf") -Raw
$backend = Get-CoolifyApplicationByName -Name "nexus-backend"
$backendHost = if ($backend) { "$($backend.uuid).85.208.48.244.sslip.io" } else { "127.0.0.1" }
$nginx = $nginx.Replace('${NEXUS_BACKEND_HOST}', $backendHost)
$nginx = $nginx.Replace('${NEXUS_BACKEND_HOST_HEADER}', $backendHost)
$tmpNginx = Join-Path $env:TEMP "nexus-dev-pack-nginx-$([Guid]::NewGuid().ToString('N')).conf"
[System.IO.File]::WriteAllText($tmpNginx, $nginx)

$parts = @(
    "wget -qO /etc/nginx/conf.d/default.conf '$(Get-CatboxUploadUrl -FilePath $tmpNginx)'"
    "mkdir -p /usr/share/nginx/html/downloads/dev-pack"
)

$siteTarUrl = $null
if (-not $SkipWebsite) {
    $webDir = Join-Path $repoRoot "apps\nexus-web"
    $outDir = Join-Path $webDir "out"
    Write-Host "Building nexus-web static export..." -ForegroundColor Cyan
    Push-Location $webDir
    try {
        if (-not (Test-Path "node_modules")) { npm ci | Out-Null }
        npm run build | Out-Null
    } finally {
        Pop-Location
    }

    if (-not (Test-Path $outDir)) { throw "nexus-web out/ missing after build" }
    $siteTar = Join-Path $env:TEMP "nexus-web-devpack-site-$([Guid]::NewGuid().ToString('N')).tar.gz"
    Push-Location $outDir
    try {
        tar -czf $siteTar *
    } finally {
        Pop-Location
    }

    $siteTarUrl = Get-CatboxUploadUrl -FilePath $siteTar
    $parts += @(
        "mkdir -p /tmp/nexus-web-site"
        "rm -rf /tmp/nexus-web-site/*"
        "wget -qO /tmp/nexus-web-site/site.tar.gz '$siteTarUrl'"
        "tar -xzf /tmp/nexus-web-site/site.tar.gz -C /tmp/nexus-web-site"
        "cp -r /tmp/nexus-web-site/* /usr/share/nginx/html/"
    )
    $report.websiteExport = "built"
}

$fileMap = @(
    @{ Local = $zipPath; Remote = "/usr/share/nginx/html/downloads/dev-pack/ninja-nexus-dev-pack.zip" }
    @{ Local = $manifestPath; Remote = "/usr/share/nginx/html/downloads/dev-pack/dev-pack.json" }
    @{ Local = $shaPath; Remote = "/usr/share/nginx/html/downloads/dev-pack/sha256.txt" }
    @{ Local = Join-Path $deployDir "www\downloads\index.html"; Remote = "/usr/share/nginx/html/downloads/index.html" }
)

$report.uploadFiles = @()
foreach ($f in $fileMap) {
    Write-Host "Staging $($f.Remote) ..." -ForegroundColor DarkGray
    $url = Get-CatboxUploadUrl -FilePath $f.Local
    $parts += "wget -qO $($f.Remote) '$url'"
    $report.uploadFiles += $f.Remote
}

$post = ($parts -join " && ") + " && nginx -t && kill -HUP 1"
$report.postCommandLength = $post.Length

Invoke-CoolifyApi -Method Patch -Path "/api/v1/applications/$($downloads.uuid)" -Body @{
    post_deployment_command = $post
} | Out-Null

Invoke-CoolifyApi -Method Get -Path "/api/v1/deploy?uuid=$($downloads.uuid)&force=true" | Out-Null
$report.gatewayDeploy = "triggered"

Write-Host "Waiting for gateway deploy..." -ForegroundColor Cyan
Start-Sleep -Seconds 85

$app = Invoke-CoolifyApi -Method Get -Path "/api/v1/applications/$($downloads.uuid)"
$report.appStatus = $app.status

if ($Json) { $report | ConvertTo-Json -Depth 8 } else { $report | Format-List }
return $report
