#!/bin/bash
set -euo pipefail

# ---------------------------------------------------------------------------
# PyCharter Docker Entrypoint
#
# Dispatches to the correct CLI command based on SERVICE env var or first arg.
# Optionally runs DB migrations before starting the service.
# Uses exec for proper PID 1 signal forwarding (graceful shutdown).
# ---------------------------------------------------------------------------

# --- Run DB migrations if requested ----------------------------------------
if [ "${RUN_MIGRATIONS:-false}" = "true" ]; then
    echo "[entrypoint] Running database migrations..."
    pycharter db upgrade || echo "[entrypoint] WARNING: Migration failed (may already be current)"
fi

# --- Dispatch based on first argument or SERVICE env var -------------------
SERVICE_CMD="${1:-${SERVICE:-api}}"

case "$SERVICE_CMD" in
    api)
        echo "[entrypoint] Starting PyCharter API server..."
        exec pycharter api \
            --host "${API_HOST:-0.0.0.0}" \
            --port "${API_PORT:-8002}" \
            --no-reload
        ;;
    worker)
        echo "[entrypoint] Starting PyCharter worker..."
        exec pycharter worker \
            --concurrency "${WORKER_CONCURRENCY:-5}" \
            --poll-interval "${WORKER_POLL_INTERVAL:-500}"
        ;;
    ui)
        echo "[entrypoint] Starting PyCharter UI server..."
        exec pycharter ui serve \
            --host "${UI_HOST:-0.0.0.0}" \
            --port "${UI_PORT:-3002}"
        ;;
    *)
        # Pass through any other command (e.g., bash, sh, pycharter db upgrade)
        exec "$@"
        ;;
esac
