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

call :resolve_base_python
if errorlevel 1 (
  echo Could not find a working Python interpreter.
  echo Please install Python 3.11+ first.
  exit /b 1
)

if not exist ".venv\Scripts\python.exe" (
  echo Dang tao virtual environment...
  %BASE_PYTHON% -m venv .venv
  if errorlevel 1 (
    echo Khong tao duoc .venv
    exit /b 1
  )
)

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

echo Dang cai/cap nhat thu vien can thiet...
"%VENV_PY%" -m pip install --disable-pip-version-check -r requirements.txt
if errorlevel 1 (
  echo Cai thu vien that bai.
  exit /b 1
)

echo Dang khoi dong local server o nen...
call "scripts\run_local_server.bat"

echo Dang doi local host san sang...
set "SERVER_READY="
for /L %%I in (1,1,30) do (
  powershell -NoProfile -Command "try { Invoke-WebRequest -UseBasicParsing 'http://127.0.0.1:8000/health' -TimeoutSec 2 ^| Out-Null; exit 0 } catch { exit 1 }" >nul 2>nul
  if not errorlevel 1 (
    set "SERVER_READY=1"
    goto server_ready
  )
  timeout /t 1 /nobreak >nul
)

:server_ready
if not defined SERVER_READY (
  echo Local host chua san sang sau 30 giay.
  exit /b 1
)

echo Dang mo desktop app...
"%VENV_PY%" main.py
exit /b %errorlevel%

:resolve_base_python
set "BASE_PYTHON="

py -3.11 --version >nul 2>&1
if not errorlevel 1 (
  set "BASE_PYTHON=py -3.11"
  exit /b 0
)

py --version >nul 2>&1
if not errorlevel 1 (
  set "BASE_PYTHON=py"
  exit /b 0
)

python --version >nul 2>&1
if not errorlevel 1 (
  set "BASE_PYTHON=python"
  exit /b 0
)

exit /b 1
