# Universal Dockerfile for Goaly MCP Server using pre-built wheel
# Configuration is handled via environment variables at runtime

FROM python:3.12-slim as runtime

# Set runtime arguments
ARG DEBIAN_FRONTEND=noninteractive

# Install runtime dependencies including tini (combine for better caching)
RUN apt-get update && apt-get install -y \
    libpq5 \
    curl \
    tini \
    && rm -rf /var/lib/apt/lists/* \
    && apt-get clean \
    && pip install uv

# Create non-root user and directories (combine for better caching)
RUN groupadd -r goaly && useradd -r -g goaly -d /app -s /bin/bash goaly \
    && mkdir -p /app/data /app/logs

# Set working directory
WORKDIR /app

# Create virtual environment (separate layer for caching)
RUN uv venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Copy pre-built wheel and install (combine for atomic operation)
COPY dist/*.whl /tmp/
RUN uv pip install /tmp/*.whl \
    && rm -f /tmp/*.whl

# Copy entrypoint script and set permissions
COPY docker/production/docker-entrypoint.sh ./
RUN chmod +x docker-entrypoint.sh

# Set ownership of all app files to goaly user
RUN chown -R goaly:goaly /app

# Switch to non-root user
USER goaly

# Default environment variables (can be overridden at runtime)
ENV GOALY_HOST=0.0.0.0
ENV GOALY_PORT=8000
ENV PYTHONPATH=/app
ENV PYTHONUNBUFFERED=1

# Note: DATABASE_URL and GOALY_DEBUG should be set via docker-compose or runtime environment

# Enhanced health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD curl -f http://localhost:8000/health && \
        python -c "import psutil; exit(0 if psutil.cpu_percent(interval=1) < 95 else 1)" || exit 1

# Expose port 8000
EXPOSE 8000

# Use tini as entrypoint for proper signal handling
ENTRYPOINT ["/usr/bin/tini", "--", "./docker-entrypoint.sh"]
