param(
    [ValidateSet("Release", "Debug")]
    [string]$Configuration = "Release",
    [string]$Runtime = "win-x64",
    [switch]$SelfContained,
    [switch]$SkipWebAssets
)

$commonScript = Join-Path $PSScriptRoot "script-common.ps1"
if (-not (Test-Path $commonScript)) {
    throw "Missing helper script: $commonScript"
}
. $commonScript

$repoRoot = Resolve-JournalRepoRoot -StartPath $PSScriptRoot
$gatewayProject = Resolve-JournalWebGatewayProjectPath -RepoRoot $repoRoot
$outputDir = Join-Path $repoRoot "output\webgateway"
$webBuildDir = Join-Path $repoRoot "Journal.App\build"
$webOutputDir = Join-Path $outputDir "wwwroot"

Clear-JournalProxyEnv
Initialize-JournalDotnetEnv -RepoRoot $repoRoot

Write-Host "Publishing Journal.WebGateway ($Configuration, $Runtime)..." -ForegroundColor Cyan
Write-Host "Project: $gatewayProject" -ForegroundColor DarkGray

$publishArgs = @(
    "publish", $gatewayProject,
    "-c", $Configuration,
    "-r", $Runtime,
    "--self-contained", ($SelfContained.IsPresent.ToString().ToLowerInvariant()),
    "-p:RestoreIgnoreFailedSources=true",
    "-p:NuGetAudit=false",
    "-o", $outputDir
)

& dotnet @publishArgs
if ($LASTEXITCODE -ne 0) {
    Write-Host "`nPublish failed with exit code $LASTEXITCODE" -ForegroundColor Red
    exit $LASTEXITCODE
}

if (-not $SkipWebAssets) {
    if (Test-Path $webBuildDir) {
        New-Item -ItemType Directory -Force -Path $webOutputDir | Out-Null
        Copy-Item -Path (Join-Path $webBuildDir "*") -Destination $webOutputDir -Recurse -Force
        Write-Host "Copied web assets to: $webOutputDir" -ForegroundColor Gray
    }
    else {
        Write-Warning "Journal.App build output not found at $webBuildDir. Run ./scripts/publish-app.ps1 -Target web first."
    }
}

Write-Host "`nPublish successful." -ForegroundColor Green
Write-Host "Output directory: $outputDir" -ForegroundColor Gray
