@echo off
chcp 65001 >nul
echo Starting AI-Core Document Parser gRPC Server...

set PORT=50051

echo Checking and cleaning up port %PORT%...
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :%PORT% ^| findstr LISTENING') do (
    echo Killing process %%a on port %PORT%...
    taskkill /F /PID %%a 2>nul
)
timeout /t 2 /nobreak >nul

cd /d %~dp0

echo Using virtual environment Python...
if exist "venv\Scripts\python.exe" (
    set PYTHON_CMD=%~dp0venv\Scripts\python.exe
) else (
    set PYTHON_CMD=py
)

echo Using Python: %PYTHON_CMD%
%PYTHON_CMD% --version

echo Checking port %PORT%...
%PYTHON_CMD% -c "import socket; s=socket.socket(); s.settimeout(1); r=s.connect_ex(('127.0.0.1',%PORT%)); s.close(); exit(0 if r!=0 else 1)" 2>nul
if %ERRORLEVEL% NEQ 0 (
    echo Port %PORT% is free, starting server...
) else (
    echo Port %PORT% is still in use, please check manually
    exit /b 1
)

echo Starting server on port %PORT%...
%PYTHON_CMD% main.py --port %PORT% --max-workers 10 --log-level INFO
