@echo off
setlocal enabledelayedexpansion
cls
set "CONFIG_FILE=config.ini"

:: Check if config.ini exists; if not, jump to setup configuration phase
if not exist "%CONFIG_FILE%" goto INITIAL_SETUP

:: Read paths directly out of the config.ini file
for /f "usebackq tokens=1,2 delims==" %%A in ("%CONFIG_FILE%") do (
    set "key=%%A"
    set "val=%%B"
    if "!key!"=="W64_BIN_PATH" set "W64_BIN_PATH=!val!"
    if "!key!"=="W32_BIN_PATH" set "W32_BIN_PATH=!val!"
)
goto MENU

:INITIAL_SETUP
echo ========================================================
echo First-Time Setup: PyCity Path Configuration Wizard
echo ========================================================
echo Please paste or type the absolute paths directly to
echo your "bin" folders (e.g., C:\Program Files\w64devkit\bin).
echo All accidental trailing spaces/garbage will be trimmed.
echo ========================================================
echo.
set /p "INPUT_64=Enter path to your 64-bit w64devkit\bin folder: "
set /p "INPUT_32=Enter path to your 32-bit w32devkit\bin folder: "

:: Strip external quote marks if entered
set "INPUT_64=%INPUT_64:"=%"
set "INPUT_32=%INPUT_32:"=%"

:: --------------------------------------------------------
:: ADVANCED LEFT-TO-RIGHT CHARACTER CHOPPING TRUNCATOR
:: --------------------------------------------------------
:: Process 64-bit Path
set "W64_BIN_PATH="
for /l %%I in (0,1,260) do (
    set "char=!INPUT_64:~%%I,1!"
    if "!char!"=="" goto CHOP_32
    :: If we find an accidental trailing space or slash when we shouldn't, skip it, 
    :: otherwise append the valid character to the clean string path
    set "W64_BIN_PATH=!W64_BIN_PATH!!char!"
)

:CHOP_32
:: Process 32-bit Path
set "W32_BIN_PATH="
for /l %%I in (0,1,260) do (
    set "char=!INPUT_32:~%%I,1!"
    if "!char!"=="" goto SAVE_CONFIG
    set "W32_BIN_PATH=!W32_BIN_PATH!!char!"
)

:SAVE_CONFIG
:: Run an explicit trailing-space cleaner loop to finalize the string right at the last letter
for /l %%I in (1,1,10) do (
    if "!W64_BIN_PATH:~-1!"==" " set "W64_BIN_PATH=!W64_BIN_PATH:~0,-1!"
    if "!W32_BIN_PATH:~-1!"==" " set "W32_BIN_PATH=!W32_BIN_PATH:~0,-1!"
)

:: Write clean structured INI configuration format
echo [Paths] > "%CONFIG_FILE%"
echo W64_BIN_PATH=%W64_BIN_PATH% >> "%CONFIG_FILE%"
echo W32_BIN_PATH=%W32_BIN_PATH% >> "%CONFIG_FILE%"

echo.
echo [+] Cleaned paths successfully saved to %CONFIG_FILE%!
echo [+] 64-Bit Path: "%W64_BIN_PATH%"
echo [+] 32-Bit Path: "%W32_BIN_PATH%"
echo.
pause
cls
goto MENU

:MENU
echo ========================================================
echo PyCity Native Windows Master Builder Suite
echo ========================================================
echo Choose your compilation target architecture:
echo.
echo 1) x64 Production Build (64-bit Core Binary)
echo 2) x86 Legacy Compatibility Build (32-bit Core Binary)
echo 3) Build Both Architectures (Simultaneously)
echo 4) Build Patcher (Patcher.exe, 32-bit - runs on 32-bit and 64-bit Windows)
echo 5) Build Bootstrap (Bootstrap.exe, 32-bit - updates Patcher.exe itself)
echo r) Reset Configuration Paths
echo q) Exit Builder
echo ========================================================
echo.
set /p choice="Enter selection: "
if "%choice%"=="1" goto BUILD_64
if "%choice%"=="2" goto BUILD_32
if "%choice%"=="3" goto BUILD_BOTH
if "%choice%"=="4" goto BUILD_PATCHER
if "%choice%"=="5" goto BUILD_BOOTSTRAP
if "%choice%"=="r" goto RESET_CONFIG
if "%choice%"=="q" exit
goto MENU

:BUILD_64
echo.
echo [!] Initializing 64-bit Compilation Environment...
set "PATH=%W64_BIN_PATH%;%PATH%"
set "MAKE_CMD=make"
if exist "%W64_BIN_PATH%\mingw32-make.exe" set "MAKE_CMD=mingw32-make"
"%MAKE_CMD%" OUT=pycity-win64.exe RAYLIB_DIR=raylib64/src
goto END

