# Use Node.js 20 Alpine as base image
FROM node:20-alpine

# Install system dependencies including FFmpeg with full codec support and build tools
RUN apk add --no-cache \
    ffmpeg \
    ffmpeg-dev \
    x264 \
    x265 \
    libvpx \
    libvorbis \
    lame \
    opus \
    python3 \
    make \
    g++ \
    git \
    pkgconfig \
    cairo-dev \
    jpeg-dev \
    pango-dev \
    musl-dev \
    && rm -rf /var/cache/apk/*

# Set working directory
WORKDIR /app

# Copy package files
COPY package*.json ./

# Clear npm cache and install dependencies with native module rebuild
RUN npm cache clean --force && \
    npm install  && \
    npm rebuild --build-from-source

# Copy source code
COPY . .

# Copy and set up entrypoint script
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

# Create necessary directories
RUN mkdir -p uploads temp/video-processing

# Create non-root user
RUN addgroup -g 1001 -S nodejs
RUN adduser -S nodejs -u 1001

# Change ownership of the app directory
RUN chown -R nodejs:nodejs /app

# Verify FFmpeg installation and available codecs
RUN ffmpeg -codecs | grep -i h264 || echo "H.264 codec not found, but continuing..."
RUN ffmpeg -version

# Switch to non-root user
USER nodejs

# Expose port
EXPOSE 3040
# Set entrypoint
ENTRYPOINT ["/usr/local/bin/docker-entrypoint.sh"]

# Start the application
CMD ["npm", "run", "start"] 