# Deploy nexus-downloads gateway via post_deployment (Coolify PATCH dockerfile often returns 422).
param(
    [switch]$Json,
    [switch]$DryRun,
    [switch]$SkipPublish,
    [switch]$SkipWebsite,
    [string]$BackendHost = ""
)

$ErrorActionPreference = "Stop"
Write-Host "=== deploy-nexus-downloads ===" -ForegroundColor Cyan
. (Join-Path $PSScriptRoot "_lib\CoolifyApi.ps1")
Initialize-CoolifyEnv -AllowSecretScript

$repoRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot)
$deployDir = Join-Path $repoRoot "deployment\coolify\nexus-downloads"
$domainUrl = Get-NexusDomainUrl

$report = [ordered]@{
    scope  = "deploy_nexus_downloads"
    dryRun = [bool]$DryRun
    domain = $env:NEXUS_DOMAIN
}

function Get-TempFileDownloadUrl {
    param([string]$FilePath)
    return Get-CatboxUploadUrl -FilePath $FilePath
}

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

$backend = Get-CoolifyApplicationByName -Name "nexus-backend"
if (-not $BackendHost -and $backend) {
    $BackendHost = "$($backend.uuid).85.208.48.244.sslip.io"
}
if (-not $BackendHost) {
    throw "Set -BackendHost or deploy nexus-backend first."
}
$report.backendHost = $BackendHost

if ($DryRun) {
    $report.deploy = "dry_run"
    if ($Json) { $report | ConvertTo-Json -Depth 5 } else { $report | Format-List }
    return $report
}

$nginx = (Get-Content (Join-Path $deployDir "nginx.conf") -Raw)
$nginx = $nginx.Replace('${NEXUS_BACKEND_HOST}', $BackendHost)
$nginx = $nginx.Replace('${NEXUS_BACKEND_HOST_HEADER}', $BackendHost)
$tmpNginx = Join-Path $env:TEMP "nexus-nginx-$([Guid]::NewGuid().ToString('N')).conf"
[System.IO.File]::WriteAllText($tmpNginx, $nginx)

$uploadRoot = Join-Path $repoRoot "dist\nexus-laptop-poc\upload"
$latest = Join-Path $uploadRoot "downloads\latest.json"
$setupUpload = Join-Path $uploadRoot "downloads\NexusSetup.exe"
if (-not (Test-Path $latest) -or -not (Test-Path $setupUpload)) {
    & (Join-Path $repoRoot "scripts\nexus-laptop-poc\build-installer.ps1") | Out-Null
}
if (-not $SkipPublish) {
    & (Join-Path $PSScriptRoot "restore-historical-releases.ps1") | Out-Null
}
& (Join-Path $PSScriptRoot "generate-releases-json.ps1") | Out-Null
$version = (Get-Content $latest -Raw | ConvertFrom-Json).version

$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
    if (-not (Test-Path "node_modules")) { npm ci | Out-Null }
    npm run build | Out-Null
    Pop-Location
    if (-not (Test-Path $outDir)) { throw "nexus-web out/ missing after build" }
    $siteTar = Join-Path $env:TEMP "nexus-web-site-$([Guid]::NewGuid().ToString('N')).tar.gz"
    Push-Location $outDir
    tar -czf $siteTar *
    Pop-Location
    $siteTarUrl = Get-TempFileDownloadUrl $siteTar
    $report.websiteExport = "built"
}

$parts = @(
    "wget -qO /etc/nginx/conf.d/default.conf '$(Get-TempFileDownloadUrl $tmpNginx)'"
    "wget -qO /usr/share/nginx/html/health.json '$(Get-TempFileDownloadUrl (Join-Path $deployDir 'www\health.json'))'"
    "mkdir -p /usr/share/nginx/html/downloads"
    "wget -qO /usr/share/nginx/html/downloads/releases.json '$(Get-TempFileDownloadUrl (Join-Path $deployDir 'www\downloads\releases.json'))'"
    "mkdir -p /usr/share/nginx/html/downloads/releases/$version"
)
if ($siteTarUrl) {
    $parts += @(
        "mkdir -p /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/"
    )
}
$fileMap = @(
    @{ Local = $latest; Remote = "/usr/share/nginx/html/downloads/latest.json" }
    @{ Local = Join-Path $uploadRoot "downloads\sha256.txt"; Remote = "/usr/share/nginx/html/downloads/sha256.txt" }
    @{ Local = Join-Path $uploadRoot "downloads\nexus-shell-poc.zip"; Remote = "/usr/share/nginx/html/downloads/nexus-shell-poc.zip" }
    @{ Local = $setupUpload; Remote = "/usr/share/nginx/html/downloads/NexusSetup.exe" }
)

$devPackDir = Join-Path $repoRoot "dist\nexus-dev-pack\upload\downloads\dev-pack"
if (Test-Path (Join-Path $devPackDir "ninja-nexus-dev-pack.zip")) {
    $parts += "mkdir -p /usr/share/nginx/html/downloads/dev-pack"
    foreach ($name in @("ninja-nexus-dev-pack.zip", "dev-pack.json", "sha256.txt")) {
        $local = Join-Path $devPackDir $name
        if (Test-Path $local) {
            $fileMap += @{ Local = $local; Remote = "/usr/share/nginx/html/downloads/dev-pack/$name" }
        }
    }
}

$releasesRoot = Join-Path $uploadRoot "downloads\releases"
if (Test-Path $releasesRoot) {
    Get-ChildItem -LiteralPath $releasesRoot -Directory | ForEach-Object {
        $ver = $_.Name
        $parts += "mkdir -p /usr/share/nginx/html/downloads/releases/$ver"
        foreach ($name in @("nexus-shell-poc.zip", "sha256.txt", "manifest.json", "NexusSetup.exe")) {
            $local = Join-Path $_.FullName $name
            if (Test-Path $local) {
                $fileMap += @{ Local = $local; Remote = "/usr/share/nginx/html/downloads/releases/$ver/$name" }
            }
        }
    }
}
$report.uploadFiles = @()
foreach ($f in $fileMap) {
    if (Test-Path $f.Local) {
        Write-Host "Staging $($f.Remote) ..." -ForegroundColor DarkGray
        $url = Get-TempFileDownloadUrl $f.Local
        $parts += "wget -qO $($f.Remote) '$url'"
        $report.uploadFiles += $f.Remote
    }
}

$post = ($parts -join " && ") + " && nginx -t && kill -HUP 1"
$report.postCommandLength = $post.Length
Write-Host "Post-deploy command length: $($post.Length) chars, $($report.uploadFiles.Count) files" -ForegroundColor DarkGray
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 6 } else { $report | Format-List }
return $report
