#
# BACKEND DOCKERFILE
#
# Multi-stage image for the FastAPI + LiveKit Agent backend using uv.
# - production: smallest runtime image with gunicorn/uvicorn worker
# - development: hot-reload friendly image with full toolchain
# - builder: installs dependencies once for reuse across stages
#
# Keep dependency definitions aligned with docs/architecture.md.

FROM python:3.12-slim AS base

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1 \
    UV_PROJECT_ENVIRONMENT=/app/.venv \
    UV_LINK_MODE=copy

RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        build-essential \
        curl \
        libpq-dev \
    && rm -rf /var/lib/apt/lists/*

RUN groupadd --system app && useradd --system --home /app --gid app app
WORKDIR /app

# Install uv globally so subsequent stages share the toolchain.
RUN pip install --upgrade pip uv

# ------------------------------------------------------------------------------
# Builder: install prod dependencies into an in-project virtualenv
# ------------------------------------------------------------------------------
FROM base AS builder

COPY . .
RUN test -f pyproject.toml || (echo "pyproject.toml is required for uv sync"; exit 1)
RUN if [ -f uv.lock ]; then \
      uv sync --frozen --no-dev --compile-bytecode; \
    else \
      uv sync --no-dev --compile-bytecode; \
    fi

# ------------------------------------------------------------------------------
# Production: minimal runtime image with gunicorn as the entrypoint
# ------------------------------------------------------------------------------
FROM python:3.12-slim AS production

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1

RUN apt-get update \
    && apt-get install -y --no-install-recommends libpq5 \
    && rm -rf /var/lib/apt/lists/*

RUN groupadd --system app && useradd --system --home /app --gid app app
WORKDIR /app

COPY --from=builder --chown=app:app /app /app
ENV PATH="/app/.venv/bin:$PATH"

USER app
EXPOSE 8000
CMD ["gunicorn", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "app.main:app", "--bind", "0.0.0.0:8000"]

# ------------------------------------------------------------------------------
# Development: includes dev dependencies and keeps uvicorn reload-friendly
# ------------------------------------------------------------------------------
FROM base AS development

COPY . .
RUN test -f pyproject.toml || (echo "pyproject.toml is required for uv sync"; exit 1)
RUN if [ -f uv.lock ]; then \
      uv sync --frozen --dev --compile-bytecode; \
    else \
      uv sync --dev --compile-bytecode; \
    fi

ENV PATH="/app/.venv/bin:$PATH"
USER app
EXPOSE 8000
