param(
    [string]$SourceDir = ".",
    [ValidateSet("Win32", "x64", "ARM64")]
    [string]$Platform = "x64",
    [ValidateSet("Release", "Debug")]
    [string]$Config = "Release"
)

$SourceDir = (Resolve-Path $SourceDir).Path
$BuildBat = Join-Path $SourceDir "PCbuild\build.bat"

if (-not (Test-Path $BuildBat)) {
    Write-Error "Not a CPython source tree: $BuildBat not found"
    exit 1
}

$Args = @("-e", "-p", $Platform)
if ($Config -eq "Debug") {
    $Args = @("-e", "-d", "-p", $Platform)
}

Write-Host "[INFO] Source   : $SourceDir"
Write-Host "[INFO] Platform : $Platform"
Write-Host "[INFO] Config   : $Config"
Write-Host "[INFO] Running  : $BuildBat $($Args -join ' ')"

Push-Location $SourceDir
try {
    & $BuildBat @Args
    if ($LASTEXITCODE -ne 0) {
        throw "Build failed with exit code $LASTEXITCODE"
    }

    $outDir = $null
    switch ($Platform) {
        "Win32" { $outDir = Join-Path $SourceDir "PCbuild\win32" }
        "x64"   { $outDir = Join-Path $SourceDir "PCbuild\amd64" }
        "ARM64" {
            $cand1 = Join-Path $SourceDir "PCbuild\arm64"
            $cand2 = Join-Path $SourceDir "PCbuild\win-arm64"
            if (Test-Path $cand1) { $outDir = $cand1 }
            elseif (Test-Path $cand2) { $outDir = $cand2 }
        }
    }

    Write-Host "[INFO] Build finished successfully."
    if ($outDir) {
        Write-Host "[INFO] Output dir: $outDir"
    } else {
        Write-Warning "Could not determine output dir automatically. Check PCbuild\"
    }
}
finally {
    Pop-Location
}