#!/bin/sh
set -e

echo "[entrypoint] Starting Brunix Engine (gRPC :50051)..."
python src/server.py &
ENGINE_PID=$!

echo "[entrypoint] Starting OpenAI Proxy (HTTP :8000)..."
uvicorn openai_proxy:app --host 0.0.0.0 --port 8000 --workers 4 --app-dir src &
PROXY_PID=$!

wait_any() {
    while kill -0 $ENGINE_PID 2>/dev/null && kill -0 $PROXY_PID 2>/dev/null; do
        sleep 2
    done

    if ! kill -0 $ENGINE_PID 2>/dev/null; then
        echo "[entrypoint] Engine died — stopping proxy"
        kill $PROXY_PID 2>/dev/null
        exit 1
    fi

    if ! kill -0 $PROXY_PID 2>/dev/null; then
        echo "[entrypoint] Proxy died — stopping engine"
        kill $ENGINE_PID 2>/dev/null
        exit 1
    fi
}

wait_any