# 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 base dependencies (FastAPI, uvicorn, pybreaker)
COPY sdk-examples/vendor-bridge/requirements-base.txt requirements.txt
RUN pip install --no-cache-dir -r requirements.txt

# Copy local MCA SDK source and install
COPY mca_sdk /build/mca_sdk
COPY setup.py /build/
COPY README.md /build/
RUN pip install --no-cache-dir .[vendor]

# 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

# Install curl and ca-certificates for efficient health checks and TLS support
# curl: 1.5MB vs 20-30MB per Python interpreter spawn
# ca-certificates: Required for TLS handshakes if curl is used for external calls
RUN apt-get update && \
    apt-get install -y --no-install-recommends curl ca-certificates && \
    rm -rf /var/lib/apt/lists/*

# 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 application code as non-root user
COPY --chown=appuser:appuser sdk-examples/vendor-bridge/mock_vendor_api.py .
COPY --chown=appuser:appuser sdk-examples/vendor-bridge/api_to_otlp_bridge.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: Vendor Bridge" \
      org.opencontainers.image.description="External vendor API bridge instrumented with MCA SDK"

# Expose vendor API port
EXPOSE 8080

# Health check for vendor API with timeout for fast failure
# -f: fail on HTTP errors, -s: silent mode, -S: show errors only, -L: follow redirects
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
  CMD curl -fsSL --max-time 2 http://localhost:8080/health > /dev/null || exit 1

# Default command (can be overridden in docker-compose)
CMD ["python", "mock_vendor_api.py"]
