# Stage 1: Build stage
FROM python:3.12-slim as builder

WORKDIR /app

# Install system dependencies
RUN apt-get update && apt-get install -y \
    build-essential \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Install Python dependencies into the system site-packages (not --user) so
# that PYTHONNOUSERSITE=1 in the runtime stage doesn't hide them.
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Stage 2: Final runtime stage
FROM python:3.12-slim

# OCI Labels for GitHub Container Registry
LABEL org.opencontainers.image.source="https://github.com/GYFSOO/blob-backend"
LABEL org.opencontainers.image.description="Blob Voice AI Backend"
LABEL org.opencontainers.image.licenses="UNLICENSED"

WORKDIR /app

# Install runtime dependencies (e.g. for faster-whisper/VAD)
RUN apt-get update && apt-get install -y \
    libgomp1 \
    && rm -rf /var/lib/apt/lists/*

# Copy only the installed packages from the builder's system site-packages.
# Avoids copying build tools (gcc, etc.) or /root/.local user-site packages.
COPY --from=builder /usr/local/lib/python3.12/site-packages /usr/local/lib/python3.12/site-packages

# Copy application code
COPY . .

# Expose port
EXPOSE 8000

# Set environment variables
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONPATH=/app
# Prevent Python from loading packages from user site-packages (~/.local),
# eliminating split-site-packages state when additional packages are installed
# manually on a running container (e.g. grpcio-status, protobuf).
ENV PYTHONNOUSERSITE=1

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

# Command to run the application
CMD ["python", "app/main.py"]
