# syntax=docker/dockerfile:1
# Multi-stage production build for the kaya-rbcs app on the Kaya framework.
# Base: alpine:3.24 (python3 = 3.14). Deps are installed into a venv in the
# builder; apk and pip caches use BuildKit cache mounts so they persist across
# builds and never land in the image layers. Requires BuildKit (default for
# `docker build` / `docker buildx` on modern daemons).

# --- Builder ---------------------------------------------------------------
FROM alpine:3.24 AS builder

RUN --mount=type=cache,target=/var/cache/apk \
    apk add python3

WORKDIR /build

COPY requirements.txt ./

RUN --mount=type=cache,target=/root/.cache/pip \
    python3 -m venv /opt/venv \
 && /opt/venv/bin/pip install -r requirements.txt

COPY pyproject.toml README.md ./
COPY src ./src

RUN --mount=type=cache,target=/root/.cache/pip \
    /opt/venv/bin/pip install --no-deps .

# --- Runtime ---------------------------------------------------------------
FROM alpine:3.24

RUN --mount=type=cache,target=/var/cache/apk \
    apk add python3 ca-certificates tzdata \
 && addgroup -S rbcs && adduser -S -G rbcs rbcs

COPY --from=builder /opt/venv /opt/venv

ENV PATH="/opt/venv/bin:${PATH}" \
    PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    RBCS_HOST=0.0.0.0 \
    RBCS_PORT=8080 \
    RBCS_MEMCACHE_HOST=memcached \
    RBCS_MEMCACHE_PORT=11211

USER rbcs

EXPOSE 8080

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD python3 -c "import socket, os; socket.create_connection(('127.0.0.1', int(os.environ['RBCS_PORT'])), timeout=3).close()"

ENTRYPOINT ["rbcs-server"]
