param([string]$Configuration = "Release")
$ErrorActionPreference = "Stop"
$root = Split-Path -Parent $PSScriptRoot
$lib = Join-Path $root "src\IMSApiDotNet\IMSApiDotNet.csproj"
$smoke = Join-Path $root "tests\IMSApiDotNet.LegacyBinarySmoke\IMSApiDotNet.LegacyBinarySmoke.csproj"

Write-Host "Building candidate net48 ..." -ForegroundColor Cyan
dotnet build $lib -c $Configuration -f net48
if ($LASTEXITCODE -ne 0) { throw "net48 build failed" }

Write-Host "Building candidate netstandard2.0 ..." -ForegroundColor Cyan
dotnet build $lib -c $Configuration -f netstandard2.0
if ($LASTEXITCODE -ne 0) { throw "netstandard2.0 build failed" }

Write-Host "Building smoke EXE AGAINST ORIGINAL 10.0.0-3 DLL ..." -ForegroundColor Cyan
dotnet build $smoke -c $Configuration
if ($LASTEXITCODE -ne 0) { throw "legacy smoke build failed" }

$smokeOut = Join-Path $root "tests\IMSApiDotNet.LegacyBinarySmoke\bin\$Configuration\net48"
$exe = Join-Path $smokeOut "IMSApiDotNet.LegacyBinarySmoke.exe"
if (-not (Test-Path $exe)) { throw "smoke exe not found: $exe" }

function Test-Candidate([string]$Target, [string]$CandidateDll) {
    if (-not (Test-Path $CandidateDll)) { throw "candidate not found: $CandidateDll" }
    $run = Join-Path $root "artifacts\abi-$Target"
    if (Test-Path $run) { Remove-Item $run -Recurse -Force }
    New-Item -ItemType Directory -Path $run -Force | Out-Null

    Copy-Item $exe (Join-Path $run "IMSApiDotNet.LegacyBinarySmoke.exe") -Force
    $config = $exe + ".config"
    if (Test-Path $config) { Copy-Item $config (Join-Path $run "IMSApiDotNet.LegacyBinarySmoke.exe.config") -Force }
    Copy-Item $CandidateDll (Join-Path $run "IMSApiDotNet.dll") -Force

    Write-Host "Running unchanged legacy EXE with $Target candidate ..." -ForegroundColor Yellow
    Push-Location $run
    try {
        & (Join-Path $run "IMSApiDotNet.LegacyBinarySmoke.exe")
        if ($LASTEXITCODE -ne 0) { throw "$Target binary compatibility failed (exit $LASTEXITCODE)" }
    }
    finally { Pop-Location }
}

Test-Candidate "net48" (Join-Path $root "src\IMSApiDotNet\bin\$Configuration\net48\IMSApiDotNet.dll")
Test-Candidate "netstandard2.0" (Join-Path $root "src\IMSApiDotNet\bin\$Configuration\netstandard2.0\IMSApiDotNet.dll")

Write-Host "Both targets passed legacy binary smoke test." -ForegroundColor Green
