param(
    [string]$Configuration = "Release",
    [string]$Runtime = "win-x64"
)

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

$repoRoot = Resolve-JournalRepoRoot -StartPath $PSScriptRoot
$csproj = Resolve-JournalSidecarProjectPath -RepoRoot $repoRoot
$outputDir = Join-Path $repoRoot "output"

# Setup local dotnet environment (matches dotnet-min.ps1 logic)
Clear-JournalProxyEnv
Initialize-JournalDotnetEnv -RepoRoot $repoRoot

Write-Host "Publishing Journal.Sidecar ($Configuration, $Runtime)..." -ForegroundColor Cyan
Write-Host "Using project: $csproj" -ForegroundColor DarkGray

$publishArgs = @(
    "publish", $csproj,
    "-c", $Configuration,
    "-r", $Runtime,
    "--self-contained",
    "-p:PublishSingleFile=true",
    "-p:IncludeNativeLibrariesForSelfExtract=true",
    "-p:RestoreIgnoreFailedSources=true",
    "-p:NuGetAudit=false",
    "-o", $outputDir
)

& dotnet @publishArgs

if ($LASTEXITCODE -eq 0) {
    $binaryName = [System.IO.Path]::GetFileNameWithoutExtension($csproj)
    $isWindowsRuntime = $Runtime -like "win-*"
    $binaryFile = if ($isWindowsRuntime) { "$binaryName.exe" } else { $binaryName }
    $binaryPath = Join-Path $outputDir $binaryFile

    Write-Host "`nPublish successful!" -ForegroundColor Green
    if (Test-Path $binaryPath) {
        Write-Host "Executable location: $binaryPath" -ForegroundColor Gray
    }
    else {
        Write-Host "Output directory: $outputDir" -ForegroundColor Gray
    }
}
else {
    Write-Host "`nPublish failed with exit code $LASTEXITCODE" -ForegroundColor Red
    exit $LASTEXITCODE
}
