# -------- Stage 1: Build --------
    FROM node:22-alpine AS builder

    # Declare build-args first (this is crucial!)
    ARG HTTP_PROXY
    ARG HTTPS_PROXY
    
    WORKDIR /app
    
    # Set lowercase proxy env vars (for curl, node-fetch, etc.)
    ENV http_proxy=${HTTP_PROXY}
    ENV https_proxy=${HTTPS_PROXY}
    
    # Configure npm to use the proxy globally (do this early for npm install to use proxy)
    RUN npm config set proxy ${http_proxy} && \
        npm config set https-proxy ${https_proxy}
    
    # Install system tools: git for versioning, rsync for file copying, and build tools for native dependencies
    # Added ca-certificates for SSL issues
    RUN apk add --no-cache git rsync ca-certificates \
        && apk add --no-cache --virtual .build-deps python3 make g++ pkgconfig pixman-dev cairo-dev pango-dev libjpeg-turbo-dev giflib-dev
    
    # Now configure git to use the proxy (after git is installed)
    RUN git config --global http.proxy ${http_proxy} && \
        git config --global https.proxy ${https_proxy}
    
    # Install main project dependencies
    COPY package*.json ./
    RUN npm install --legacy-peer-deps
    
    # Copy the entire project
    COPY . .
    
    # Debug: Test proxy with curl and node-fetch before build (to confirm proxy works)
    RUN echo "Testing proxy with curl..." && \
        curl -x ${http_proxy} -I https://raw.githubusercontent.com/zotero/utilities/master/resource/dateFormats.json || echo "Curl test failed!" && \
        echo "Testing proxy with node-fetch..." && \
        node -e "const fetch = require('node-fetch'); fetch('https://raw.githubusercontent.com/zotero/utilities/master/resource/dateFormats.json', { timeout: 10000 }).then(res => res.text()).then(text => console.log('Success: ' + text.slice(0,100))).catch(e => console.error('Node-fetch failed: ' + e.message))"
    
    # Run the build
    RUN npm run build
    
    # Remove temporary build tools to reduce image size
    RUN apk del .build-deps
    
    # -------- Stage 2: Runtime --------
    FROM node:22-alpine AS runtime
    
    # Declare build-args for runtime stage too
    ARG HTTP_PROXY
    ARG HTTPS_PROXY
    
    WORKDIR /app
    
    # Set lowercase proxy env vars in runtime stage (if needed for runtime fetches, though unlikely for static serve)
    ENV http_proxy=${HTTP_PROXY}
    ENV https_proxy=${HTTPS_PROXY}
    
    # Configure npm (runtime uses npm install --omit=dev)
    RUN npm config set proxy ${http_proxy} && \
        npm config set https-proxy ${https_proxy}
    
    # Install production dependencies only
    COPY package*.json ./
    RUN npm install --omit=dev --legacy-peer-deps
    
    # Copy the build output
    COPY --from=builder /app/build ./build
    
    # Run the app (using serve to serve static files)
    CMD ["npx", "serve", "-s", "build", "-l", "3000"]