@echo off
setlocal enabledelayedexpansion

:: =============================================
:: Project Build Script - Optimized for Windows
:: Builds Linux and Windows executables
:: Outputs to dist directory with timestamped filenames
:: =============================================

:: Project name
set PROJECT=xk-websocket

:: Fix Windows time format issue (hour might be single digit)
set HOUR=%time:~0,2%
if "%HOUR:~0,1%"==" " set HOUR=0%HOUR:~1,1%
set MIN=%time:~3,2%
set SEC=%time:~6,2%
set MSEC=%time:~9,2%

:: Create precise timestamp (YYYY-MM-DD_HH-MM-SS)
set DATE_STAMP=%date:~0,4%-%date:~5,2%-%date:~8,2%
set TIME_STAMP=%HOUR%-%MIN%-%SEC%
set TIMESTAMP=%DATE_STAMP%_%TIME_STAMP%

:: Target directory
set DIST_DIR=dist

echo.
echo [1/5] Preparing build environment...
if not exist "%DIST_DIR%" (
    mkdir "%DIST_DIR%"
    echo   Created directory: %DIST_DIR%
) else (
    echo   Directory exists: %DIST_DIR%
)

echo.
echo [2/5] Setting build info...
echo   Project name: %PROJECT%
echo   Build time: %TIMESTAMP%

echo.
echo [3/5] Building Linux version...
set GOOS=linux
set GOARCH=amd64
go build -o "%DIST_DIR%\%PROJECT%-linux-%TIMESTAMP%"
if %errorlevel% neq 0 (
    echo.
    echo ERROR: Linux build failed!
    exit /b 1
)

echo.
echo [4/5] Building Windows version...
set GOOS=windows
set GOARCH=amd64
go build -o "%DIST_DIR%\%PROJECT%-windows-%TIMESTAMP%.exe"
if %errorlevel% neq 0 (
    echo.
    echo ERROR: Windows build failed!
    exit /b 1
)

echo.
echo [5/5] Build successful!
echo.
echo Output directory: %cd%\%DIST_DIR%\
echo Generated files:
echo   1. %PROJECT%-linux-%TIMESTAMP%
echo   2. %PROJECT%-windows-%TIMESTAMP%.exe
echo.

:: Add cleanup option
:clean_prompt
echo Clean up old build files? [Y/N]
set /p CLEAN_OLD=
if /i "%CLEAN_OLD%"=="Y" (
    call :clean_old_builds
    goto :end
)
if /i "%CLEAN_OLD%"=="N" (
    goto :end
)
echo Please enter Y or N
goto :clean_prompt

:clean_old_builds
echo.
echo Cleaning old build files...
set KEEP_PATTERN=*%TIMESTAMP%*
for %%f in ("%DIST_DIR%\%PROJECT%-*") do (
    if not "%%~nxf"=="%PROJECT%-linux-%TIMESTAMP%" (
        if not "%%~nxf"=="%PROJECT%-windows-%TIMESTAMP%.exe" (
            echo   Deleting: %%f
            del /q "%%f"
        )
    )
)
echo Cleanup complete! Kept latest build files.
goto :eof

:end
echo.
echo Run instructions:
echo   Linux: .\%DIST_DIR%\%PROJECT%-linux-%TIMESTAMP% --nodeId=node1 --port=12081
echo   Windows: .\%DIST_DIR%\%PROJECT%-windows-%TIMESTAMP%.exe --nodeId=win1 --port=12080
echo.

endlocal