# 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 first (proper pip install for metadata and dependencies)
COPY mca_sdk /build/mca_sdk
COPY setup.py /build/
COPY README.md /build/
RUN pip install --no-cache-dir .

# Install additional dependencies
COPY sdk-examples/predictive-model/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 (includes SDK installed via pip)
COPY --from=builder --chown=appuser:appuser /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Copy application code as non-root user (atomic ownership)
COPY --chown=appuser:appuser sdk-examples/predictive-model/instrumented_model.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: Internal Model" \
      org.opencontainers.image.description="Predictive ML model instrumented with MCA SDK"

# No healthcheck for batch jobs - Docker monitors PID 1 automatically
# If the Python process (PID 1) crashes, container stops immediately

# Run the instrumented script
CMD ["python", "instrumented_model.py"]
