@echo off
setlocal EnableDelayedExpansion
cd /d "%~dp0\app"

rem Force UTF-8 for Python so prints with unicode chars don't crash on cp1252 consoles
set PYTHONIOENCODING=utf-8
set PYTHONUTF8=1
chcp 65001 >nul 2>&1

rem Set up a Python 3.11 venv if missing
if exist ".venv\Scripts\python.exe" goto :sync_deps

where uv >nul 2>&1
if errorlevel 1 (
    echo Installing the 'uv' tool to manage Python 3.11...
    powershell -ExecutionPolicy ByPass -Command "irm https://astral.sh/uv/install.ps1 | iex"
    if exist "%USERPROFILE%\.local\bin" set PATH=%USERPROFILE%\.local\bin;!PATH!
    if exist "%USERPROFILE%\.cargo\bin" set PATH=%USERPROFILE%\.cargo\bin;!PATH!
)

where uv >nul 2>&1
if errorlevel 1 (
    echo.
    echo   ERROR: uv install failed.
    echo   Install uv manually from https://docs.astral.sh/uv/
    echo   Or install Python 3.11 from https://www.python.org/downloads/
    echo.
    pause
    exit /b 1
)

echo Creating Python 3.11 venv via uv. May download Python the first time...
uv venv --seed --python 3.11 .venv
if errorlevel 1 (
    echo Failed to create venv.
    pause
    exit /b 1
)
.venv\Scripts\python.exe -m pip install --quiet --upgrade pip setuptools

:sync_deps
rem Always run pip install so any new exact pin in pyproject.toml or
rem proxy/requirements.txt is reflected in the venv. Pip re-resolves
rem exact pins automatically. We deliberately omit --upgrade because
rem that would also bump unpinned transitive deps to latest.
echo Syncing dependencies...
.venv\Scripts\python.exe -m pip install --quiet -e .[dev]
if errorlevel 1 (
    echo Install failed. Check your internet connection.
    pause
    exit /b 1
)
if exist "proxy\requirements.txt" (
    .venv\Scripts\python.exe -m pip install --quiet -r proxy\requirements.txt
)

rem Kill anything already on :9999 / :8188 so this launcher fully owns them
for %%p in (9999 8188) do (
    for /f "tokens=5" %%a in ('netstat -ano ^| findstr ":%%p " ^| findstr "LISTENING"') do (
        echo Stopping process %%a on port %%p...
        taskkill /F /PID %%a >nul 2>&1
    )
)
del /f /q .admin-ui.pid >nul 2>&1

echo.
echo Starting admin UI on http://localhost:9999 ...
echo Close this window to stop the server.
echo.

.venv\Scripts\python.exe admin-ui\server.py

pause
endlocal
