<#
.SYNOPSIS
    Publishes Mbproxy.exe in two flavours: self-contained and framework-dependent.

.DESCRIPTION
    Produces two single-file win-x64 builds under <repo>\publish-out\:

      self-contained\Mbproxy.exe         ~100 MB — bundles the .NET 10 runtime;
                                                   no .NET install needed on target.
      framework-dependent\Mbproxy.exe    ~1.6 MB — requires .NET 10 + ASP.NET Core
                                                   runtime preinstalled on target.

    Both builds use the Release configuration and inherit the publish settings
    declared in src\Mbproxy\Mbproxy.csproj (PublishSingleFile=true,
    IncludeNativeLibrariesForSelfExtract=true). The framework-dependent build
    overrides SelfContained=false on the command line.

.PARAMETER OutputDir
    Root output directory. Two subfolders are created beneath it.
    Default: <repo>\publish-out

.PARAMETER Clean
    Delete OutputDir before publishing.

.EXAMPLE
    .\publish.ps1
    .\publish.ps1 -Clean
#>
[CmdletBinding()]
param(
    [string]$OutputDir = (Join-Path (Split-Path -Parent $PSScriptRoot) 'publish-out'),
    [switch]$Clean
)

$ErrorActionPreference = 'Stop'

$repoRoot = Split-Path -Parent $PSScriptRoot
$csproj   = Join-Path $repoRoot 'src\Mbproxy\Mbproxy.csproj'

if (-not (Test-Path $csproj)) {
    throw "Cannot find $csproj"
}

if ($Clean -and (Test-Path $OutputDir)) {
    Write-Host "Cleaning $OutputDir" -ForegroundColor Yellow
    Remove-Item -Recurse -Force $OutputDir
}

$selfContainedOut       = Join-Path $OutputDir 'self-contained'
$frameworkDependentOut  = Join-Path $OutputDir 'framework-dependent'

Write-Host "`n=== Publishing self-contained (~100 MB) ===" -ForegroundColor Cyan
& dotnet publish $csproj -c Release -r win-x64 -o $selfContainedOut --nologo
if ($LASTEXITCODE -ne 0) { throw "self-contained publish failed (exit $LASTEXITCODE)" }

Write-Host "`n=== Publishing framework-dependent (~1.6 MB) ===" -ForegroundColor Cyan
& dotnet publish $csproj -c Release -r win-x64 -p:SelfContained=false -p:PublishSingleFile=true -o $frameworkDependentOut --nologo
if ($LASTEXITCODE -ne 0) { throw "framework-dependent publish failed (exit $LASTEXITCODE)" }

function Format-Size {
    param([long]$Bytes)
    if ($Bytes -ge 1MB) { '{0:N1} MB' -f ($Bytes / 1MB) }
    else                { '{0:N1} KB' -f ($Bytes / 1KB) }
}

Write-Host "`n=== Result ===" -ForegroundColor Green
foreach ($flavour in 'self-contained','framework-dependent') {
    $exe = Join-Path $OutputDir "$flavour\Mbproxy.exe"
    if (Test-Path $exe) {
        $size = (Get-Item $exe).Length
        Write-Host ("  {0,-22} {1,10}  {2}" -f $flavour, (Format-Size $size), $exe)
    } else {
        Write-Warning "Missing: $exe"
    }
}
Write-Host ""
