# ==========================================
# STAGE 1: Builder Environment
# ==========================================
FROM python:3.11-slim AS builder

WORKDIR /build

RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    gcc \
    patchelf \
    && rm -rf /var/lib/apt/lists/*

ENV PIP_NO_CACHE_DIR=1
ENV PIP_DISABLE_PIP_VERSION_CHECK=1

COPY requirements.txt .

RUN pip install --user --extra-index-url https://download.pytorch.org/whl/cu121 -r requirements.txt

# Silence the "Lightning auto-upgraded checkpoint" warning on every diarization run
RUN python -c "import sys, subprocess, whisperx, pathlib; ckpt = pathlib.Path(whisperx.__file__).parent/'assets'/'pytorch_model.bin'; ckpt.exists() and subprocess.run([sys.executable, '-m', 'pytorch_lightning.utilities.upgrade_checkpoint', str(ckpt)])" 2>/dev/null || true

RUN patchelf --clear-execstack /root/.local/lib/python3.11/site-packages/ctranslate2.libs/libctranslate2-*.so*

RUN find /root/.local -type d -name "__pycache__" -exec rm -rf {} + \
    && find /root/.local -type d \( -name "test" -o -name "tests" \) -exec rm -rf {} + \
    && find /root/.local -name "*.dist-info" -exec sh -c 'rm -f "$1"/RECORD "$1"/INSTALLER' _ {} \;

# ==========================================
# STAGE 2: Lightweight Final Runtime
# ==========================================
FROM python:3.11-slim AS runtime

WORKDIR /app

# ffmpeg is mandatory for the audio-extraction step.
RUN apt-get update && apt-get install -y --no-install-recommends \
    ffmpeg \
    && rm -rf /var/lib/apt/lists/*

# Copy the (now stripped) site-packages from the builder stage. None of the
# build-essential/gcc toolchain from Stage 1 ends up here.
COPY --from=builder /root/.local /root/.local
COPY app /app/app

ENV PATH=/root/.local/bin:$PATH
ENV PYTHONUNBUFFERED=1

EXPOSE 8000

CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
