FROM python:3.12-slim AS base

ENV PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1

WORKDIR /app

# Install uv
COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv

# ── Build stage ──
FROM base AS builder

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

COPY pyproject.toml uv.lock* ./
# ``--locked`` (not ``--frozen``) verifies pyproject.toml and uv.lock are
# in sync; the build fails if a contributor added a dep to pyproject
# without running ``uv lock``. ``--frozen`` would silently install only
# what's in the lock and ship a broken image — that exact failure mode
# rolled back a prod deploy on 2026-04-27 (the ``mcp`` package was in
# pyproject.toml but missing from uv.lock, so the backend crashed at
# import). Catching the inconsistency in the build is much cheaper.
#
# This build is main-only, so it used to be the *only* place the check ran and
# it always fired after merge. The Backend Lint job now runs ``uv lock --check``
# on every PR; keep both — this one is what actually gates the artefact.
RUN uv sync --no-dev --locked

COPY . .

# ── Runtime stage ──
FROM base AS runtime

COPY --from=builder /app /app

EXPOSE 8000

# ``--proxy-headers`` + ``--forwarded-allow-ips=*`` is REQUIRED behind
# nginx so uvicorn picks up X-Forwarded-Proto and emits HTTPS in
# redirects (e.g. trailing-slash 307 on /api/v1/mcp). Without this,
# MCP clients hitting the bare ``/api/v1/mcp`` get redirected to
# ``http://``, which fails on prod where TLS is terminated upstream.
CMD ["/app/.venv/bin/uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--proxy-headers", "--forwarded-allow-ips=*"]
