@echo off
setlocal EnableExtensions

rem ============================================================================
rem  Build script for the PQ mapping/parser/tracing tool.
rem
rem  Purpose:
rem    1. Compile sources from the source directory.
rem    2. Write bin\pq_tool.exe by default, or write the output path passed as %1.
rem    3. Require a 32-bit i686 MinGW compiler because the executable and
rem       RocketMQ runtime DLLs must use the same 32-bit architecture.
rem
rem  Inputs:
rem    %1             Optional output exe path.
rem    PQ_BUILD_TEMP  Optional temp directory, useful when the system temp drive
rem                   has too little free space.
rem
rem  Outputs:
rem    Success: generated exe and optional DLL warnings.
rem    Failure: non-zero errorlevel and a printed error message.
rem
rem  Keep this file ASCII-only. cmd.exe parses batch files with the active code
rem  page, and UTF-8 Chinese comments can break command parsing on some systems.
rem ============================================================================

rem ROOT is the directory containing this script. All relative paths are based on
rem the project root after pushd.
set "ROOT=%~dp0"
pushd "%ROOT%" >nul
set "SRC_DIR=%ROOT%source"

rem Prefer the known 32-bit MinGW g++; otherwise fall back to g++ from PATH.
set "DEFAULT_CXX=C:\Users\lnk\Downloads\mingw32\bin\g++.exe"
if exist "%DEFAULT_CXX%" (
    set "CXX=%DEFAULT_CXX%"
) else (
    set "CXX=g++"
)

rem The first argument controls the output path, so a test build can coexist with
rem the normal bin\pq_tool.exe.
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
)

rem Redirect TMP/TEMP when the caller provides a valid build temp directory.
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.
    )
)

rem -dumpmachine returns values such as i686-w64-mingw32. Reject x86_64 here.
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%
rem Delete the old output before compiling. If deletion fails, the program is
rem usually still running or the file is locked by another process.
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
    )
)

rem Compile units:
rem   main.cpp        CLI entry, JSON/XML mapping parser, Excel XML output.
rem   interface.cpp   Win32 GUI, page interaction, preview, reverse XML output.
rem   mq.cpp          HTTP ledger/ICD fetch, RocketMQ loader, trace data storage.
rem   icd_mapper.cpp  Imports ICD descriptions into unmatched-origin workbook rows.
rem   tinyxml2.cpp    XML parsing/printing library.
"%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
)

rem Confirm that the compiler really produced the output file.
if not exist "%OUT%" (
    echo [ERR] Build command finished but output file was not created: %OUT%
    popd >nul
    exit /b 1
)

rem These DLLs are loaded dynamically at runtime. The program can still start
rem without them, but MQ tracing will fall back to runtime\json\mq_outbox_*.jsonl.
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
