# BookWyrm Base Multi-stage Build
# Production-optimized build targeting ~400MB final image size
# Shared base image for BookWyrm web and worker containers

# Build stage - Install dependencies and prepare optimized source
FROM python:3.11-slim AS builder

LABEL org.opencontainers.image.title="BookWyrm Base" \
      org.opencontainers.image.description="Shared base image for BookWyrm social reading platform" \
      org.opencontainers.image.source="https://github.com/bookwyrm-social/bookwyrm" \
      org.opencontainers.image.vendor="Keyboard Vagabond"

# Install build dependencies in a single layer
RUN apt-get update && apt-get install -y --no-install-recommends \
    git \
    build-essential \
    libpq-dev \
    libffi-dev \
    libssl-dev \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean

WORKDIR /app

# Clone source with minimal depth and remove git afterwards to save space
RUN git clone -b production --depth 1 --single-branch \
    https://github.com/bookwyrm-social/bookwyrm.git . \
    && rm -rf .git

# Create virtual environment and install Python dependencies
RUN python3 -m venv /opt/venv \
    && /opt/venv/bin/pip install --no-cache-dir --upgrade pip setuptools wheel \
    && /opt/venv/bin/pip install --no-cache-dir -r requirements.txt \
    && find /opt/venv -name "*.pyc" -delete \
    && find /opt/venv -name "__pycache__" -type d -exec rm -rf {} + \
    && find /opt/venv -name "*.pyo" -delete

# Remove unnecessary files from source to reduce image size
# Note: .dockerignore will exclude __pycache__, *.pyc, etc. automatically
# Note: Keep /app/locale for i18n support (translations)
RUN rm -rf \
    /app/.github \
    /app/docker \
    /app/nginx \
    /app/bw-dev \
    /app/bookwyrm/tests \
    /app/bookwyrm/test* \
    /app/*.md \
    /app/LICENSE \
    /app/.gitignore \
    /app/requirements.txt

# Runtime stage - Minimal runtime environment
FROM python:3.11-slim AS runtime

# Set environment variables
ENV TZ=UTC \
    PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    PATH="/opt/venv/bin:$PATH" \
    VIRTUAL_ENV="/opt/venv"

# Install only essential runtime dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
    libpq5 \
    curl \
    gettext \
    && apt-get autoremove -y \
    && apt-get clean \
    && rm -rf /var/lib/apt/lists/*

# Create bookwyrm user for security
RUN useradd --create-home --shell /bin/bash --uid 1000 bookwyrm

# Copy virtual environment and optimized source
COPY --from=builder /opt/venv /opt/venv
COPY --from=builder /app /app

# Set working directory and permissions
WORKDIR /app
RUN chown -R bookwyrm:bookwyrm /app \
    && mkdir -p /app/mediafiles /app/static /app/images \
    && chown -R bookwyrm:bookwyrm /app/mediafiles /app/static /app/images

# Default user
USER bookwyrm

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
    CMD python manage.py check --deploy || exit 1