@echo off
setlocal EnableExtensions

set "SELF_DIR=%~dp0"
pushd "%SELF_DIR%"

set "BUILD_DIR=%SELF_DIR%dist"
set "SPEC_DIR=%SELF_DIR%build"
set "PY_CMD=%SELF_DIR%.venv\Scripts\python.exe"
set "UPX_DIR=%SELF_DIR%buildtools"

set "MINIFY="
if /I "%~1"=="--minify" set "MINIFY=1"

echo [INFO] Build started...

rem =========================
rem Check Python
rem =========================

if not exist "%PY_CMD%" (
    echo [ERROR] Python not found
    exit /b 1
)

rem =========================
rem Check PyInstaller
rem =========================

"%PY_CMD%" -m pip show pyinstaller >nul 2>&1
if errorlevel 1 (
    echo [INFO] Installing PyInstaller...
    "%PY_CMD%" -m pip install pyinstaller --quiet
)

rem =========================
rem Clean
rem =========================

if exist "%BUILD_DIR%" rmdir /s /q "%BUILD_DIR%"
if exist "%SPEC_DIR%" rmdir /s /q "%SPEC_DIR%"

rem =========================
rem Optional icon
rem =========================

set "ICON_ARG="
if exist "%SELF_DIR%pptx-image-compress.ico" (
    set "ICON_ARG=%SELF_DIR%pptx-image-compress.ico"
)
echo [INFO] Icon param: %ICON_ARG%


rem =========================
rem Build EXE (STABLE)
rem =========================

echo [INFO] Building EXE...

if defined ICON_ARG (
    "%PY_CMD%" -m PyInstaller ^
        --onefile ^
        --console ^
        --name pptx-image-compress ^
        --distpath "%BUILD_DIR%" ^
        --specpath "%SPEC_DIR%" ^
        --workpath "%SPEC_DIR%\build" ^
        --icon="%ICON_ARG%" ^
        --hidden-import svg_polish ^
        pptx_image_compress.py
) else (
    "%PY_CMD%" -m PyInstaller ^
        --onefile ^
        --console ^
        --name pptx-image-compress ^
        --distpath "%BUILD_DIR%" ^
        --specpath "%SPEC_DIR%" ^
        --workpath "%SPEC_DIR%\build" ^
        --hidden-import svg_polish ^
        pptx_image_compress.py
)

if errorlevel 1 (
    echo [ERROR] Build failed
    exit /b 1
)

rem =========================
rem Optional UPX
rem =========================

if defined MINIFY (
    if exist "%UPX_DIR%\upx.exe" (
        echo [INFO] Running UPX compression...
        "%UPX_DIR%\upx.exe" --best --force "%BUILD_DIR%\pptx-image-compress.exe"
    ) else (
        echo [WARN] UPX not found at %UPX_DIR%
    )
)

rem =========================
rem Copy templates
rem =========================

copy "%SELF_DIR%templates\run.tpl.bat" "%BUILD_DIR%\run.bat" >nul
copy "%SELF_DIR%templates\dragdrop.tpl.bat" "%BUILD_DIR%\dragdrop.bat" >nul


rem =========================
rem Copy caesiumclt.exe
rem =========================
copy "%SELF_DIR%bin\caesiumclt.exe" "%BUILD_DIR%\caesiumclt.exe"

rem =========================
rem Done
rem =========================

echo(
echo [SUCCESS] Build complete!
echo Output:
echo   %BUILD_DIR%\pptx-image-compress.exe

popd
endlocal