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

rem Force UTF-8 so Python doesn'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

:sync_deps
rem Always run pip install so any new exact pin in proxy/requirements.txt
rem is reflected in the venv. We omit --upgrade because that would also
rem bump unpinned transitive deps to latest and can break things.
echo Syncing dependencies...
.venv\Scripts\python.exe -m pip install --quiet -r proxy\requirements.txt
.venv\Scripts\python.exe -m pip install --quiet fastapi uvicorn

rem Kill anything already on :9998 / :8188
for %%p in (9998 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 .launcher.pid >nul 2>&1

echo.
echo Starting fal ComfyUI launcher on http://localhost:9998 ...
echo Close this window to quit.
echo.

.venv\Scripts\python.exe launcher\server.py

pause
endlocal
