# syntax=docker/dockerfile:1

# {{ parent_stack }}.{{ layer_name }}'s base image, built from a uv project (BUILD_CONTEXT in
# image.env) on a hardened Wolfi base: the locked environment (uv.lock) with the project
# installed into it. Each environment's overlay (<env>/Dockerfile) builds FROM it. The
# source layer's own Operations lint, test and scan the source; this layer builds, scans
# and pushes the image. The runtime runs as a non-root user and has no package manager.
#
# The base is pinned by digest, but `apk upgrade` and `apk add` fetch the current Wolfi
# packages on every build, so each rebuild picks up new fixes.

# The Python release line the lock targets. Wolfi ships its latest patch.
ARG PYTHON_VERSION=3.12
# uv, from its release image.
ARG UV_IMAGE=ghcr.io/astral-sh/uv:0.13.4
# cgr.dev/chainguard/wolfi-base:latest, pinned. Bump it by digest.
ARG WOLFI_BASE=cgr.dev/chainguard/wolfi-base@sha256:256c88bb066424045021090932d50be93c8e3f2ce3586707702a401b146f3e43

FROM ${UV_IMAGE} AS uv

FROM ${WOLFI_BASE} AS build
ARG PYTHON_VERSION
RUN apk upgrade --no-cache && apk add --no-cache "python-${PYTHON_VERSION}" ca-certificates
COPY --from=uv /uv /usr/local/bin/uv
WORKDIR /app
ENV UV_COMPILE_BYTECODE=1 \
    UV_LINK_MODE=copy \
    UV_PYTHON_DOWNLOADS=never \
    UV_PYTHON=/usr/bin/python${PYTHON_VERSION}
# Dependencies first (a cached layer), then the project, installed (not editable) so the
# runtime needs only the environment.
COPY pyproject.toml uv.lock README.md ./
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-install-project --no-dev
COPY src ./src
RUN --mount=type=cache,target=/root/.cache/uv \
    uv sync --frozen --no-dev --no-editable

FROM ${WOLFI_BASE} AS runtime
ARG PYTHON_VERSION
# Python and its CA bundle and a non-root user; then drop the package manager.
# wolfi-baselayout and busybox are added by name so that removing the wolfi-base
# meta-package (which pulls in apk) keeps them.
RUN apk upgrade --no-cache \
    && apk add --no-cache "python-${PYTHON_VERSION}" busybox wolfi-baselayout ca-certificates \
    && addgroup -g 1000 app \
    && adduser -D -u 1000 -G app -h /app -s /sbin/nologin app \
    && apk del --no-cache wolfi-base apk-tools wolfi-keys \
    && rm -rf /var/cache/apk /etc/apk /lib/apk
WORKDIR /app
COPY --from=build --chown=1000:1000 /app/.venv /app/.venv

ENV PATH="/app/.venv/bin:$PATH" \
    PYTHONUNBUFFERED=1 \
    PORT={{ container_port }}
USER 1000
EXPOSE {{ container_port }}

# The installed module, not a console script, whose shebang points at the build stage's
# environment. The app-python template's entry point; name your own.
CMD ["python", "-m", "src.main"]
