param(
    [string]$BuildType = "Release"
)

$ProjectRoot = Resolve-Path "$PSScriptRoot\.."
$SdlSource   = "$ProjectRoot\external\SDL"
$BuildDir    = "$ProjectRoot\out\build\_sdl_build\windows"
$PrebuiltDir = "$ProjectRoot\prebuilt\windows"

function Build-SDL {
    param([string]$LinkType)

    $Shared   = if ($LinkType -eq "dynamic") { "ON" } else { "OFF" }
    $Static   = if ($LinkType -eq "static")  { "ON" } else { "OFF" }
    $OutDir   = "$PrebuiltDir\SDL3-$LinkType"
    $BuildOut = "$BuildDir\$LinkType"

    Write-Host "`n=== Building SDL3 ($LinkType) for Windows ===" -ForegroundColor Cyan

    # Wipe any stale build directory to avoid corrupted cache issues
    if (Test-Path $BuildOut) {
        Write-Host "Removing stale build directory: $BuildOut" -ForegroundColor Yellow
        Remove-Item -Recurse -Force $BuildOut
    }

    cmake -S "$SdlSource" -B "$BuildOut" `
        -G "Visual Studio 17 2022" `
        -A x64 `
        -DCMAKE_INSTALL_PREFIX="$OutDir" `
        -DSDL_SHARED="$Shared" `
        -DSDL_STATIC="$Static" `
        -DSDL_INSTALL=ON `
        -DSDL_TEST_LIBRARY=OFF `
        -DSDL_TESTS=OFF

    if ($LASTEXITCODE -ne 0) { Write-Error "CMake configure failed"; exit 1 }

    cmake --build "$BuildOut" --config "$BuildType"
    if ($LASTEXITCODE -ne 0) { Write-Error "CMake build failed"; exit 1 }

    cmake --install "$BuildOut" --config "$BuildType"
    if ($LASTEXITCODE -ne 0) { Write-Error "CMake install failed"; exit 1 }

    Write-Host "=== Done: $OutDir ===" -ForegroundColor Green
}

Build-SDL -LinkType "dynamic"
Build-SDL -LinkType "static"