FROM node:22-alpine

WORKDIR /app

RUN apk add --no-cache su-exec

# Copy package files first for better layer caching
COPY package*.json ./
RUN npm ci --omit=dev

# Copy source
COPY . .
RUN mkdir -p /app/runs /app/runs/memory /app/runs/memory/cold && chown -R node:node /app
RUN chmod +x /app/docker-entrypoint.sh

# Default port (override with -e PORT=xxxx)
EXPOSE 3117
ENV PORT=3117 \
    AUTO_OPEN_BROWSER=false \
    NODE_ENV=production

# Health check
HEALTHCHECK --interval=60s --timeout=10s --start-period=45s --retries=3 \
  CMD node -e "fetch('http://127.0.0.1:'+(process.env.PORT||3117)+'/api/health').then(r=>{if(![200,503].includes(r.status))process.exit(1);return r.json()}).then(j=>{if(['error'].includes(j.status))process.exit(1)}).catch(()=>process.exit(1))"

ENTRYPOINT ["/app/docker-entrypoint.sh"]
CMD ["node", "server.mjs"]
