@echo off
setlocal EnableExtensions
cd /d "%~dp0"

set "UC_PROFILE=%~1"
if not defined UC_PROFILE set "UC_PROFILE=baseline"
set "UC_RUN_TESTS=%~2"

call :find_cmake
if errorlevel 1 exit /b 1

if /I "%UC_PROFILE%"=="all" (
    call :build_one scalar
    if errorlevel 1 exit /b 1
    call :build_one baseline
    if errorlevel 1 exit /b 1
    call :build_one avx2
    if errorlevel 1 exit /b 1
) else if /I "%UC_PROFILE%"=="scalar" (
    call :build_one scalar
) else if /I "%UC_PROFILE%"=="baseline" (
    call :build_one baseline
) else if /I "%UC_PROFILE%"=="avx2" (
    call :build_one avx2
) else (
    echo Unknown profile "%UC_PROFILE%".
    echo Usage: build.bat [scalar^|baseline^|avx2^|all] [test]
    exit /b 2
)

if errorlevel 1 exit /b 1
echo.
echo Build completed. Executables are under out\bin\PROFILE\Release\
exit /b 0

:build_one
set "UC_ONE_PROFILE=%~1"
echo.
echo === Configuring %UC_ONE_PROFILE% Release ===
"%UC_CMAKE%" --preset "msvc-%UC_ONE_PROFILE%"
if errorlevel 1 exit /b 1

echo === Building %UC_ONE_PROFILE% Release ===
"%UC_CMAKE%" --build --preset "build-%UC_ONE_PROFILE%-release"
if errorlevel 1 exit /b 1

echo === Auditing %UC_ONE_PROFILE% compiler flags ===
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "tools\audit_build_flags.ps1" -Profile "%UC_ONE_PROFILE%"
if errorlevel 1 exit /b 1

if /I "%UC_RUN_TESTS%"=="test" (
    if /I "%UC_ONE_PROFILE%"=="avx2" (
        echo === Checking AVX2 support before running avx2 tests ===
        powershell.exe -NoProfile -ExecutionPolicy Bypass -File "tools\test_avx2.ps1"
        if errorlevel 1 (
            echo AVX2 tests skipped because this CPU/OS does not report AVX2 support.
            exit /b 0
        )
    )
    echo === Testing %UC_ONE_PROFILE% Release ===
    "%UC_CMAKE%" --build "out\build\msvc-%UC_ONE_PROFILE%" --config Release --target RUN_TESTS
    if errorlevel 1 exit /b 1
)
exit /b 0

:find_cmake
for /f "delims=" %%I in ('where cmake.exe 2^>nul') do (
    if not defined UC_CMAKE set "UC_CMAKE=%%I"
)
if defined UC_CMAKE exit /b 0

set "UC_VSWHERE=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe"
if not exist "%UC_VSWHERE%" (
    echo Could not find cmake.exe or Visual Studio Installer's vswhere.exe.
    exit /b 1
)

for /f "usebackq delims=" %%I in (`"%UC_VSWHERE%" -latest -products * -requires Microsoft.Component.MSBuild -property installationPath`) do set "UC_VSROOT=%%I"
if not defined UC_VSROOT (
    echo No Visual Studio installation with MSBuild was found.
    exit /b 1
)

set "UC_CMAKE=%UC_VSROOT%\Common7\IDE\CommonExtensions\Microsoft\CMake\CMake\bin\cmake.exe"
if not exist "%UC_CMAKE%" (
    echo Visual Studio was found, but its bundled CMake is missing:
    echo %UC_CMAKE%
    exit /b 1
)
exit /b 0
