@echo off
setlocal enabledelayedexpansion
chcp 65001 >nul
title Setup and run SunnyERPApp Local Server

:: --- 1. Kiem tra quyen admin ---
net session >nul 2>&1
if %errorLevel% neq 0 (
  echo Vui long chay script nay bang quyen Administrator de cai Python/venv.
  pause
  exit /b 1
)

:: --- 2. Lay duong dan project ---
set "SCRIPT_DIR=%~dp0"
set "PROJECT_DIR=%SCRIPT_DIR%.."
cd /d "%PROJECT_DIR%"

if not exist "%PROJECT_DIR%\requirements.txt" (
  echo Khong tim thay requirements.txt tai: %PROJECT_DIR%
  pause
  exit /b 1
)

:: --- 3. Python ---
where python >nul 2>&1
if %errorLevel% neq 0 (
  echo Python chua duoc cai dat. Dang cai Python 3.11...
  set "PYTHON_INSTALLER=%TEMP%\python-3.11.9-amd64.exe"
  powershell -NoProfile -ExecutionPolicy Bypass -Command "Invoke-WebRequest -Uri 'https://www.python.org/ftp/python/3.11.9/python-3.11.9-amd64.exe' -OutFile '%PYTHON_INSTALLER%'"
  start /wait "" "%PYTHON_INSTALLER%" /quiet InstallAllUsers=1 PrependPath=1 Include_pip=1 Include_test=0
  del /f "%PYTHON_INSTALLER%" >nul 2>&1
  timeout /t 5 /nobreak >nul
)

set "PYTHON_CMD=python"
python --version >nul 2>&1
if %errorLevel% neq 0 (
  echo Python van chua san sang. Kiem tra lai PATH hoac cai thu cong.
  pause
  exit /b 1
)

:: --- 4. Tao venv neu chua co ---
if not exist ".venv\Scripts\python.exe" (
  echo Tao moi truong ao .venv...
  "%PYTHON_CMD%" -m venv .venv
)

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

:: --- 5. Cai dat thu vien ---
echo Dang cap nhat pip trong .venv...
"%VENV_PY%" -m pip install --upgrade pip

echo Dang cai dependencies tu requirements.txt...
"%VENV_PY%" -m pip install -r requirements.txt

:: --- 6. Dam bao uvicorn ---
"%VENV_PY%" -m pip install "uvicorn[standard]"

:: --- 7. Chay backend ---
echo.
echo =====================
echo  Khoi dong local server
echo =====================
echo Backend se chay tai: http://127.0.0.1:8000
echo Nhan Ctrl+C de dung server.
echo.

:: Chay thu backend
"%VENV_PY%" -m uvicorn local_server.app:app --host 127.0.0.1 --port 8000 --log-level info

pause
