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

set "PYTHON_CMD="

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

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

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

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

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

if not exist "%BACKUP_DIR%" (
  echo Backup folder not found: %BACKUP_DIR%
  exit /b 1
)

set /a COUNT=0
for %%F in ("%BACKUP_DIR%\po_internal_code_*.zip") do (
  set /a COUNT+=1
  set "BACKUP_!COUNT!=%%~fF"
  echo [!COUNT!] %%~nxF
)

if %COUNT% EQU 0 (
  echo Khong tim thay file backup nao trong %BACKUP_DIR%
  exit /b 1
)

set /p "CHOICE=Nhap so thu tu backup can restore: "
if not defined CHOICE (
  echo Chua chon backup.
  exit /b 1
)

set "SELECTED=!BACKUP_%CHOICE%!"
if not defined SELECTED (
  echo Lua chon khong hop le.
  exit /b 1
)

echo Dang restore:
echo   !SELECTED!

%PYTHON_CMD% restore_backup.py "!SELECTED!"
if errorlevel 1 (
  echo Restore failed.
  exit /b 1
)

echo Restore finished.
echo Thu muc phuc hoi nam trong restored_backups\
