@echo off
setlocal EnableExtensions

set "ROOT=%~dp0"
pushd "%ROOT%" >nul
set "SRC_DIR=%ROOT%source"

set "DEFAULT_CXX=C:\Users\lnk\Downloads\mingw32\bin\g++.exe"
if exist "%DEFAULT_CXX%" (
    set "CXX=%DEFAULT_CXX%"
) else (
    set "CXX=g++"
)

set "OUT=%~1"
if "%OUT%"=="" set "OUT=bin\pq_tool.exe"
if not exist "bin" mkdir "bin"
if not exist "%SRC_DIR%\main.cpp" (
    echo [ERR] Source directory not found: %SRC_DIR%
    popd >nul
    exit /b 1
)

if not "%PQ_BUILD_TEMP%"=="" (
    if exist "%PQ_BUILD_TEMP%" (
        set "TMP=%PQ_BUILD_TEMP%"
        set "TEMP=%PQ_BUILD_TEMP%"
        echo [INFO] TEMP: %PQ_BUILD_TEMP%
    ) else (
        echo [WARN] PQ_BUILD_TEMP does not exist; using default TEMP.
    )
)

echo [INFO] Compiler: %CXX%
for /f "delims=" %%M in ('"%CXX%" -dumpmachine 2^>nul') do set "TARGET=%%M"
echo [INFO] Target: %TARGET%
echo %TARGET% | findstr /i "i686" >nul
if errorlevel 1 (
    echo [ERR] This project must be built with a 32-bit i686 MinGW compiler.
    echo [ERR] Current compiler target is: %TARGET%
    popd >nul
    exit /b 1
)

echo [INFO] Output: %OUT%
if exist "%OUT%" (
    del /f "%OUT%" >nul 2>nul
    if exist "%OUT%" (
        echo [ERR] Cannot overwrite existing output. Is it still running? %OUT%
        popd >nul
        exit /b 1
    )
)

"%CXX%" ^
  -std=gnu++17 ^
  -O2 ^
  -Wall ^
  -Wno-deprecated-declarations ^
  -I"%SRC_DIR%" ^
  -o "%OUT%" ^
  "%SRC_DIR%\main.cpp" "%SRC_DIR%\interface.cpp" "%SRC_DIR%\mq.cpp" "%SRC_DIR%\icd_mapper.cpp" "%SRC_DIR%\tinyxml2.cpp" ^
  -lcomctl32 -lcomdlg32 -lwinhttp -lole32 -luuid -lws2_32 -lgdi32 ^
  -static-libgcc -static-libstdc++

if errorlevel 1 (
    echo [ERR] Build failed.
    popd >nul
    exit /b 1
)

if not exist "%OUT%" (
    echo [ERR] Build command finished but output file was not created: %OUT%
    popd >nul
    exit /b 1
)

if not exist "bin\rocketmq-client-cpp.dll" (
    echo [WARN] bin\rocketmq-client-cpp.dll is missing. MQ runtime will not load.
)

if not exist "bin\libwinpthread-1.dll" (
    echo [WARN] bin\libwinpthread-1.dll is missing. RocketMQ DLL may fail to load.
)

echo [OK] Build complete: %OUT%
popd >nul
exit /b 0
