# =============================================================================
# Sentence Transformers Search Starter – Dockerfile
# =============================================================================
# Multi-stage build: keeps the final image lean by separating dependency
# installation from the runtime layer.
#
# Build:  docker build -t demia/sentence-search .
# Run:    docker run -p 8000:8000 demia/sentence-search
# =============================================================================

# ---------------------------------------------------------------------------
# Stage 1 – dependency builder
# ---------------------------------------------------------------------------
FROM python:3.11-slim AS builder

WORKDIR /build

# Install build tools needed by some wheels (e.g. tokenizers Rust extension)
RUN apt-get update && apt-get install -y --no-install-recommends \
        build-essential \
        curl \
    && rm -rf /var/lib/apt/lists/*

COPY requirements.txt .

# Download and build wheels into a local directory so the final stage can
# install from the wheel cache without network access.
RUN pip install --upgrade pip && \
    pip wheel --no-cache-dir --wheel-dir /wheels -r requirements.txt

# ---------------------------------------------------------------------------
# Stage 2 – runtime image
# ---------------------------------------------------------------------------
FROM python:3.11-slim AS runtime

LABEL maintainer="DemIA Living Lab - Universidad de Salamanca (USAL) / BISITE"
LABEL description="Semantic-search service using sentence-transformers"

# Non-root user for security
RUN useradd --create-home --shell /bin/bash appuser

WORKDIR /app

# Install wheels built in stage 1 (no pip network call at runtime)
COPY --from=builder /wheels /wheels
COPY requirements.txt .
RUN pip install --no-cache-dir --no-index --find-links=/wheels -r requirements.txt \
    && rm -rf /wheels

# Copy application source
COPY config/     config/
COPY src/        src/
COPY api/        api/
COPY app/        app/
COPY scripts/    scripts/
COPY examples/   examples/
COPY .env.example .env.example

# HF model cache lives inside the container (can be mounted as a volume to
# persist downloads across restarts).
ENV HF_HOME=/app/hf_cache
RUN mkdir -p /app/hf_cache && chown -R appuser:appuser /app

USER appuser

# Expose FastAPI port
EXPOSE 8000

# Default command starts the FastAPI service.
# Override with: docker run ... python app/app.py   (Gradio UI)
#                docker run ... python scripts/run.py --query "..."  (CLI)
CMD ["uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "8000"]
