@echo off
setlocal

set "PROJECT_DIR=%~dp0.."
set "PROJECT_FILE=%PROJECT_DIR%\AgrarianGame.uproject"
set "UE_ROOT=C:\Program Files\Epic Games\UE_5.7"
set "RUN_UAT=%UE_ROOT%\Engine\Build\BatchFiles\RunUAT.bat"
set "BUILD_BAT=%UE_ROOT%\Engine\Build\BatchFiles\Build.bat"
set "ARCHIVE_DIR=%PROJECT_DIR%\Builds\WindowsDevelopment"
set "LOG_DIR=%PROJECT_DIR%\Saved\BuildLogs"
set "LOG_FILE=%LOG_DIR%\PackageWindowsDevelopment.log"
set "BUILD_LOG_FILE=%LOG_DIR%\PackageWindowsBuild.log"

if not exist "%LOG_DIR%" mkdir "%LOG_DIR%"
if not exist "%ARCHIVE_DIR%" mkdir "%ARCHIVE_DIR%"

if not exist "%RUN_UAT%" (
  echo Unreal Engine 5.7 RunUAT was not found at:
  echo %RUN_UAT%
  exit /b 1
)

if not exist "%BUILD_BAT%" (
  echo Unreal Engine 5.7 Build.bat was not found at:
  echo %BUILD_BAT%
  exit /b 1
)

if not exist "%PROJECT_FILE%" (
  echo Project file was not found at:
  echo %PROJECT_FILE%
  exit /b 1
)

echo Packaging Agrarian Windows Development build...
echo Archive: %ARCHIVE_DIR%
echo Log: %LOG_FILE%

echo Building packaged targets without Unreal Build Accelerator...
(
  call "%BUILD_BAT%" AgrarianGameEditor Win64 Development -Project="%PROJECT_FILE%" -WaitMutex -architecture=x64 -NoUBA
  call "%BUILD_BAT%" AgrarianGame Win64 Development -Project="%PROJECT_FILE%" -WaitMutex -architecture=x64 -NoUBA
) > "%BUILD_LOG_FILE%" 2>&1

set "BUILD_EXIT_CODE=%ERRORLEVEL%"
type "%BUILD_LOG_FILE%"

if not "%BUILD_EXIT_CODE%"=="0" (
  echo.
  echo Target build failed with exit code %BUILD_EXIT_CODE%.
  echo Log file: %BUILD_LOG_FILE%
  exit /b %BUILD_EXIT_CODE%
)

call "%RUN_UAT%" BuildCookRun ^
  -project="%PROJECT_FILE%" ^
  -noP4 ^
  -platform=Win64 ^
  -clientconfig=Development ^
  -skipbuild ^
  -cook ^
  -stage ^
  -pak ^
  -archive ^
  -archivedirectory="%ARCHIVE_DIR%" ^
  -map=/Game/Agrarian/Maps/L_GroundZeroTerrain_Test ^
  -prereqs ^
  -utf8output ^
  -NoUBA > "%LOG_FILE%" 2>&1

set "PACKAGE_EXIT_CODE=%ERRORLEVEL%"
type "%LOG_FILE%"

if not "%PACKAGE_EXIT_CODE%"=="0" (
  echo.
  echo Package failed with exit code %PACKAGE_EXIT_CODE%.
  echo Log file: %LOG_FILE%
  exit /b %PACKAGE_EXIT_CODE%
)

call "%PROJECT_DIR%\Scripts\InstallWindowsDemoLaunchers.bat" "%ARCHIVE_DIR%"
set "LAUNCHER_EXIT_CODE=%ERRORLEVEL%"

if not "%LAUNCHER_EXIT_CODE%"=="0" (
  echo.
  echo Launcher install failed with exit code %LAUNCHER_EXIT_CODE%.
  exit /b %LAUNCHER_EXIT_CODE%
)

echo.
echo Package completed successfully.
echo Archive: %ARCHIVE_DIR%
echo.
exit /b 0
