# 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

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 + gateway/).
COPY README.md ./
COPY gateway ./gateway
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 \
    KB_GATEWAY_CONFIG=/app/config.yaml \
    KB_GATEWAY_HOST=0.0.0.0 \
    KB_GATEWAY_PORT=8080 \
    KB_GATEWAY_WORKERS=auto

WORKDIR /app

RUN useradd --create-home --uid 10001 appuser

COPY --from=builder /app/.venv /app/.venv
COPY gateway ./gateway
COPY config.yaml ./config.yaml

RUN mkdir -p /app/logs && chown -R appuser:appuser /app/logs

USER appuser

EXPOSE 8080

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --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('KB_GATEWAY_PORT','8080')}/healthz\").status==200 else sys.exit(1)"

CMD ["kb-gateway"]
