# BUILD STAGE (System Deps)
FROM node:20-bookworm-slim AS build

RUN apt-get update && \
    apt-get install -y python3 ffmpeg curl unzip && \
    curl -fsSL https://deno.land/x/install/install.sh | sh && \
    rm -rf /var/lib/apt/lists/*

ENV DENO_INSTALL="/root/.deno"
ENV PATH="$DENO_INSTALL/bin:$PATH"

RUN curl -L https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp -o /usr/local/bin/yt-dlp && \
    chmod a+rx /usr/local/bin/yt-dlp

WORKDIR /app

# R335: Cache npm dependencies
COPY package*.json ./
RUN npm install

# RUN STAGE
FROM node:20-bookworm-slim

# Copy system binaries from build stage
COPY --from=build /usr/bin/python3 /usr/bin/python3
COPY --from=build /usr/bin/ffmpeg /usr/bin/ffmpeg
COPY --from=build /usr/local/bin/yt-dlp /usr/local/bin/yt-dlp
# FFmpeg usually needs shared libs, so we actually need to install it in the final stage too
# But caching npm modules is the primary win.

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

WORKDIR /app

# Copy cached modules
COPY --from=build /app/node_modules ./node_modules
COPY . .

CMD ["npm", "start"]
