@echo off
setlocal

:: --- 1. Handle Compiler Choice ---
:: Default to Clang, but allow override via "build_game.bat msvc"
set "COMPILER_TYPE=%~1"
if "%COMPILER_TYPE%"=="" set "COMPILER_TYPE=clang"

if /I "%COMPILER_TYPE%"=="clang" (
    set "PLATFORM=x64Clang"
) else (
    set "PLATFORM=x64"
)

:: --- 2. Generate Random ID & Setup Paths ---
set "CONFIG=Debug"
set "GAME_BUILD_ID=%RANDOM%"
set "TARGET=Game-%PLATFORM%-%CONFIG%"
set "OUT_DIR=%~dp0..\bin\%PLATFORM%-%CONFIG%"

echo --- Building %TARGET% (ID: %GAME_BUILD_ID%) ---

:: --- 3. Manage Lock File ---
if not exist "%OUT_DIR%" mkdir "%OUT_DIR%"
pushd "%OUT_DIR%"
:: Clean up old DLLs/PDBs in this folder to prevent clutter
del Game-*.dll Game-*.pdb > NUL 2> NUL
echo %GAME_BUILD_ID% > lock.tmp
popd

:: --- 4. Run FASTBuild ---
:: We pass the ID via an Environment Variable so the .bff can read it
set "GAME_BUILD_ID=%GAME_BUILD_ID%"
fbuild %TARGET% -cache

if %ERRORLEVEL% NEQ 0 (
    echo.
    echo BUILD FAILED!
    goto :cleanup
)

echo.
echo SUCCESS: Generated %OUT_DIR%\Game-%GAME_BUILD_ID%.dll

:cleanup
if exist "%OUT_DIR%\lock.tmp" del "%OUT_DIR%\lock.tmp"