# ─────────────────────────────────────────────────────────────────────────────
# Dockerfile — LangChain PDF Chat Starter (FastAPI service)
#
# Multi-stage build:
#   Stage 1 (builder) — install Python dependencies into a venv
#   Stage 2 (runtime) — copy the venv and application code into a slim image
#
# Build:
#   docker build -t langchain-pdf-chat .
#
# Run:
#   docker run -p 8000:8000 --env-file .env langchain-pdf-chat
#
# DemIA Living Lab — Template #52: LangChain PDF Chat Starter
# ─────────────────────────────────────────────────────────────────────────────

# ── Stage 1: Builder ──────────────────────────────────────────────────────────
FROM python:3.11-slim AS builder

WORKDIR /build

# Install build tools
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    gcc \
    && rm -rf /var/lib/apt/lists/*

# Create virtual environment
RUN python -m venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Install Python dependencies
COPY requirements.txt .
RUN pip install --upgrade pip && \
    pip install --no-cache-dir -r requirements.txt


# ── Stage 2: Runtime ──────────────────────────────────────────────────────────
FROM python:3.11-slim AS runtime

LABEL maintainer="DemIA Living Lab <bisite@usal.es>"
LABEL description="LangChain PDF Chat Starter — Template #52"
LABEL version="0.1.0"

WORKDIR /app

# Copy virtual environment from builder
COPY --from=builder /opt/venv /opt/venv
ENV PATH="/opt/venv/bin:$PATH"

# Create non-root user for security
RUN useradd --create-home --shell /bin/bash appuser && \
    mkdir -p /app/chroma_db /app/uploads && \
    chown -R appuser:appuser /app

# Copy application source
COPY --chown=appuser:appuser config/ ./config/
COPY --chown=appuser:appuser src/ ./src/
COPY --chown=appuser:appuser api/ ./api/

# Switch to non-root user
USER appuser

# Expose API port
EXPOSE 8000

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"

# Default: run the FastAPI server
CMD ["uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "1"]
