# syntax=docker/dockerfile:1.4
ARG NODE_VERSION=20

# Base development image
FROM node:${NODE_VERSION}-slim AS base

# Install Python and basic build dependencies
RUN apt-get update && apt-get install -y \
    python3 \
    python3-pip \
    git \
    curl \
    build-essential \
    procps \
    && rm -rf /var/lib/apt/lists/*

# Create cache directories
RUN mkdir -p /root/.npm
RUN mkdir -p /root/.pip

# Set working directory
WORKDIR /app

# Development stage
FROM base AS dev

# Install development tools
RUN apt-get update && apt-get install -y \
    vim \
    ssh \
    && rm -rf /var/lib/apt/lists/*

# Create a non-root user for development
ARG USERNAME=node
ARG USER_UID=1000
ARG USER_GID=$USER_UID

# Create the user (skip if already exists)
RUN (groupadd --gid $USER_GID $USERNAME || true) \
    && (useradd --uid $USER_UID --gid $USER_GID -m $USERNAME || true) \
    && apt-get update \
    && apt-get install -y sudo \
    && echo $USERNAME ALL=\(root\) NOPASSWD:ALL > /etc/sudoers.d/$USERNAME \
    && chmod 0440 /etc/sudoers.d/$USERNAME

# Set npm config
RUN npm config set cache /root/.npm \
    && npm config set prefer-offline true \
    && npm config set package-lock true

# Copy package files
COPY package*.json ./
COPY .npmrc ./
COPY requirements.txt ./

# Install Node.js dependencies with cache
RUN --mount=type=cache,target=/root/.npm \
    npm ci

# Install Python dependencies with cache (skip if no real dependencies)
RUN --mount=type=cache,target=/root/.cache/pip \
    pip3 install --break-system-packages -r requirements.txt || echo "No Python dependencies to install"

# Switch to non-root user
USER $USERNAME

# Set the default command for development
CMD ["npm", "run", "dev"]

# Production stage
FROM base AS prod

# Copy package files
COPY package*.json ./
COPY .npmrc ./
COPY requirements.txt ./

# Install production dependencies
RUN --mount=type=cache,target=/root/.npm \
    npm ci --only=production

# Install Python production dependencies (skip if no real dependencies)
RUN --mount=type=cache,target=/root/.cache/pip \
    pip3 install --break-system-packages -r requirements.txt || echo "No Python dependencies to install"

# Copy application code
COPY . .

# Build the application
RUN npm run build

# Production command
CMD ["npm", "start"]