#!/usr/bin/env bash
set -euo pipefail

ROLE="${ROLE:-web}"                       # web | worker | beat
PORT="${PORT:-8080}"                      # web poort (in k8s vaak 8080)
WORKERS="${WORKERS:-1}"                   # gunicorn workers (web)
WORKER_CLASS="${WORKER_CLASS:-gevent}"    # web: gevent|sync
WORKER_CONN="${WORKER_CONN:-100}"         # web: --worker-connections
LOGLEVEL="${LOGLEVEL:-info}"
MAX_REQ="${MAX_REQUESTS:-1000}"
MAX_JITTER="${MAX_REQUESTS_JITTER:-100}"
COMPONENT_NAME="${COMPONENT_NAME:-eveai_app}"  # component name for dynamic import

case "$ROLE" in
  web)
    echo "[start] role=web component=$COMPONENT_NAME port=$PORT workers=$WORKERS class=$WORKER_CLASS"
    exec gunicorn -w "$WORKERS" -k "$WORKER_CLASS" \
      -b "0.0.0.0:${PORT}" --worker-connections "$WORKER_CONN" \
      --access-logfile - --error-logfile - --log-level "$LOGLEVEL" \
      --graceful-timeout 25 --timeout 30 --keep-alive 5 \
      --max-requests "$MAX_REQ" --max-requests-jitter "$MAX_JITTER" \
      scripts.run:app
    ;;
  worker)
    echo "[start] role=worker component=$COMPONENT_NAME"
    CONCURRENCY="${CELERY_CONCURRENCY:-2}"
    exec celery -A scripts.run worker \
      -Q ${CELERY_QUEUE_NAME} \
      --loglevel="${CELERY_LOGLEVEL:-INFO}" \
      --concurrency="${CONCURRENCY}" \
      --max-tasks-per-child="${CELERY_MAX_TASKS_PER_CHILD:-1000}" \
      --prefetch-multiplier="${CELERY_PREFETCH:-1}" -O fair
    ;;
  beat)
    echo "[start] role=beat component=$COMPONENT_NAME"
    exec celery -A scripts.run beat \
      --loglevel="${CELERY_LOGLEVEL:-INFO}"
    ;;
  *)
    echo "Unknown ROLE=$ROLE" >&2; exit 1
    ;;
esac
