@echo off
chcp 65001 >nul
cd /d "%~dp0"
echo.
echo Starting I'M TranslAID...
echo.

if not exist "python\python.exe" (
    echo [ERROR] The python folder is missing or incomplete.
    echo         Please re-extract the IMLAIDDesktop package from the original ZIP.
    pause
    exit /b 1
)

if not exist "app.py" (
    echo [ERROR] app.py not found. Please re-extract the package.
    pause
    exit /b 1
)

if exist .ptilock if exist .port (
    set /p PORT=<.port
    python\python.exe -c "import urllib.request; urllib.request.urlopen('http://localhost:%PORT%/ping')" >nul 2>&1
    if not errorlevel 1 (
        echo I'M TranslAID is already running. Opening browser...
        start "" "http://localhost:%PORT%"
        exit /b 0
    )
)

if exist .port del .port

wmic process where "name='python.exe' and commandline like '%%%~dp0app.py%%'" call terminate >nul 2>&1

start "I'M TranslAID" /D "%~dp0" python\python.exe app.py

echo Waiting for server to start...
:waitport
timeout /t 1 /nobreak >nul
if not exist .port goto waitport

set /p PORT=<.port

:waitping
timeout /t 1 /nobreak >nul
python\python.exe -c "import urllib.request; urllib.request.urlopen('http://localhost:%PORT%/ping')" >nul 2>&1
if errorlevel 1 goto waitping

start "" "http://localhost:%PORT%"