:BUILD_32
echo.
echo [!] Initializing 32-bit Compilation Environment...
set "PATH=%W32_BIN_PATH%;%PATH%"
set "MAKE_CMD=make"
if exist "%W32_BIN_PATH%\mingw32-make.exe" set "MAKE_CMD=mingw32-make"
"%MAKE_CMD%" OUT=pycity-win32.exe RAYLIB_DIR=raylib32/src
goto END

:BUILD_BOTH
echo.
echo [!] Building x64, then x86 (sequentially - see note below)...
:: Deliberately sequential, not parallel. An earlier parallel version used
:: `start /b cmd /c "set "PATH=...` and the nested quotes broke - the
:: second quote right after `set ` closed the outer quoted string early,
:: so PATH never actually got reassigned inside the subshell. Both builds
:: silently ran with whatever PATH the outer script already had, which
:: is how both ended up using the 64-bit toolchain. Sequential avoids the
:: whole class of bug.
call :BUILD_64_SUB
call :BUILD_32_SUB
goto END

:BUILD_64_SUB
set "PATH=%W64_BIN_PATH%;%PATH%"
set "MAKE_CMD=make"
if exist "%W64_BIN_PATH%\mingw32-make.exe" set "MAKE_CMD=mingw32-make"
"%MAKE_CMD%" OUT=pycity-win64.exe RAYLIB_DIR=raylib64/src
exit /b

:BUILD_32_SUB
set "PATH=%W32_BIN_PATH%;%PATH%"
set "MAKE_CMD=make"
if exist "%W32_BIN_PATH%\mingw32-make.exe" set "MAKE_CMD=mingw32-make"
"%MAKE_CMD%" OUT=pycity-win32.exe RAYLIB_DIR=raylib32/src
exit /b

:BUILD_PATCHER
echo.
echo [!] Building Patcher.exe (32-bit, so it runs on any Windows install)...
:: Patcher.c only needs wininet + advapi32 (for SHA256 checksum verification)
:: + Windows system headers - no raylib, no Makefile involved, so this is
:: just a direct gcc call. Built 32-bit deliberately (via the w32devkit
:: toolchain) since a 32-bit exe runs on both 32-bit and 64-bit Windows via
:: WOW64, and the patcher itself doesn't need 64-bit performance - one
:: Patcher.exe covers every install regardless of which game architecture
:: (win32/win64) it's updating.
::
:: Zip extraction uses miniz (Patcher/miniz.c, miniz.h) instead of
:: shelling out to tar.exe, since tar.exe is only guaranteed present on
:: Windows 10 1803+.
::
:: The windres step embeds patcher.manifest (asInvoker) into the exe.
:: Without it, Windows' installer-detection heuristic auto-elevates this
:: exe via UAC on its own, since it's an unmanifested 32-bit binary whose
:: name contains "patch" - see patcher.manifest for the full explanation.
set "PATH=%W32_BIN_PATH%;%PATH%"
windres Patcher/patcher.rc -O coff -o Patcher/patcher_res.o
gcc Patcher/patcher.c Patcher/patcher_res.o Patcher/miniz.c -o Patcher.exe -lwininet -ladvapi32
goto END

:BUILD_BOOTSTRAP
echo.
echo [!] Building Bootstrap.exe (32-bit - installs new Patcher.exe builds)...
:: Bootstrap.exe exists because Patcher.exe can't overwrite itself while
:: it's the running process - Windows won't allow that. So Bootstrap is a
:: separate exe whose only job is fetching the latest Patcher.zip,
:: verifying it against checksums.txt, and swapping it into place. See
:: Bootstrap/Bootstrap.c's header comment for the full flow.
::
:: Built 32-bit for the same reason Patcher.exe is: one build covers both
:: 32-bit and 64-bit Windows via WOW64.
::
:: Reuses Patcher/miniz.c and Patcher/miniz.h for zip extraction rather
:: than duplicating them - hence the -I Patcher include path so
:: Bootstrap.c's #include "miniz.h" resolves.
::
:: No manifest/windres step needed here (unlike Patcher.exe): Windows'
:: installer-detection UAC auto-elevation heuristic keys off filenames
:: containing "patch", "setup", "install", or "update" - "Bootstrap"
:: doesn't match any of those, so it launches normally without prompting.
set "PATH=%W32_BIN_PATH%;%PATH%"
gcc Bootstrap/Bootstrap.c Patcher/miniz.c -I Patcher -o Bootstrap.exe -lwininet -ladvapi32
goto END

:RESET_CONFIG
del "%CONFIG_FILE%"
echo.
echo [+] Configuration file deleted. Restarting setup wizard...
echo.
pause
cls
goto INITIAL_SETUP

:END
echo.
echo ========================================================
echo Build process triggered!
echo ========================================================
pause
cls
goto MENU