# syntax=docker/dockerfile:1
# Multi-stage build for the extractors service. Non-root runtime, ffmpeg/ffprobe
# available for video metadata and audio decoding.

FROM python:3.11-slim AS builder

WORKDIR /build
COPY pyproject.toml ./
COPY src ./src
RUN pip install --no-cache-dir --upgrade pip build \
    && pip wheel --no-cache-dir --wheel-dir /wheels ".[ml]"

FROM python:3.11-slim AS runtime

# ffmpeg provides ffmpeg/ffprobe; libgl1/libglib/libxcb are the OpenCV runtime
# libs needed by ultralytics (YOLO).
RUN apt-get update \
    && apt-get install -y --no-install-recommends \
        ffmpeg \
        libgl1 \
        libglib2.0-0 \
        libxcb1 \
    && rm -rf /var/lib/apt/lists/*

RUN useradd --create-home --uid 10001 appuser
WORKDIR /app

COPY --from=builder /wheels /wheels
RUN pip install --no-cache-dir /wheels/*.whl && rm -rf /wheels

USER appuser

ENV EXTRACTORS_HOST=0.0.0.0 \
    EXTRACTORS_PORT=54400

EXPOSE 54400

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD python -c "import urllib.request,os,sys; \
url=f'http://127.0.0.1:{os.getenv(\"EXTRACTORS_PORT\",\"54400\")}/health'; \
sys.exit(0 if urllib.request.urlopen(url, timeout=3).status==200 else 1)"

CMD ["sh", "-c", "uvicorn extractors.app:app --host $EXTRACTORS_HOST --port $EXTRACTORS_PORT"]
