# ──────────────────────────────────────
# Stage 1: Build dependencies
# ──────────────────────────────────────
FROM python:3.12-alpine AS builder

RUN apk add --no-cache gcc musl-dev gcompat libstdc++

WORKDIR /build
COPY requirements.txt .
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt

# ──────────────────────────────────────
# Stage 2: Runtime (minimal)
# ──────────────────────────────────────
FROM python:3.12-alpine AS runtime

LABEL maintainer="anhvh"
LABEL description="Document Converter API - PDF→Docling, DOCX→python-docx"

# Create non-root user
RUN addgroup -S appgroup && adduser -S appuser -G appgroup

# Install runtime dependencies for PyMuPDF
RUN apk add --no-cache libstdc++ gcompat

WORKDIR /app

# Copy installed packages from builder
COPY --from=builder /install /usr/local

# Copy source code
COPY app.py .
COPY docx_converter.py .

# Switch to non-root user
USER appuser

EXPOSE 8000

HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
    CMD python -c "import urllib.request; urllib.request.urlopen('http://localhost:8000/health')" || exit 1

CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000", "--workers", "2"]
