# Dockerfile for py-docx-mcp (Python MCP server) - OpenWebUI: MCP (Streamable HTTP)
# Usage:
#   docker build -t py-docx-mcp .
#   docker run --rm -p 3000:3000 py-docx-mcp
#
# In OpenWebUI:
#   - Type: MCP (Streamable HTTP)
#   - URL: http://<host>:3000
#   - Auth: Bearer (if DOCX_MCP_API_KEY is set)
#
# Environment:
#   DOCX_MCP_API_KEY            - API key (Bearer). Optional but recommended.
#   DOCX_MCP_HTTP_HOST          - Bind host (default: 0.0.0.0)
#   DOCX_MCP_HTTP_PORT          - Bind port (default: 3000)
#   DOCX_MCP_TEMPLATES_DIR      - Templates directory (default: /templates)
#   DOCX_MCP_MAX_SIZE           - Max document size in bytes (default: 104857600)
#   DOCX_MCP_MAX_DOCS           - Max open documents (default: 30)
#   DOCX_MCP_SANDBOX            - Enable sandbox mode (default: true)
#   DOCX_MCP_ALLOW_EXTERNAL_TOOLS - Allow external tools (default: false)
#   DOCX_MCP_ALLOW_NETWORK      - Allow network access (default: false)

FROM python:3.12-slim AS base

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=off \
    PIP_DISABLE_PIP_VERSION_CHECK=1

WORKDIR /app

# System deps (for python-docx, Pillow, and optional external converters)
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    libjpeg62-turbo-dev \
    libpng-dev \
    libfreetype6-dev \
    libfontconfig1-dev \
    libreoffice \
    poppler-utils \
    && rm -rf /var/lib/apt/lists/*

# Copy project metadata and source before installing
COPY pyproject.toml ./
COPY src ./src

# Install Python dependencies (including this package)
RUN pip install --upgrade pip && pip install .

# Ensure modules in src are importable at runtime
ENV PYTHONPATH="/app/src"

# Create runtime dirs
RUN mkdir -p /templates /out /tmp/py-docx-mcp

# Environment
ENV DOCX_MCP_HTTP_HOST=0.0.0.0 \
    DOCX_MCP_HTTP_PORT=3000 \
    DOCX_MCP_TEMPLATES_DIR=/templates \
    DOCX_MCP_MAX_SIZE=104857600 \
    DOCX_MCP_MAX_DOCS=30 \
    DOCX_MCP_SANDBOX=true \
    DOCX_MCP_ALLOW_EXTERNAL_TOOLS=true \
    DOCX_MCP_ALLOW_NETWORK=false

# Expose HTTP port (Streamable HTTP for OpenWebUI)
EXPOSE 3000

# Health check (ensure server module is importable)
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
    CMD python -c "from server import make_app; print('ok')" || exit 1

# Default: Streamable HTTP for OpenWebUI MCP
ENTRYPOINT ["python", "-m", "server"]
