# Stage 1: Builder
FROM python:3.11 as builder
WORKDIR /opt/venv

# Create a virtual environment and install dependencies
COPY requirements.txt .
RUN python -m venv . && . /opt/venv/bin/activate && pip install --no-cache-dir -r requirements.txt

# Stage 2: Runner (The final image)
FROM python:3.11-slim

# Install system dependencies needed at runtime
# ffmpeg is required for audio conversion
RUN apt-get update && apt-get install -y --no-install-recommends \
    ffmpeg \
    && rm -rf /var/lib/apt/lists/*

# Create an unprivileged user
RUN useradd --create-home --shell /bin/bash appuser

# Set working directory for the application code
WORKDIR /home/appuser

# Copy the virtual environment from the builder stage
COPY --from=builder /opt/venv /opt/venv

# Copy the application code into the container
COPY app/ ./app

# Set the PATH to include the virtual environment's bin directory
ENV PATH="/opt/venv/bin:$PATH"

# Expose the application port
EXPOSE 8000

# Run as the unprivileged user
USER appuser

# Command to run the application using gunicorn for production
CMD ["gunicorn", "-k", "uvicorn.workers.UvicornWorker", "-w", "2", "-b", "0.0.0.0:8000", "app.main:app"]


