# Build stage
FROM python:3.13.2-slim AS builder

WORKDIR /app

# Install Poetry
RUN pip install --no-cache-dir poetry

# Copy Poetry configuration files and README
COPY pyproject.toml poetry.lock* README.md ./

# Copy application code
COPY server.py server.json config.py github.py cache.py auth.py ./
COPY images/cloud-bicep-mcp-96.png ./images/

# Configure Poetry to not create virtualenv and install dependencies
RUN poetry config virtualenvs.create false \
  && poetry install --no-interaction --without dev \
  && poetry check \
  && rm -rf ~/.cache/pypoetry \
  && rm -rf ~/.cache/pip

# Runtime stage
FROM python:3.13.2-slim

WORKDIR /app

# Copy application code from builder
COPY --from=builder /app /app

# Copy installed dependencies from builder
COPY --from=builder /usr/local/lib /usr/local/lib
COPY --from=builder /usr/local/bin /usr/local/bin

# Clean up pip cache in runtime stage
RUN pip cache purge \
  && rm -rf /tmp/* /var/tmp/* ~/.cache/pip

# Set environment variables with defaults that can be overridden
# the transport can be set to "stdio", "sse" or "http". Defaults to "stdio".
# "stdio" uses standard input/output for communication.
# "sse" is the server-sent events mode and uses HTTP (Server-Sent Events) for communication.
# "http" enables the Streamable HTTP transport as defined by the MCP specification.
ENV MCP_TRANSPORT=stdio
# The port is used by the "sse" and "http" transport modes and defaults to 8080.
ENV MCP_PORT=8080
# The host address to bind to. Defaults to 0.0.0.0 for containerized deployments.
# WARNING: When using 0.0.0.0, MCP_API_KEY must be set for security.
ENV MCP_HOST=0.0.0.0

# Create entrypoint script
RUN echo '#!/bin/bash\n\
  TRANSPORT_ARG=""\n\
  PORT_ARG=""\n\
  HOST_ARG=""\n\
  \n\
  # Only add transport parameter if MCP_TRANSPORT is set\n\
  if [ -n "$MCP_TRANSPORT" ]; then\n\
  TRANSPORT_ARG="--transport $MCP_TRANSPORT"\n\
  fi\n\
  \n\
  # Only add port parameter if MCP_PORT is set\n\
  if [ -n "$MCP_PORT" ]; then\n\
  PORT_ARG="--port $MCP_PORT"\n\
  fi\n\
  \n\
  # Only add host parameter if MCP_HOST is set\n\
  if [ -n "$MCP_HOST" ]; then\n\
  HOST_ARG="--host $MCP_HOST"\n\
  fi\n\
  \n\
  python server.py $TRANSPORT_ARG $PORT_ARG $HOST_ARG\n\
  ' > /app/docker-entrypoint.sh \
  && chmod +x /app/docker-entrypoint.sh

EXPOSE 8080

# Set the entry point for the container
ENTRYPOINT ["/app/docker-entrypoint.sh"]
