# MediaFetch backend — production image
#
# Base: Debian slim (not Alpine) because ffmpeg's Alpine build is
# missing several codecs commonly needed for muxing/audio extraction
# across different source platforms; Debian's apt build is the safer
# default here.
FROM node:20-bookworm-slim

# --- System dependencies -------------------------------------------------
# ffmpeg      - required by yt-dlp for muxing video+audio and for MP3 extraction
# python3/pip - yt-dlp itself is a Python package; installing it via pip
#               (rather than relying on yt-dlp-exec's own GitHub-release
#               download) avoids GitHub API rate limits and matches
#               yt-dlp's own recommended install/update method.
# ca-certificates - needed for HTTPS requests made by yt-dlp/ffmpeg
RUN apt-get update && apt-get install -y --no-install-recommends \
    ffmpeg \
    python3 \
    python3-pip \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

# Install yt-dlp via pip, independent of the Node dependency tree, so
# it can be upgraded on its own schedule (see services/updater.service.js
# and the note below).
RUN pip3 install --break-system-packages --no-cache-dir -U yt-dlp

WORKDIR /app

# --- Node dependencies ----------------------------------------------------
# YOUTUBE_DL_SKIP_DOWNLOAD=true tells yt-dlp-exec's postinstall script to
# skip downloading its own bundled binary — we symlink the pip-installed
# one into the exact path it expects instead, further down.
ENV YOUTUBE_DL_SKIP_DOWNLOAD=true
ENV NODE_ENV=production

COPY package.json package-lock.json* ./
RUN npm ci --omit=dev

# Symlink the real, pip-managed yt-dlp binary into the path yt-dlp-exec
# looks for. This means our application code (services/ytdlp.service.js)
# needs zero changes to work with either install method.
RUN mkdir -p node_modules/yt-dlp-exec/bin \
    && ln -sf "$(command -v yt-dlp)" node_modules/yt-dlp-exec/bin/yt-dlp

# --- Application source -----------------------------------------------------
COPY . .

# Non-root user for defense in depth.
RUN useradd --create-home --uid 1001 mediafetch \
    && mkdir -p /app/tmp \
    && chown -R mediafetch:mediafetch /app
USER mediafetch

EXPOSE 5000

HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 \
    CMD node -e "fetch('http://localhost:'+(process.env.PORT||5000)+'/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"

CMD ["node", "server.js"]
