@echo off
setlocal EnableExtensions EnableDelayedExpansion
cd /d "%~dp0"

echo ============================================
echo Building NexaOffice WorkSuite - robust replace
echo ============================================

if not exist "assets\nexaoffice.ico" (
  echo ERROR: assets\nexaoffice.ico not found.
  pause
  exit /b 1
)
if not exist "nexaoffice_worksuite.spec" (
  echo ERROR: nexaoffice_worksuite.spec not found.
  pause
  exit /b 1
)

for /f %%i in ('python tools\build_timestamp.py') do set "STAMP=%%i"
if "!STAMP!"=="" set "STAMP=build_!RANDOM!"
set "DIST_DIR=%~dp0dist"
set "BUILD_DIR=%~dp0build"
set "DIST_NEW=%~dp0dist_new_!STAMP!"
set "BUILD_NEW=%~dp0build_new_!STAMP!"
set "BACKUP_ROOT=%~dp0build_backups"
set "DIST_OLD=%BACKUP_ROOT%\dist_old_!STAMP!"
set "BUILD_OLD=%BACKUP_ROOT%\build_old_!STAMP!"
set "LOG_DIR=%~dp0build_logs"
set "BUILD_LOG=%LOG_DIR%\build_!STAMP!.log"

echo.
echo Stopping old NexaOffice processes if they are running...
taskkill /F /IM NexaOffice.exe >nul 2>nul
taskkill /F /IM NexaOffice_WorkSuite.exe >nul 2>nul
timeout /t 1 /nobreak >nul

echo.
echo Preparing folders...
if not exist "%BACKUP_ROOT%" mkdir "%BACKUP_ROOT%" >nul 2>nul
if not exist "%LOG_DIR%" mkdir "%LOG_DIR%" >nul 2>nul
echo Build log: %BUILD_LOG%
echo NexaOffice build started at %DATE% %TIME% > "%BUILD_LOG%"

for /d %%F in ("%~dp0dist_new_*" "%~dp0build_new_*") do (
  if exist "%%~fF" rmdir /S /Q "%%~fF" >nul 2>nul
)
for /d /r . %%d in (__pycache__) do @if exist "%%d" rmdir /S /Q "%%d" 2>nul

python -m pip install -r requirements.txt >> "%BUILD_LOG%" 2>&1
if errorlevel 1 (
  echo Runtime dependency install failed. Check %BUILD_LOG%.
  pause
  exit /b 1
)
if exist "requirements-build.txt" (
  python -m pip install -r requirements-build.txt >> "%BUILD_LOG%" 2>&1
) else (
  python -m pip install "pyinstaller>=6.10,<7" pillow >> "%BUILD_LOG%" 2>&1
)
if errorlevel 1 (
  echo Build dependency install failed. Check %BUILD_LOG%.
  pause
  exit /b 1
)

echo.
echo Running release policy check...
python tools\release_policy_check.py --write-report >> "%BUILD_LOG%" 2>&1
if errorlevel 1 (
  echo Release policy check failed. If this is a 10-version milestone, create the milestone check doc first.
  echo Check log: %BUILD_LOG%
  pause
  exit /b 1
)

echo.
echo Running security preflight checks...
python tools\security_preflight.py --write-report >> "%BUILD_LOG%" 2>&1
if errorlevel 1 (
  echo Security preflight failed. Please check data\security_preflight_latest.json.
  echo Check log: %BUILD_LOG%
  pause
  exit /b 1
)

echo.
echo Running desktop preflight checks...
python tools\desktop_preflight.py >> "%BUILD_LOG%" 2>&1
if errorlevel 1 (
  echo Desktop preflight failed. Please check data\desktop_preflight_latest.json.
  pause
  exit /b 1
)

echo.
echo Building into temporary output folders...
pyinstaller --clean --noconfirm --distpath "%DIST_NEW%" --workpath "%BUILD_NEW%" "%~dp0nexaoffice_worksuite.spec" >> "%BUILD_LOG%" 2>&1
if errorlevel 1 (
  echo.
  echo Build failed.
  if exist "%DIST_NEW%" rmdir /S /Q "%DIST_NEW%" >nul 2>nul
  if exist "%BUILD_NEW%" rmdir /S /Q "%BUILD_NEW%" >nul 2>nul
  pause
  exit /b 1
)

if not exist "%DIST_NEW%\NexaOffice_WorkSuite\NexaOffice_WorkSuite.exe" (
  echo ERROR: Temporary build did not create expected EXE.
  echo Expected: %DIST_NEW%\NexaOffice_WorkSuite\NexaOffice_WorkSuite.exe
  pause
  exit /b 1
)

