# syntax=docker/dockerfile:1
# Multi-stage build: uv resolves the locked [service] environment in the
# builder; the runtime stage is a plain slim Python image with the venv,
# a non-root user, and a single-worker uvicorn entrypoint (the memory vault
# is per-process — create_app refuses divergent multi-worker setups).

FROM ghcr.io/astral-sh/uv:python3.12-bookworm-slim AS builder
ENV UV_COMPILE_BYTECODE=1 \
    UV_LINK_MODE=copy \
    UV_PYTHON_DOWNLOADS=never
WORKDIR /app

# dependency layer first (cache-friendly): lockfile only, no project source
COPY pyproject.toml uv.lock ./
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-install-project --no-dev --extra service --extra redis

COPY src ./src
COPY README.md ./
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-dev --no-editable --extra service --extra redis

# fast-tier detection model (dev-group-only in the lockfile, needed at runtime)
RUN --mount=type=cache,target=/root/.cache/uv \
    uv pip install \
    https://github.com/explosion/spacy-models/releases/download/en_core_web_sm-3.8.0/en_core_web_sm-3.8.0-py3-none-any.whl


FROM python:3.12-slim-bookworm AS runtime
RUN groupadd -r pii && useradd -r -g pii -d /app pii
WORKDIR /app
COPY --from=builder /app/.venv /app/.venv
ENV PATH="/app/.venv/bin:$PATH" \
    PYTHONUNBUFFERED=1
USER pii
EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=3s --start-period=20s --retries=3 \
    CMD ["python", "-c", "import urllib.request, sys; sys.exit(0 if urllib.request.urlopen('http://127.0.0.1:8000/healthz', timeout=2).status == 200 else 1)"]

CMD ["uvicorn", "--factory", "maskrelay.service.app:create_app", \
     "--host", "0.0.0.0", "--port", "8000"]
