# 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"

# Upgrade wheel to remediate CVE-2026-24049 (privilege escalation via malicious wheel file)
RUN pip install --no-cache-dir "wheel>=0.46.2"

# 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/internal-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/internal-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"

# HEALTHCHECK: liveness probe for a batch container. `os.path.exists('/proc/1/status')`
# is true while PID 1 (the python interpreter) is alive. If the script crashes
# or deadlocks on I/O, the probe returns non-zero and Docker marks the
# container unhealthy. Honest framing: this is a liveness check, not a
# readiness check — it tells you "PID 1 is alive", nothing more. Uses only
# the stdlib so no procps install is required.
# TODO(story-6-14-followup-pin-digests): pin python:3.11-slim to a digest.
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD python -c "import os, sys; sys.exit(0 if os.path.exists('/proc/1/status') else 1)" || exit 1

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