==# Multi-stage build for production optimization
FROM python:3.11-slim as builder

# Set build arguments
ARG BUILD_DATE
ARG VERSION
ARG VCS_REF

# Install build dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    curl \
    git \
    libpq-dev \
    && rm -rf /var/lib/apt/lists/*

# Create build directory
WORKDIR /build

# Copy requirements first for better caching
COPY requirements.txt .

# Install Python dependencies
RUN pip install --no-cache-dir --user -r requirements.txt

# Copy source code
COPY . .

# Install the package
RUN pip install --no-cache-dir --user -e .

# Production stage
FROM python:3.11-slim as production

# Set labels for metadata
LABEL maintainer="Nik Jois <nikjois@llamasearch.ai>"
LABEL org.opencontainers.image.title="OpenDistillery"
LABEL org.opencontainers.image.description="Advanced Compound AI Systems for Enterprise Workflow Transformation"
LABEL org.opencontainers.image.version="${VERSION}"
LABEL org.opencontainers.image.created="${BUILD_DATE}"
LABEL org.opencontainers.image.revision="${VCS_REF}"
LABEL org.opencontainers.image.source="https://github.com/opendistillery/opendistillery"

# Set environment variables
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PYTHONPATH=/app \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1 \
    OPENDISTILLERY_ENV=production

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

# Create non-root user with specific UID/GID
RUN groupadd -r -g 1000 opendistillery && \
    useradd -r -g opendistillery -u 1000 -m -s /bin/bash opendistillery

# Create application directory
WORKDIR /app

# Copy Python packages from builder stage
COPY --from=builder /root/.local /home/opendistillery/.local

# Copy application code
COPY --chown=opendistillery:opendistillery . .

# Create necessary directories with proper permissions
RUN mkdir -p /app/logs /app/data /app/cache /app/config && \
    chown -R opendistillery:opendistillery /app

# Switch to non-root user
USER opendistillery

# Add local bin to PATH
ENV PATH=/home/opendistillery/.local/bin:$PATH

# Create health check script
RUN echo '#!/bin/bash\ncurl -f http://localhost:8000/health || exit 1' > /app/healthcheck.sh && \
    chmod +x /app/healthcheck.sh

# Expose ports
EXPOSE 8000 8001 9090

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD /app/healthcheck.sh

# Default command
CMD ["uvicorn", "opendistillery.api.server:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "4"]

# Alternative commands for different services
# Worker: CMD ["opendistillery-worker"]
# CLI: CMD ["opendistillery", "--help"] 