echo.
echo Replacing old dist/build automatically...

call :ReplaceFolder "%DIST_DIR%" "%DIST_NEW%" "%DIST_OLD%" "dist"
if errorlevel 1 (
  echo ERROR: Could not replace dist. New dist remains at:
  echo %DIST_NEW%
  pause
  exit /b 1
)

call :ReplaceFolder "%BUILD_DIR%" "%BUILD_NEW%" "%BUILD_OLD%" "build"
if errorlevel 1 (
  echo WARNING: Could not replace build folder. This does not affect the EXE.
)

echo.
echo Checking build result...
python tools\build_result_check.py >> "%BUILD_LOG%" 2>&1
if errorlevel 1 (
  echo ERROR: Build result check failed. Please check data\build_result_latest.json.
  echo Check log: %BUILD_LOG%
  pause
  exit /b 1
)

powershell -NoProfile -ExecutionPolicy Bypass -File tools\sign_windows_build.ps1 >> "%BUILD_LOG%" 2>&1
if errorlevel 1 (
  echo WARNING: Code signing helper reported a problem. If you do not have a signing certificate, this can be ignored. Check data\code_signing_latest.json.
)

python tools\build_manifest.py >> "%BUILD_LOG%" 2>&1
if errorlevel 1 (
  echo WARNING: Build manifest could not be created. Check log: %BUILD_LOG%
)

python tools\package_trust_report.py >> "%BUILD_LOG%" 2>&1
if errorlevel 1 (
  echo WARNING: Trust report could not be created. Check log: %BUILD_LOG%
)

powershell -NoProfile -ExecutionPolicy Bypass -File tools\windows_defender_scan.ps1 >> "%BUILD_LOG%" 2>&1
if errorlevel 1 (
  echo WARNING: Windows Defender scan helper reported a problem. This does not mean the build is unsafe; check data\windows_defender_scan_latest.json.
)

echo.
echo Done.
echo EXE: %~dp0dist\NexaOffice_WorkSuite\NexaOffice_WorkSuite.exe
echo Icon embedded from: %~dp0assets\nexaoffice.ico
echo Runtime data folder: %%APPDATA%%\NexaOffice\data
echo.
echo Security preflight:
echo %~dp0data\security_preflight_latest.json
echo Code signing report:
echo %~dp0data\code_signing_latest.json
echo Defender helper report:
echo %~dp0data\windows_defender_scan_latest.json
echo If Avast/Windows Defender still reports a generic detection, submit data\package_trust_report_latest.json and the EXE hash as a false-positive report.
echo If taskbar icon is old/blurry, unpin old shortcut and pin the new EXE again.
echo Build log:
echo %BUILD_LOG%
echo Build manifest:
echo %~dp0data\build_manifest_latest.json
echo Old locked folders, if any, were moved to:
echo %BACKUP_ROOT%
echo.
pause
exit /b 0

:ReplaceFolder
set "TARGET=%~1"
set "SOURCE=%~2"
set "BACKUP=%~3"
set "LABEL=%~4"

if exist "%TARGET%" (
  echo Removing old %LABEL%...
  rmdir /S /Q "%TARGET%" >nul 2>nul
  if exist "%TARGET%" (
    echo Old %LABEL% is locked. Moving it to backup...
    move "%TARGET%" "%BACKUP%" >nul 2>nul
    if exist "%TARGET%" (
      echo Could not move locked old %LABEL%. Trying copy fallback...
      if not exist "%TARGET%__replace_tmp" mkdir "%TARGET%__replace_tmp" >nul 2>nul
      xcopy "%SOURCE%" "%TARGET%__replace_tmp" /E /I /Y >nul
      if errorlevel 1 exit /b 1
      echo New %LABEL% copied to %TARGET%__replace_tmp because old folder is locked.
      echo Close apps using %LABEL%, then rename it manually if needed.
      exit /b 1
    )
  )
)

move "%SOURCE%" "%TARGET%" >nul 2>nul
if errorlevel 1 (
  echo Move failed for %LABEL%. Trying xcopy fallback...
  if not exist "%TARGET%" mkdir "%TARGET%" >nul 2>nul
  xcopy "%SOURCE%" "%TARGET%" /E /I /Y >nul
  if errorlevel 1 exit /b 1
  rmdir /S /Q "%SOURCE%" >nul 2>nul
)
exit /b 0
