@echo off
chcp 65001>nul
setlocal

set "PROJECT_DIR=%~dp0"
set "BUILD_DIR=%PROJECT_DIR%build"

echo ========================================
echo  Building SealProcessing project with CMake
echo ========================================
echo.

if not exist "%BUILD_DIR%" mkdir "%BUILD_DIR%"

cd /d "%BUILD_DIR%"

echo [1/3] Configuring CMake...
rem 尝试多个可能的 OpenCV 路径
set "OPENCV_PATHS=C:/msys64/mingw64/lib/cmake/opencv4;C:/mingw64/lib/cmake/opencv4;C:/opencv/build/x64/mingw/lib"

set "CMAKE_COMMAND=cmake .. -G "MinGW Makefiles""

rem 优先尝试我们指定的路径，忽略环境变量
set "FOUND_OPENCV=0"
echo Trying multiple OpenCV paths...
for %%p in (%OPENCV_PATHS%) do (
    if exist "%%p" (
        echo Found OpenCV at: %%p
        set "CMAKE_COMMAND=%CMAKE_COMMAND% -DOpenCV_DIR="%%p""
        set "FOUND_OPENCV=1"
        goto :cmake_config
    )
)

rem 如果没有找到，尝试使用环境变量
if %FOUND_OPENCV%==0 (
    if defined OpenCV_DIR (
        echo Warning: Using OpenCV_DIR from environment variable: %OpenCV_DIR%
        echo This might not be compatible with MinGW.
        set "CMAKE_COMMAND=%CMAKE_COMMAND% -DOpenCV_DIR="%OpenCV_DIR%""
    ) else (
        echo Warning: No OpenCV directory found. CMake will try to find it automatically.
    )
)

:cmake_config
%CMAKE_COMMAND%
if errorlevel 1 (
    echo.
    echo CMake configuration failed!
    pause
    exit /b 1
)

echo.
echo [2/3] Building project...
cmake --build .
if errorlevel 1 (
    echo.
    echo Build failed!
    pause
    exit /b 1
)

echo.
echo ========================================
echo  Build successful!
echo ========================================
echo Executables are in: %BUILD_DIR%
echo.
echo Available targets:
echo   - test_extract_seal.exe
echo   - test_remove_border.exe
echo.

pause
