# Multi-stage Dockerfile for MCP Server
# Optimized for AWS ECS Fargate deployment

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

WORKDIR /app

# Install build dependencies for Python packages
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    gcc \
    && rm -rf /var/lib/apt/lists/*

# Create virtual environment for clean copying to runtime stage
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir --upgrade pip && \
    pip install --no-cache-dir -r requirements.txt

# =============================================================================
# Stage 2: Runtime - Minimal image for production
# =============================================================================
FROM python:3.11-slim-bookworm AS runtime

WORKDIR /app

# Create non-root user for security
RUN groupadd -r mcpuser && useradd -r -g mcpuser mcpuser

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

# Copy MCP application code
COPY --chown=mcpuser:mcpuser src/ ./src/

# Set Python path so oncallhealth_mcp package is importable
ENV PYTHONPATH=/app/src

# Set Python to run unbuffered (important for Docker logging)
ENV PYTHONUNBUFFERED=1

# Switch to non-root user
USER mcpuser

# Expose MCP server port
EXPOSE 8080

# Health check for AWS ECS and Docker
# Uses Python urllib to avoid adding curl/wget to minimal image
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8080/health')" || exit 1

# Run MCP server with uvicorn
CMD ["uvicorn", "oncallhealth_mcp.transport:mcp_http_app", "--host", "0.0.0.0", "--port", "8080"]
