# syntax=docker/dockerfile:1
# In-memory messenger, lab 1. Build: docker build -t mtusi-messenger:lab1 .
#
# Python is interpreted, so there is no separate compile stage; the image
# contains only the interpreter, locked dependencies and the source code.
# Base image is pinned by version AND digest (python 3.13.15, Debian 12 bookworm).
FROM python:3.13.15-slim-bookworm@sha256:2325bb286ec344af3e5898cc224b5844e2707ac6e26b1632516fd3edc84a5e26

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

WORKDIR /app

# 1. Dependencies first (layer cache survives source edits). Every package,
#    including transitive ones, is pinned with sha256 hashes in requirements.txt;
#    --no-deps guarantees nothing outside the lock file is installed.
COPY requirements.txt ./
RUN pip install --root-user-action=ignore --require-hashes --no-deps -r requirements.txt

# 2. Unprivileged runtime user. Code stays owned by root, so the process
#    cannot modify its own code.
RUN groupadd --system --gid 10001 app \
    && useradd --system --uid 10001 --gid app --no-create-home --shell /usr/sbin/nologin app

COPY src/ ./src/
# Course contract, served read-only at /openapi.json for Swagger UI (/docs).
COPY contracts/openapi.json ./contracts/openapi.json

# Defaults make `docker run` work without an .env file; --env-file overrides them.
ENV PYTHONPATH=/app/src \
    APP_HOST=0.0.0.0 \
    APP_PORT=8080 \
    APP_ENV=lab \
    LOG_LEVEL=info \
    SHUTDOWN_TIMEOUT_SECONDS=8 \
    DOCS_ENABLED=true

USER app:app
EXPOSE 8080
STOPSIGNAL SIGTERM

HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=3 \
    CMD ["python", "-m", "messenger.healthcheck"]

# Exec form: the Python server is PID 1 and receives SIGTERM directly (no shell in between).
CMD ["python", "-m", "messenger"]
