# Stage 1: Builder (for heavy Python dependencies including CUDA-enabled PyTorch)
FROM nvidia/cuda:12.1.0-devel-ubuntu22.04 as builder
WORKDIR /opt/venv

# Install Python 3.11 and venv in the builder stage
RUN apt-get update && apt-get install -y python3.11 python3.11-venv

# Create a virtual environment and install Python dependencies
COPY requirements.txt .
COPY patches/ ./patches/
RUN python3.11 -m venv . && . /opt/venv/bin/activate && pip install --no-cache-dir -r requirements.txt && \
    chmod +x ./patches/fix-misaki-espeak.sh && ./patches/fix-misaki-espeak.sh

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

# Install system dependencies needed at runtime
# ffmpeg is required for audio conversion
# espeak-ng is required for Kokoro TTS phonemization
RUN apt-get update && apt-get install -y --no-install-recommends \
    ffmpeg \
    espeak-ng \
    && 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 entire virtual environment from the builder stage
COPY --from=builder /opt/venv /opt/venv

# Add venv to PATH and PYTHONPATH so packages and scripts work correctly
ENV PATH="/opt/venv/bin:$PATH"
ENV PYTHONPATH="/opt/venv/lib/python3.11/site-packages:$PYTHONPATH"

# Create espeak-ng-data symlink for misaki compatibility
RUN mkdir -p /home/runner/work/espeakng-loader/espeakng-loader/espeak-ng/_dynamic/share/ && \
    ln -sf /usr/lib/x86_64-linux-gnu/espeak-ng-data /home/runner/work/espeakng-loader/espeakng-loader/espeak-ng/_dynamic/share/espeak-ng-data

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

# Expose the application port
EXPOSE 8000

# Run as the unprivileged user
USER appuser

# Command to run the application using uvicorn for development with auto-reloading
CMD ["python3.11", "-m", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--log-level", "debug"]



