@echo off
chcp 65001 >nul 2>nul
setlocal enableextensions

rem ============================================================================
rem  Migu2.0 platform frontend build (sync to MiGu.Server\wwwroot)
rem ----------------------------------------------------------------------------
rem  Usage:
rem    build-platform-frontend.bat [--reinstall] [--npm | --pnpm] [--no-start]
rem ============================================================================

set "ROOT=%~dp0"
set "FE_ROOT=%ROOT%frontends"
set "FE_APP=%ROOT%frontends\apps\simple-platform-vue"
set "DEST=%ROOT%MiGu.Server\wwwroot"
set "MIGU_BAT=%ROOT%MiGu.Server\build-and-run.bat"

set "NEED_INSTALL=0"
set "FORCE_PM="
set "START_MODE=platform"

:argloop
if "%~1"=="" goto argdone
if /I "%~1"=="--reinstall" set "NEED_INSTALL=1"
if /I "%~1"=="--npm" set "FORCE_PM=npm"
if /I "%~1"=="--pnpm" set "FORCE_PM=pnpm"
if /I "%~1"=="--no-start" set "START_MODE=none"
shift
goto argloop
:argdone

set "PM=%FORCE_PM%"
if "%PM%"=="" (
  where pnpm >nul 2>nul
  if not errorlevel 1 set "PM=pnpm"
)
if "%PM%"=="" set "PM=npm"

echo ============================================================
echo  Migu2.0 platform frontend build
echo    workspace : %FE_ROOT%
echo    wwwroot   : %DEST%
echo    pm        : %PM%
echo ============================================================

if not exist "%FE_ROOT%\package.json" (
  echo [ERROR] Missing %FE_ROOT%\package.json
  exit /b 1
)

pushd "%FE_ROOT%"
if errorlevel 1 exit /b 1

if not exist "node_modules" set "NEED_INSTALL=1"
if "%NEED_INSTALL%"=="1" (
  echo [1/3] %PM% install ...
  call %PM% install
  if errorlevel 1 ( popd & exit /b 1 )
) else (
  echo [1/3] node_modules exists, skip install. Use --reinstall to force.
)

echo [2/3] %PM% --filter simple-platform-vue build ...
if /I "%PM%"=="pnpm" (
  call pnpm --filter simple-platform-vue build
) else (
  pushd "%FE_APP%"
  call npm run build
  popd
)
if errorlevel 1 ( popd & exit /b 1 )
popd

if not exist "%FE_APP%\dist\index.html" (
  echo [ERROR] dist not found
  exit /b 1
)

echo [3/3] robocopy dist to wwwroot ...
if not exist "%DEST%" mkdir "%DEST%"
robocopy "%FE_APP%\dist" "%DEST%" /MIR /NFL /NDL /NJH /NJS /NP
set "RC=%ERRORLEVEL%"
if %RC% GEQ 8 exit /b %RC%

echo Done: %DEST%
if /I "%START_MODE%"=="none" exit /b 0
if not exist "%MIGU_BAT%" (
  echo [WARN] Missing %MIGU_BAT%
  exit /b 0
)
start "" cmd /k "%MIGU_BAT%"
exit /b 0
