@echo off
REM ========================================
REM Church SongLyric - All Services Launcher
REM ========================================
REM This script starts MongoDB, Backend, and Frontend in hidden windows

title Church SongLyric - Service Launcher
color 0A

echo.
echo ========================================
echo CHURCH SONGLYRIC SERVICE LAUNCHER
echo ========================================
echo.

REM Check if MongoDB is running
echo [1/4] Checking MongoDB...
tasklist /FI "IMAGENAME eq mongod.exe" 2>NUL | find /I /N "mongod.exe">NUL
if "%ERRORLEVEL%"=="0" (
    echo   MongoDB is already running
) else (
    echo   Starting MongoDB...
    start "" "C:\Program Files\MongoDB\Server\8.0\bin\mongod.exe" --dbpath "C:\data\db"
    timeout /t 3 /nobreak >nul
    echo   MongoDB started
)

echo.
echo [2/4] Starting Backend Server (Flask)...
cd /d "%~dp0backend"
start "Church Backend" /MIN cmd /c "venv\Scripts\python.exe app.py"
timeout /t 3 /nobreak >nul
echo   Backend starting on port 5000...

echo.
echo [3/4] Starting Frontend Server (React)...
cd /d "%~dp0frontend"
start "Church Frontend" /MIN cmd /c "npm start"
timeout /t 5 /nobreak >nul
echo   Frontend starting on port 3000...

echo.
echo [4/4] Verifying services...
timeout /t 5 /nobreak >nul

REM Test backend
powershell -Command "try { $r = Invoke-RestMethod -Uri 'http://localhost:5000/api/health' -TimeoutSec 5; Write-Host '  Backend: ONLINE - Status:' $r.status -ForegroundColor Green } catch { Write-Host '  Backend: Starting... (wait 10 seconds)' -ForegroundColor Yellow }"

REM Test frontend
powershell -Command "try { $r = Invoke-WebRequest -Uri 'http://localhost:3000' -TimeoutSec 5 -UseBasicParsing; Write-Host '  Frontend: ONLINE' -ForegroundColor Green } catch { Write-Host '  Frontend: Starting... (wait 10 seconds)' -ForegroundColor Yellow }"

echo.
echo ========================================
echo ALL SERVICES STARTED!
echo ========================================
echo.
echo Access URLs:
echo   Local:    http://localhost:3000
echo   LAN:      http://192.168.10.178:3000
echo   External: http://houseofprayer.ddns.net:3000
echo.
echo Backend API:
echo   Local:    http://localhost:5000
echo   External: http://houseofprayer.ddns.net:8080
echo.
echo Services running in background (minimized windows)
echo Close those windows to stop the servers
echo.
echo Press any key to open the app in browser...
pause >nul

start http://localhost:3000

echo.
echo ========================================
echo App opened in browser!
echo ========================================
echo.
echo To stop all services, run: stop-all-services.bat
echo.
pause
