# Enhanced ZKP Engine Dockerfile with Circom Support
FROM node:18-bullseye as builder

# Install system dependencies for snarkjs and circom
RUN apt-get update && apt-get install -y \
    build-essential \
    cmake \
    git \
    libgmp-dev \
    libsodium-dev \
    nasm \
    nlohmann-json3-dev \
    python3 \
    python3-pip \
    curl \
    netcat \
    && rm -rf /var/lib/apt/lists/*

# Install Rust for circom
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
ENV PATH="/root/.cargo/bin:${PATH}"

# Install Circom
WORKDIR /tmp
RUN git clone https://github.com/iden3/circom.git \
    && cd circom \
    && cargo build --release \
    && cp target/release/circom /usr/local/bin/ \
    && cd .. \
    && rm -rf circom

# Production stage
FROM node:18-bullseye-slim

# Install runtime dependencies
RUN apt-get update && apt-get install -y \
    libgmp10 \
    libsodium23 \
    curl \
    netcat \
    postgresql-client \
    && rm -rf /var/lib/apt/lists/*

# Copy circom from builder
COPY --from=builder /usr/local/bin/circom /usr/local/bin/circom

# Install global Node tools
RUN npm install -g snarkjs@latest nodemon

WORKDIR /app

# Copy package files first for better caching
COPY package*.json ./
RUN npm ci --only=production

# Copy application code
COPY . .

# Create necessary directories
RUN mkdir -p circuits/build keys ptau logs cache

# Setup script for circuit compilation
COPY scripts/setup-circuits.sh /usr/local/bin/setup-circuits
RUN chmod +x /usr/local/bin/setup-circuits

# Entry script
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=40s --retries=3 \
    CMD curl -f http://localhost:8080/health || exit 1

# Expose ports
EXPOSE 8080 8081

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["node", "src/index.js"]