# Multi-stage build. Compatible with the legacy docker builder (no BuildKit
# cache mounts). The base image and proxy are parameterized via build args so
# the build works behind a corporate mirror/proxy.

ARG PYTHON_IMAGE=hub.yangzhiqiang.tech/library/python:3.12-slim

# ---- builder: resolve deps and build a venv with uv ----
FROM ${PYTHON_IMAGE} AS builder

# Docker's predefined proxy build args (http_proxy/https_proxy) are injected
# into RUN automatically when passed via --build-arg; declaring them keeps the
# linter quiet and makes the intent explicit.
ARG http_proxy
ARG https_proxy

# Disabled: bulk .pyc compilation opens many files and hits EMFILE on low ulimit hosts.
ENV UV_COMPILE_BYTECODE=0 \
    UV_LINK_MODE=copy \
    UV_PROJECT_ENVIRONMENT=/app/.venv \
    PIP_DISABLE_PIP_VERSION_CHECK=1

WORKDIR /app

# uv: fast, reproducible dependency management.
RUN pip install --no-cache-dir uv

# Install dependencies from the committed lockfile first so this layer stays
# cached when only application source changes.
COPY pyproject.toml uv.lock ./
RUN uv sync --frozen --no-dev --no-install-project

# Install the project itself (needs README for package metadata + ragext/).
COPY README.md ./
COPY ragext ./ragext
RUN uv pip install --python /app/.venv/bin/python --no-deps .

# ---- runtime: slim image with only the venv and source ----
FROM ${PYTHON_IMAGE} AS runtime

ENV PATH="/app/.venv/bin:$PATH" \
    PYTHONPATH=/app \
    PYTHONUNBUFFERED=1 \
    PYTHONDONTWRITEBYTECODE=1 \
    RAGEXT_HOST=0.0.0.0 \
    RAGEXT_PORT=8080 \
    RAGEXT_WORKERS=auto \
    RAGEXT_LOGS_DIR=/app/logs

WORKDIR /app

RUN useradd --create-home --uid 10001 appuser \
    && mkdir -p /app/logs \
    && chown -R appuser:appuser /app/logs

COPY --from=builder /app/.venv /app/.venv
COPY ragext ./ragext

USER appuser

EXPOSE 8080

HEALTHCHECK --interval=30s --timeout=3s --start-period=20s --retries=3 \
    CMD python -c "import urllib.request,os,sys; sys.exit(0) if urllib.request.urlopen(f\"http://127.0.0.1:{os.environ.get('RAGEXT_PORT','8080')}/healthz\").status==200 else sys.exit(1)"

CMD ["ragext"]
