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

ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

# Install system dependencies for building Python packages
# Example:
RUN apt-get update && \
    apt-get install -y --no-install-recommends \
    gcc \
    libpq-dev \
    && rm -rf /var/lib/apt/lists/*

# Set the working directory
WORKDIR /app

# Copy requirements to install dependencies
COPY requirements.txt .

# Install dependencies in a temporary directory /install to avoid polluting the final image
RUN pip install --upgrade pip && \
    pip install --no-cache-dir --prefix=/install -r requirements.txt

# Stage 2: Production stage
FROM python:3.11-slim

# Set environment variables again in the final stage
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1

# Set working directory in the final container
WORKDIR /app

# Copy only the installed Python dependencies from the builder stage
COPY --from=builder /install /usr/local

# Copy the application code from the host to the final image
COPY . .

# Expose port
EXPOSE PORT

CMD ["python", "APP_ENTRY"]