# MCP Service - Kubernetes optimized build
# Lightweight HTTP-based microservice optimized for K8s
# Optimizations:
# - Non-root user for security
# - Proper signal propagation for graceful shutdown
# - No HEALTHCHECK (K8s uses liveness/readiness probes)
# - Cache cleanup for smaller image size

FROM python:3.12-slim

WORKDIR /app

# Install uv
RUN pip install --no-cache-dir uv && \
    rm -rf ~/.cache/pip

# Copy pyproject.toml for dependency installation
COPY pyproject.toml .

# Install only mcp dependencies using uv
RUN uv pip install --system --group mcp && \
    rm -rf ~/.cache/uv ~/.cache/pip

# Create minimal directory structure
RUN mkdir -p src/mcp_server/features/projects src/mcp_server/features/tasks src/mcp_server/features/documents src/server/services src/server/config

# Create non-root user
RUN groupadd -r appuser -g 1001 && \
    useradd -r -g appuser -u 1001 appuser && \
    chown -R appuser:appuser /app

# Copy only MCP-specific files
COPY --chown=appuser:appuser src/mcp_server/ src/mcp_server/
COPY --chown=appuser:appuser src/__init__.py src/

# Copy the server files MCP needs for HTTP communication
COPY --chown=appuser:appuser src/server/__init__.py src/server/
COPY --chown=appuser:appuser src/server/services/__init__.py src/server/services/
COPY --chown=appuser:appuser src/server/services/mcp_service_client.py src/server/services/
COPY --chown=appuser:appuser src/server/services/client_manager.py src/server/services/
COPY --chown=appuser:appuser src/server/services/mcp_session_manager.py src/server/services/
COPY --chown=appuser:appuser src/server/config/__init__.py src/server/config/
COPY --chown=appuser:appuser src/server/config/service_discovery.py src/server/config/
COPY --chown=appuser:appuser src/server/config/logfire_config.py src/server/config/

# Set environment variables
ENV PYTHONPATH="/app:$PYTHONPATH"
ENV PYTHONUNBUFFERED=1

# Expose MCP port
ARG ARCHON_MCP_PORT=8051
ENV ARCHON_MCP_PORT=${ARCHON_MCP_PORT}
EXPOSE ${ARCHON_MCP_PORT}

# Switch to non-root user
USER appuser

# Run the MCP server
# CMD already in exec form - proper signal propagation
CMD ["python", "-m", "src.mcp_server.mcp_server"]
