# ────────────────────────────────────────────────────────────────
#  Dockerfile — builds rails + sister-agent + CLI into one image
#
#  The image starts `rails serve` in single-process (in-process) mode.
#  For distributed mode, see docker-compose.full.yml which uses the same
#  image but overrides CMD / env vars per container.
# ────────────────────────────────────────────────────────────────

FROM node:22-bookworm-slim AS builder

RUN corepack enable \
  && apt-get update \
  && apt-get install -y --no-install-recommends git ca-certificates openssl \
  && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy manifests first for better layer caching
COPY package.json pnpm-lock.yaml tsconfig.json ./
COPY prisma ./prisma
COPY sister-agent/package.json ./sister-agent/
COPY sister-agent/tsconfig.json ./sister-agent/

# Install deps (root + sister-agent workspace — sister-agent has its own lockfile)
RUN pnpm install --frozen-lockfile

WORKDIR /app/sister-agent
RUN pnpm install --frozen-lockfile || pnpm install

WORKDIR /app

# Copy sources
COPY src ./src
COPY sister-agent/src ./sister-agent/src

# Generate prisma client + build both
RUN npx prisma generate \
  && pnpm build \
  && cd sister-agent && pnpm build

# ────────────── runtime image ──────────────
FROM node:22-bookworm-slim

RUN corepack enable \
  && apt-get update \
  && apt-get install -y --no-install-recommends git ca-certificates openssl wget \
  && rm -rf /var/lib/apt/lists/*

WORKDIR /app

COPY --from=builder /app/package.json /app/pnpm-lock.yaml ./
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/prisma ./prisma
COPY --from=builder /app/sister-agent/package.json ./sister-agent/
COPY --from=builder /app/sister-agent/node_modules ./sister-agent/node_modules
COPY --from=builder /app/sister-agent/dist ./sister-agent/dist

ENV NODE_ENV=production
ENV RAILS_PORT=18800
ENV RAILS_TRANSPORT=in-process
ENV SISTER_AGENT_CORE_PATH=/app/sister-agent/dist/core.js
ENV SISTER_WORKSPACE_DIR=/app/rails-projects

EXPOSE 18800

# Default command: run migrations then start the HTTP server
CMD ["sh", "-c", "npx prisma migrate deploy && node dist/cli/index.js serve"]
