# syntax=docker/dockerfile:1

# -------- Stage 1: builder (installs deps, watermarks the catalog) --------
FROM python:3.10-slim AS builder

ENV PIP_NO_CACHE_DIR=1 \
    PIP_DISABLE_PIP_VERSION_CHECK=1 \
    PYTHONDONTWRITEBYTECODE=1

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

WORKDIR /build
COPY src/requirements.txt src/requirements.txt
RUN pip install --extra-index-url https://download.pytorch.org/whl/cpu \
        -r src/requirements.txt

# Stage the videoseal CWD shims + pre-fetch the weights (own cached layer, independent of the clips).
COPY src/configs/attenuation.yaml configs/attenuation.yaml
RUN mkdir -p videoseal/cards \
    && cp /usr/local/lib/python3.10/site-packages/videoseal/cards/*.yaml videoseal/cards/ \
    && python -c "import videoseal; videoseal.load('videoseal')"

# Watermark the catalog. ADMIN_USERNAME (build arg) MUST equal the runtime value; compose syncs them.
COPY src/ src/
ARG ADMIN_USERNAME=Marcel
COPY input/ input/
RUN ADMIN_USERNAME="$ADMIN_USERNAME" \
    python -m src.generate_catalog --seed-dir input --out-dir src/catalog

# -------- Stage 2: runtime --------
FROM python:3.10-slim AS runtime

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1 \
    CATALOG_DIR=/app/src/catalog \
    UPLOAD_TMP_DIR=/tmp

RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg \
    && rm -rf /var/lib/apt/lists/* \
    && groupadd -g 65532 sealer \
    && useradd -u 65532 -g 65532 -M -s /usr/sbin/nologin sealer

WORKDIR /app

COPY --from=builder /usr/local/lib/python3.10 /usr/local/lib/python3.10
COPY --from=builder /usr/local/bin /usr/local/bin

COPY --from=builder /build/ckpts /app/ckpts
COPY --from=builder /build/configs /app/configs
COPY --from=builder /build/videoseal /app/videoseal

COPY --from=builder /build/src /app/src

USER 65532:65532

EXPOSE 8000

ENTRYPOINT ["gunicorn", "--workers", "1", "--threads", "4", \
            "--timeout", "60", "--bind", "0.0.0.0:8000", \
            "src.app:create_app()"]
