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

set "PY_CMD="
where py >nul 2>nul
if not errorlevel 1 set "PY_CMD=py"
if not defined PY_CMD (
  where python >nul 2>nul
  if not errorlevel 1 set "PY_CMD=python"
)

if not defined PY_CMD (
  echo.
  echo [MelumiyaChat] Python was not found.
  echo Install Python 3.11 or newer, then run this file again.
  echo.
  pause
  exit /b 1
)

if not exist ".venv\Scripts\python.exe" (
  echo.
  echo [MelumiyaChat] First launch for this build.
  echo Creating the private local environment. This can take a few minutes once.
  echo.
  %PY_CMD% -m venv .venv
  if errorlevel 1 (
    echo Failed to create the local environment.
    pause
    exit /b 1
  )
)

call ".venv\Scripts\activate.bat"

python -c "import fastapi,uvicorn,httpx,pydantic" >nul 2>nul
if errorlevel 1 (
  echo [MelumiyaChat] Installing/updating the required local packages...
  python -m pip install --upgrade pip
  if errorlevel 1 goto :install_failed
  python -m pip install -r requirements.txt
  if errorlevel 1 goto :install_failed
)

if not exist ".env" copy ".env.example" ".env" >nul
exit /b 0

:install_failed
echo.
echo [MelumiyaChat] Setup could not finish.
echo Check your internet connection and try again.
echo.
pause
exit /b 1
