# ==========================================
# STAGE 1 — builder: compile Python deps
# ==========================================
# Changes only when requirements.txt is modified.
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 — whisperx-base: deps only, no app
# ==========================================
# Targeted by docker-compose for dev caching.
# If you only need this layer: docker build --target=whisperx-base -t nat20-whisperx-base .
FROM python:3.11-slim AS whisperx-base

RUN apt-get update && apt-get install -y --no-install-recommends \
    ffmpeg \
    && rm -rf /var/lib/apt/lists/*

COPY --from=builder /root/.local /root/.local

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

# ==========================================
# STAGE 3 — runtime: full release image
# ==========================================
# Build for production: docker build --target=runtime -t nat20-notes-backend .
# Layers app code on top of whisperx-base in a single Dockerfile pass.
FROM whisperx-base AS runtime

WORKDIR /app

COPY app /app/app

EXPOSE 8000

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