# Stage 1: Builder - Install dependencies using virtual environment
FROM python:3.11-slim AS builder

WORKDIR /build

# Create virtual environment
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Install MCA SDK with GCP auth support
COPY mca_sdk /build/mca_sdk
COPY setup.py /build/
COPY README.md /build/
RUN pip install --no-cache-dir ".[gcp-auth]"

# Install additional example dependencies
COPY sdk-examples/gcp-registry-example/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Stage 2: Runtime - Minimal production image
FROM python:3.11-slim

# Accept build arguments for OCI image labels
ARG BUILD_DATE
ARG VCS_REF

WORKDIR /app

# Create non-root user FIRST
RUN groupadd --gid 1000 appuser && \
    useradd --uid 1000 --gid 1000 --create-home --shell /bin/bash appuser && \
    chown appuser:appuser /app

# Switch to non-root user BEFORE copying application code
USER appuser

# Copy virtual environment from builder
COPY --from=builder --chown=appuser:appuser /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Copy example script as non-root user
COPY --chown=appuser:appuser sdk-examples/gcp-registry-example/main.py .

# Environment variables
ENV PYTHONUNBUFFERED=1

# OCI image labels for audit traceability
LABEL org.opencontainers.image.created="${BUILD_DATE}" \
      org.opencontainers.image.revision="${VCS_REF}" \
      org.opencontainers.image.title="MCA SDK Example: GCP Registry" \
      org.opencontainers.image.description="MCA SDK example using GCP Cloud Run Registry API"

# GCP Application Default Credentials must be mounted at runtime:
#   docker run -v "$HOME/.config/gcloud:/root/.config/gcloud" <image>
# Or set GOOGLE_APPLICATION_CREDENTIALS env var to a service account key file.

CMD ["python", "main.py"]
