@echo off
setlocal
for %%I in ("%~dp0..") do set "PROJECT_DIR=%%~fI"
cd /d "%PROJECT_DIR%"

set "BOOTSTRAP_PYTHON="
set "PYTHON_CMD="

py -3.11 --version >nul 2>&1
if not errorlevel 1 (
  set "BOOTSTRAP_PYTHON=py -3.11"
)

if not defined BOOTSTRAP_PYTHON (
  py --version >nul 2>&1
  if not errorlevel 1 (
    set "BOOTSTRAP_PYTHON=py"
  )
)

if not defined BOOTSTRAP_PYTHON (
  python --version >nul 2>&1
  if not errorlevel 1 (
    set "BOOTSTRAP_PYTHON=python"
  )
)

if not defined BOOTSTRAP_PYTHON (
  if exist ".venv\Scripts\python.exe" (
    ".venv\Scripts\python.exe" --version >nul 2>&1
    if not errorlevel 1 (
      set "BOOTSTRAP_PYTHON=.venv\Scripts\python.exe"
    )
  )
)

if not defined BOOTSTRAP_PYTHON (
  echo Could not find a working Python interpreter.
  echo Please install Python 3.11+ or recreate .venv.
  exit /b 1
)

echo Ensuring project virtualenv is healthy...
%BOOTSTRAP_PYTHON% scripts\ensure_project_venv.py --install-requirements
if errorlevel 1 (
  echo Failed to prepare project virtualenv.
  exit /b 1
)

set "PYTHON_CMD=.venv\Scripts\python.exe"

echo Building exe...
%PYTHON_CMD% build_exe.py
if errorlevel 1 (
  echo Build failed.
  exit /b 1
)

if not exist "dist\SunnyERPApp\app_core" (
  echo Missing packaged folder: dist\SunnyERPApp\app_core
  exit /b 1
)

if not exist "dist\SunnyERPApp\app_modules\production_module.py" (
  echo Missing packaged file: dist\SunnyERPApp\app_modules\production_module.py
  exit /b 1
)

if not exist "dist\SunnyERPApp\local_server" (
  echo Missing packaged folder: dist\SunnyERPApp\local_server
  exit /b 1
)

if not exist "dist\SunnyERPApp\language\ko.json" (
  echo Missing packaged language file: dist\SunnyERPApp\language\ko.json
  exit /b 1
)

if not exist "dist\SunnyERPApp\language\vi.json" (
  echo Missing packaged language file: dist\SunnyERPApp\language\vi.json
  exit /b 1
)

if not exist "dist\SunnyERPApp\database.py" (
  echo Missing packaged file: dist\SunnyERPApp\database.py
  exit /b 1
)

if not exist "dist\SunnyERPApp\requirements.txt" (
  echo Missing packaged file: dist\SunnyERPApp\requirements.txt
  exit /b 1
)

if not exist "dist\SunnyERPApp\scripts\update_app.ps1" (
  echo Missing packaged updater script: dist\SunnyERPApp\scripts\update_app.ps1
  exit /b 1
)

if not exist "dist\SunnyERPApp_package.zip" (
  echo Missing package zip: dist\SunnyERPApp_package.zip
  exit /b 1
)

echo.
echo Build finished.
echo Output folder: dist\SunnyERPApp
echo Package zip: dist\SunnyERPApp_package.zip
echo Included for tester local host: app_core, app_modules, local_server, database.py, requirements.txt
