# One-time bootstrap: builds SDL3 from source and installs it into prebuilt/windows/.
# Run this once after cloning. Re-run only when upgrading SDL.
param(
    [string]$SdlVersion = "3.2.10",
    [string]$BuildType  = "Release"
)

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

# Download SDL source if not already present
if (-not (Test-Path $SdlSource)) {
    Write-Host "`n=== Downloading SDL3 $SdlVersion ===" -ForegroundColor Cyan
    New-Item -ItemType Directory -Force -Path $BuildDir | Out-Null
    $Archive = "$BuildDir\SDL-$SdlVersion.tar.gz"
    Invoke-WebRequest -Uri "https://github.com/libsdl-org/SDL/archive/refs/tags/release-$SdlVersion.tar.gz" `
        -OutFile $Archive
    tar -xf $Archive -C $BuildDir
    Rename-Item "$BuildDir\SDL-release-$SdlVersion" "SDL-src"
    Remove-Item $Archive
}

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

    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"