@echo off
chcp 65001 >nul
title HealthManager

set "PATH=D:\PostgreSQL\18\pgsql\bin;D:\Android\platform-tools;%PATH%"

echo ========================================
echo   HealthManager - Start Services
echo ========================================
echo.

echo [1/2] Starting PostgreSQL...
"D:\PostgreSQL\18\pgsql\bin\pg_ctl.exe" -D "D:\health_project\backend\pgdata" start 2>nul
if errorlevel 1 (echo   PG already running) else (echo   PG started)
echo.

echo [2/2] Starting .NET Backend...
start "Backend" cmd /k "cd /d D:\health_project\backend\src\Health.WebApi && dotnet run"
echo   Waiting for backend readiness...
set /a BACKEND_WAIT_SECONDS=0

:wait_backend
powershell -NoProfile -NonInteractive -Command "try { $response = Invoke-WebRequest -UseBasicParsing -Uri 'http://127.0.0.1:5000/openapi/v1.json' -TimeoutSec 2; if ($response.StatusCode -eq 200) { exit 0 } } catch {}; exit 1" >nul 2>&1
if not errorlevel 1 goto backend_ready
set /a BACKEND_WAIT_SECONDS+=1
if %BACKEND_WAIT_SECONDS% GEQ 30 goto backend_failed
timeout /t 1 /nobreak >nul
goto wait_backend

:backend_failed
echo.
echo ERROR: Backend failed to become ready within 30 seconds.
echo Check the Backend window for the detailed error.
pause
exit /b 1

:backend_ready
echo   Backend is ready at http://127.0.0.1:5000
echo.

echo All done. Phone connects via WiFi to this PC.
echo If your PC IP changed, rebuild app with:
echo   flutter run -d ^<device^> --dart-define=API_BASE_URL=http://^<pc-ip^>:5000
pause
