# Use base image built from Dockerfile.base
# Build base image first: docker build -f Dockerfile.base -t ragflow-base:latest .
ARG BASE_IMAGE=ragflow-base:latest
FROM ${BASE_IMAGE} AS base

ARG NEED_MIRROR=0
ARG LIGHTEN=0
ENV LIGHTEN=${LIGHTEN}

# builder stage
FROM base AS builder
USER root

WORKDIR /ragflow

# Ensure Node.js/npm available even if base image lacks it
RUN --mount=type=cache,id=ragflow_apt,target=/var/cache/apt,sharing=locked \
    if ! command -v npm >/dev/null 2>&1; then \
        apt-get update && \
        curl -fsSL https://deb.nodesource.com/setup_20.x | bash - && \
        apt-get install -y --no-install-recommends nodejs && \
        rm -rf /var/lib/apt/lists/*; \
    fi

# Set UV HTTP timeout to handle large package downloads (e.g., nvidia-cusolver-cu12)
# Default is 30s, increase to 600s (10 minutes) for large packages
ENV UV_HTTP_TIMEOUT=600

# install dependencies from pyproject.toml
COPY pyproject.toml ./
# https://github.com/astral-sh/uv/issues/10462
# uv records index url into uv.lock but doesn't failover among multiple indexes
# Generate uv.lock from pyproject.toml and install dependencies with cache
RUN --mount=type=cache,id=ragflow_uv,target=/root/.cache/uv,sharing=locked \
    if [ "$NEED_MIRROR" == "1" ]; then \
        uv lock --index-url https://mirrors.aliyun.com/pypi/simple; \
        sed -i 's|pypi.org|mirrors.aliyun.com/pypi|g' uv.lock; \
    else \
        uv lock; \
        sed -i 's|mirrors.aliyun.com/pypi|pypi.org|g' uv.lock; \
    fi; \
    if [ "$LIGHTEN" == "1" ]; then \
        uv sync --python 3.10 --frozen; \
    else \
        uv sync --python 3.10 --frozen --all-extras; \
    fi

COPY web web
COPY docs docs
RUN --mount=type=cache,id=ragflow_npm,target=/root/.npm,sharing=locked \
    cd web && npm install && npm run build

COPY .git /ragflow/.git

RUN version_info=$(git describe --tags --match=v* --first-parent --always); \
    if [ "$LIGHTEN" == "1" ]; then \
        version_info="$version_info slim"; \
    else \
        version_info="$version_info full"; \
    fi; \
    echo "RAGFlow version: $version_info"; \
    echo $version_info > /ragflow/VERSION

# production stage
FROM base AS production
USER root

WORKDIR /ragflow

# Copy Python environment and packages
ENV VIRTUAL_ENV=/ragflow/.venv
COPY --from=builder ${VIRTUAL_ENV} ${VIRTUAL_ENV}
ENV PATH="${VIRTUAL_ENV}/bin:${PATH}"

ENV PYTHONPATH=/ragflow/

COPY web web
COPY admin admin
COPY api api
COPY conf conf
COPY deepdoc deepdoc
COPY rag rag
COPY agent agent
COPY graphrag graphrag
COPY agentic_reasoning agentic_reasoning
COPY pyproject.toml ./
COPY mcp mcp
COPY plugin plugin

COPY docker/service_conf.yaml.template ./conf/service_conf.yaml.template
COPY --chmod=+x docker/entrypoint.sh ./entrypoint.sh


# Copy compiled web pages
COPY --from=builder /ragflow/web/dist /ragflow/web/dist

COPY --from=builder /ragflow/VERSION /ragflow/VERSION
ENTRYPOINT ["./entrypoint.sh"]
