#!/bin/bash
set -e

# Ensure the virtualenv binaries are on PATH. Dependencies are installed
# to /opt/venv (not /app/.venv) to survive bind mounts in development.
if [ -d "/opt/venv/bin" ]; then
  export PATH="/opt/venv/bin:$PATH"
  export VIRTUAL_ENV="/opt/venv"
fi

# Only the backend service should run migrations and init_db
# Celery workers should skip this to avoid race conditions
# Check if the first argument contains 'celery' - if so, skip migrations
if [[ "$1" == *"celery"* ]]; then
  echo "Starting Celery worker (skipping migrations)"
else
  echo "Starting Backend"

  # Apply database migrations
  # Avoid installing the project in editable mode (which tries to write egg-info)
  # when running inside a bind-mounted volume with restricted permissions.
  # See: https://github.com/astral-sh/uv (use --no-project to skip project build)
  uv run --no-project alembic upgrade head

  # Initialize database (creates first superuser if needed)
  uv run --no-project python app/init_db.py
fi

# Execute the command passed to docker run
exec "$@"