# paper-doc backend image — the REST API and the MCP server, one build.
#
# Both entry points live in the same package and share the same domain layer, so
# they share an image: the Deployment picks which one to run with its own
# command. Building two images would mean two dependency resolutions that can
# drift apart, for a difference of one argv.
#
# The base image comes from a mirror rather than docker.io, which this network
# cannot reach; the pip index is the Tsinghua mirror for the same reason.
FROM docker.m.daocloud.io/library/python:3.12-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1 \
    PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple

WORKDIR /app

# The unprivileged uid is created before the code is copied, so the copies can
# be owned by it in one pass.
RUN useradd --no-create-home --shell /usr/sbin/nologin --uid 10001 appuser

# Requirements first, and alone: the dependency layer is the slow one and the
# application code changes far more often than it does.
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY --chown=10001:10001 app ./app
COPY --chown=10001:10001 scripts ./scripts
# Not used by the MCP server, but the API Deployment runs `alembic upgrade head`
# as an init container against the same image, and shipping the migrations
# beside the models they describe is the only way to keep them in step.
COPY --chown=10001:10001 alembic ./alembic
COPY --chown=10001:10001 alembic.ini ./

# COPY carries the source file's mode across, and this working tree keeps its
# files at 0600 — so without this the container starts, reads nothing, and exits
# with "can't open file ... Permission denied". Read and traverse for everyone,
# which is all any of it needs: the image writes nothing.
RUN chmod -R a+rX /app

USER 10001

EXPOSE 8931

# Defaults for the container, not the deployment: a Deployment that means to
# run stdio overrides these, and one that forgets to set MCP_HTTP_TOKEN gets a
# server that is only reachable from inside the cluster.
ENV MCP_TRANSPORT=http \
    MCP_HOST=0.0.0.0 \
    MCP_PORT=8931 \
    MCP_PATH=/mcp

# No HEALTHCHECK: the Deployment probes /healthz and /readyz directly, and a
# Docker healthcheck would be a second, differently-tuned copy of that.
CMD ["python", "scripts/mcp_server.py"]
