# ---- Build stage ----
FROM python:3.13.5-slim AS builder

WORKDIR /app

# Install system dependencies required for FAISS, PyMuPDF, etc.
RUN apt-get update && apt-get install -y --no-install-recommends \
    gcc \
    g++ \
    libgomp1 \
    libopenblas-dev \
    && rm -rf /var/lib/apt/lists/*

# Copy only requirements first for better caching
COPY requirements.txt .

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

# ---- Final stage ----
FROM python:3.13.5-slim

WORKDIR /app

# Install runtime system dependencies (FAISS, fonts for PDF, etc.)
RUN apt-get update && apt-get install -y --no-install-recommends \
    libgomp1 \
    libopenblas0 \
    && rm -rf /var/lib/apt/lists/*

# Copy installed Python packages from builder
COPY --from=builder /usr/local/lib/python3.13/site-packages /usr/local/lib/python3.13/site-packages
COPY --from=builder /usr/local/bin /usr/local/bin

# Copy application code
COPY . .

# Create directories for FAISS index and SQLite database (if not exist)
RUN mkdir -p /app/faiss_index /app/diet /app/workout

# Expose port
EXPOSE 8000

# Health check (optional)
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8000/health || exit 1

# Run with Gunicorn + Uvicorn workers (adjust -w to number of CPU cores)
CMD ["gunicorn", "-w", "4", "-k", "uvicorn.workers.UvicornWorker", "run:app", "--bind", "0.0.0.0:8000", "--timeout", "120"]