@echo off
title WebRadar — Build All

echo [WebRadar] ========================================
echo [WebRadar] Building WebRadar (C++ + Frontend)
echo [WebRadar] ========================================
echo.

set PROJECT_DIR=%~dp0

REM ── Tim Visual Studio ──────────────────────────────────
set VSPATH=
if exist "%ProgramFiles%\Microsoft Visual Studio\Installer\vswhere.exe" (
    for /f "tokens=* usebackq" %%a in (
        `"%ProgramFiles%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -property installationPath`
    ) do set VSPATH=%%a
)
if "%VSPATH%"=="" (
    if exist "%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" (
        for /f "tokens=* usebackq" %%a in (
            `"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -property installationPath`
        ) do set VSPATH=%%a
    )
)

REM ── Fallback ───────────────────────────────────────────
if "%VSPATH%"=="" (
    if exist "C:\Program Files\Microsoft Visual Studio\2022\Community" set VSPATH=C:\Program Files\Microsoft Visual Studio\2022\Community
)
if "%VSPATH%"=="" (
    echo [WebRadar] ERROR: Khong tim thay Visual Studio 2022!
    pause
    exit /b 1
)
echo [WebRadar] Visual Studio: %VSPATH%

REM ── Load VS environment ────────────────────────────────
call "%VSPATH%\VC\Auxiliary\Build\vcvarsall.bat" x64
if %ERRORLEVEL% neq 0 (
    echo [WebRadar] ERROR: Khong the load VS environment!
    pause
    exit /b 1
)

REM ── Build C++ ──────────────────────────────────────────
echo [WebRadar] Step 1/2: Building C++...
cd /d "%PROJECT_DIR%"
msbuild webradar_cpp.vcxproj /p:Configuration=Release /p:Platform=x64 /v:m
if errorlevel 1 (
    echo [WebRadar] ERROR: Build C++ that bai!
    pause
    exit /b 1
)
echo [WebRadar] C++ build OK.

REM ── Build frontend ─────────────────────────────────────
echo [WebRadar] Step 2/3: Building frontend...
cd /d "%PROJECT_DIR%\webapp"
call npx vite build
if errorlevel 1 (
    echo [WebRadar] WARNING: Frontend build that bai. Ban co the can chay: npm install
) else (
    echo [WebRadar] Frontend build OK.
)

REM ── Copy frontend vao build/ ────────────────────────────
echo [WebRadar] Step 3/3: Copying frontend vao build/...
if exist "%PROJECT_DIR%build\webapp" rmdir /s /q "%PROJECT_DIR%build\webapp"
if exist "%PROJECT_DIR%webapp\dist" (
    xcopy /e /i /y "%PROJECT_DIR%webapp\dist" "%PROJECT_DIR%build\webapp\dist\" > nul
    if errorlevel 1 (
        echo [WebRadar] WARNING: Copy frontend that bai!
    ) else (
        echo [WebRadar] Copy frontend OK.
    )
) else (
    echo [WebRadar] WARNING: Khong tim thay webapp\dist. Hay build frontend truoc.
)

echo.
echo [WebRadar] ========================================
echo [WebRadar] BUILD HOAN TAT!
echo [WebRadar] ========================================
echo.
echo Binary: %PROJECT_DIR%build\WebRadar.exe
echo Frontend: %PROJECT_DIR%build\webapp\dist\
echo.
echo Chay: %PROJECT_DIR%build\WebRadar.exe
echo.
