# syntax=docker/dockerfile:1

##############
# Base Image #
##############
FROM python:3.13-slim-bookworm AS base

# Install system dependencies and Poetry in a dedicated layer (with BuildKit apt cache mounts)
RUN --mount=type=cache,id=apt-cache,target=/var/cache/apt \
    --mount=type=cache,id=apt-lists,target=/var/lib/apt/lists \
    rm -f /etc/apt/apt.conf.d/docker-clean && \
    echo 'Binary::apt::APT::Keep-Downloaded-Packages "true";' > /etc/apt/apt.conf.d/keep-cache && \
    apt-get update && \
    apt-get install -y --no-install-recommends \
        gcc \
        g++ \
        python3-dev \
        build-essential

# Install Poetry in a separate layer with aggressive caching
ENV POETRY_VERSION=2.0.1 \
    POETRY_HOME="/opt/poetry" \
    POETRY_CACHE_DIR=/opt/poetry-cache \
    POETRY_CONFIG_DIR=/opt/poetry-config

RUN pip install --upgrade pip && \
    pip install "poetry==${POETRY_VERSION}"

RUN poetry config virtualenvs.create false && \
    poetry config cache-dir $POETRY_CACHE_DIR

#########
# Build #
#########
FROM base AS builder

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

WORKDIR /app

# Copy dependency files first for better layer caching
COPY pyproject.toml poetry.lock ./

# Install dependencies with aggressive caching
RUN --mount=type=cache,target=/root/.cache/pip \
    --mount=type=cache,target=/opt/poetry-cache \
    poetry install --no-interaction --no-ansi --only main --no-root

###########
# Runtime #
###########
FROM python:3.13-slim-bookworm AS runtime

ARG ENV_APP_NAME
ARG ENV_VERSION
ARG ENV_HASH

ENV APP_NAME=$ENV_APP_NAME \
    VERSION=$ENV_VERSION \
    HASH=$ENV_HASH \
    PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1

WORKDIR /app

# Copy Python packages from builder (excluding Poetry and build tools)
COPY --from=builder /usr/local/lib/python3.13/site-packages /usr/local/lib/python3.13/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin

# Remove Poetry from runtime to keep image small
RUN pip uninstall -y poetry

# App code last for better layer reuse
COPY src /app/src/
COPY alembic.ini /app/
COPY alembic /app/alembic/
COPY docker-entrypoint.sh /app/
RUN chmod +x /app/docker-entrypoint.sh

ENTRYPOINT ["/app/docker-entrypoint.sh"]
