FROM node:22-slim AS builder

WORKDIR /app

# Copy package files
COPY package*.json ./
COPY tsconfig.json ./

# Install dependencies
RUN npm install

# Copy protobuf definitions
COPY protobuf ../protobuf/

# Copy source
COPY src ./src

# Build (includes protobuf generation)
RUN npm run build

# Production image
FROM node:22-slim

WORKDIR /app

RUN apt-get update && apt-get install -y bash zstd ca-certificates && rm -rf /var/lib/apt/lists/*

# Create non-root user
RUN groupadd --gid 1001 nodejs && \
    useradd --uid 1001 --gid nodejs --shell /bin/bash --create-home nodejs && \
    chown -R nodejs:nodejs /app

# Copy package files
COPY package*.json ./

# Install production dependencies only
RUN npm install --omit=dev

# Copy built application
COPY --from=builder /app/dist ./dist

# Copy protobuf definitions for runtime loading
COPY protobuf ./protobuf

# Copy k8s templates (not included in TypeScript build)
COPY src/k8s/templates ./dist/k8s/templates

# Copy harness prompts (welcome.md, etc.)
COPY src/harness/prompts ./dist/harness/prompts

# Copy wiki knowledge base
COPY knowledge ./knowledge

# Copy agent prompt pages (agent-*.md, index.md, tools.md)
COPY prompt ./prompt

# Copy entrypoint script
COPY entrypoint.sh ./
RUN chmod +x entrypoint.sh

# Ensure nodejs user owns everything
RUN chown -R nodejs:nodejs /app

USER nodejs

EXPOSE 3000

ENTRYPOINT ["./entrypoint.sh"]
