# One-time bootstrap: builds SDL2_mixer from source and installs it into prebuilt/windows/.
# SDL3 must already be bootstrapped via bootstrap_sdl_windows.ps1 before running this.
# Run this once after cloning. Re-run only when upgrading SDL2_mixer.
param(
    [string]$SdlMixerVersion = "2.8.1",
    [string]$BuildType       = "Release"
)

$ProjectRoot     = Resolve-Path "$PSScriptRoot\.."
$BuildDir        = "$ProjectRoot\out\build\_sdl_mixer_bootstrap\windows"
$PrebuiltDir     = "$ProjectRoot\prebuilt\windows"
$SdlMixerSource  = "$BuildDir\SDL2_mixer-src"

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

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

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

    Write-Host "`n=== Building SDL2_mixer ($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 "$SdlMixerSource" -B "$BuildOut" `
        -G "Visual Studio 17 2022" `
        -A x64 `
        -DCMAKE_INSTALL_PREFIX="$OutDir" `
        -DSDL2MIXER_SHARED="$Shared" `
        -DSDL2MIXER_STATIC="$Static" `
        -DSDL2MIXER_INSTALL=ON `
        -DSDL2MIXER_SAMPLES=OFF `
        -DSDL2MIXER_MIDI_FLUIDSYNTH=OFF `
        -DSDL2MIXER_WAVPACK=OFF `
        -DSDL3_DIR="$Sdl3Dir"

    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-SDLMixer -LinkType "dynamic"
Build-SDLMixer -LinkType "static"