# ── Backend Production Image ─────────────────────────────────────────
# Shared by both the FastAPI API server and the Celery worker.
# The entrypoint is determined by docker-compose `command`.
# ─────────────────────────────────────────────────────────────────────

FROM python:3.11-slim AS base

ENV PIP_INDEX_URL=https://pypi.tuna.tsinghua.edu.cn/simple \
    PIP_DEFAULT_TIMEOUT=120 \
    PIP_RETRIES=5 \
    PIP_DISABLE_PIP_VERSION_CHECK=1

# System dependencies for PyMuPDF, rapidocr, and general build
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
        gcc g++ libffi-dev curl && \
    rm -rf /var/lib/apt/lists/*

WORKDIR /app

# ── Dependencies layer (cached) ─────────────────────────────────────
COPY backend/requirements.txt /app/requirements.txt

# 1) Install all requirements (rapidocr pulls in opencv-python with GUI)
# 2) Force headless opencv to avoid X11 / libxcb dependencies
RUN --mount=type=cache,target=/root/.cache/pip \
    pip install --no-compile -r requirements.txt && \
    pip install --force-reinstall --no-deps opencv-python-headless

# ── Application code ────────────────────────────────────────────────
COPY backend/ /app/

# ── Runtime setup ────────────────────────────────────────────────────
# File storage directory (bind-mounted at runtime)
RUN mkdir -p /data/files

# Non-root user for security
RUN groupadd -r appuser && useradd -r -g appuser -d /app -s /sbin/nologin appuser && \
    chown -R appuser:appuser /app /data/files

USER appuser

# No CMD — docker-compose.prod.yml specifies the command:
#   backend:       uvicorn app.main:app --host 0.0.0.0 --port 8900 --workers 4
#   celery-worker: celery -A app.tasks.celery_app:celery_app worker ...
