@echo off
chcp 1252 >nul
setlocal EnableExtensions

REM ===================== PARAMS =====================
set "ROOT=C:\Users\miche\PycharmProjects\Ratio_Inventaires"
set "DEV_XLSM=%ROOT%\Excel\dev\Ratio_dev.xlsm"
set "PROD_DIR=%ROOT%\Excel\prod"
set "PROD_XLSM=%PROD_DIR%\Ratio_prod.xlsm"
set "VERSION_TXT=%ROOT%\Excel\dev\VERSION.txt"
set "SHEET_NAME=Tableau de bord"
set "CELL_ADDR=U1"

echo.
echo === [1/4] Prep ===============================================

if not exist "%PROD_DIR%" md "%PROD_DIR%"

if not exist "%DEV_XLSM%" goto ERR_NO_DEV

if not exist "%VERSION_TXT%" (
  >"%VERSION_TXT%" echo 1.0.0
  echo [INFO] VERSION.txt created with 1.0.0
)

for /f %%i in ('powershell -NoProfile -Command "(Get-Date).ToString('yyyy_MM_dd')"') do set "DATESTAMP=%%i"
set "ARCHIVE_FILE=%PROD_DIR%\Ratio_prod_%DATESTAMP%.xlsm"

echo.
echo === [2/4] Lire VERSION.txt et maj cellule =====================

for /f "usebackq delims=" %%v in ("%VERSION_TXT%") do set "NEW_VER=%%v"
set "NEW_VER=%NEW_VER: =%"
if "%NEW_VER%"=="" goto ERR_EMPTY_VER
echo    Version: %NEW_VER%

REM Mise a jour de P1 dans DEV via VBS (macros & evenements OFF)
cscript //nologo "%ROOT%\Scripts\set_cell_silent.vbs" "%DEV_XLSM%" "%SHEET_NAME%" "%CELL_ADDR%" "%NEW_VER%"
if errorlevel 1 goto U1_FAIL

echo [OK] U1 updated on DEV: %NEW_VER%
goto AFTER_U1

:U1_FAIL
echo [WARN] U1 update failed on DEV (continuing).

:AFTER_U1

echo.
echo === [3/4] Backup PROD et purge archives ======================

if not exist "%PROD_XLSM%" goto NO_BACKUP
echo    Backup -> "%ARCHIVE_FILE%"
copy /Y "%PROD_XLSM%" "%ARCHIVE_FILE%" >nul
goto AFTER_BACKUP

:NO_BACKUP
echo    Pas de PROD a sauvegarder.

:AFTER_BACKUP

REM Garder uniquement les 5 dernieres archives
powershell -NoProfile -Command "Get-ChildItem -Path '%PROD_DIR%' -Filter 'Ratio_prod_20*_??_??.xlsm' | Sort-Object LastWriteTime -Descending | Select-Object -Skip 5 | Remove-Item -Force -ErrorAction SilentlyContinue"

echo.
echo === [4/4] Copier DEV -> PROD =================================

copy /Y "%DEV_XLSM%" "%PROD_XLSM%"
if errorlevel 1 goto ERR_COPY

>"%PROD_DIR%\VERSION.txt" echo %NEW_VER%

echo.
echo [OK] Termine :
echo    Version  : %NEW_VER%
echo    PROD     : "%PROD_XLSM%"
echo    VERSION  : "%PROD_DIR%\VERSION.txt"
echo.
endlocal & exit /b 0

REM ===================== ERRORS =====================
:ERR_NO_DEV
echo [ERROR] DEV file not found: "%DEV_XLSM%"
endlocal & exit /b 1

:ERR_EMPTY_VER
echo [ERROR] VERSION.txt is empty. Put a version like 1.8.3 and rerun.
endlocal & exit /b 1

:ERR_COPY
echo [ERROR] Copy DEV -> PROD failed.
endlocal & exit /b 1
