FROM node:22-alpine AS builder

RUN apk upgrade --no-cache

WORKDIR /app

COPY package*.json ./
RUN npm ci --ignore-scripts

COPY tsconfig.json ./
COPY src ./src

RUN npm run build

# ── Spec corpus (CAP-17) ─────────────────────────────────────────
# Opt-in build-time pull from Gitea, so the production spec corpus ships
# decoupled from core code and updates on its own cadence. When SPECS_GIT_URL
# is set, clone the corpus from Gitea (optionally at SPECS_GIT_REF); when unset,
# fall back to the in-repo example specs (local/dev + CI default). Either way
# the runtime image's ./specs is the single spec dir the bot reads via
# config.SPECS_DIR.
FROM alpine:3 AS specs
ARG SPECS_GIT_URL=
ARG SPECS_GIT_REF=
RUN apk add --no-cache git
WORKDIR /spec-source
COPY specs ./bundled
RUN if [ -n "$SPECS_GIT_URL" ]; then \
      git clone "$SPECS_GIT_URL" pulled \
        && if [ -n "$SPECS_GIT_REF" ]; then git -C pulled checkout "$SPECS_GIT_REF"; fi \
        && rm -rf bundled && mv pulled final; \
    else \
      mv bundled final; \
    fi

# ── Runtime image ──────────────────────────────────────────────
FROM node:22-alpine

RUN apk upgrade --no-cache

WORKDIR /app

ENV NODE_ENV=production

COPY package*.json ./
RUN npm ci --omit=dev --ignore-scripts

COPY --from=builder /app/dist ./dist
COPY --from=specs /spec-source/final ./specs
COPY lore ./lore
COPY persona.yaml ./persona.yaml

CMD ["node", "dist/bot/index.js"]