# syntax=docker/dockerfile:1

# --- Stage 1: Build local doc-core from source ---
FROM node:22-bookworm AS doc-core-builder
WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .
RUN npm run build:cli
RUN npm pack --pack-destination=/tmp

# --- Stage 2: Cache patternfly-org setup ---
FROM node:22-bookworm AS org-base

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

WORKDIR /patternfly-org

ARG ORG_REPO=https://github.com/patternfly/patternfly-org.git
ARG ORG_REF

# run.sh resolves `latest` once and passes its commit SHA here.
RUN git init . \
    && git remote add origin "${ORG_REPO}" \
    && git fetch --depth 1 origin "${ORG_REF}" \
    && git checkout --detach FETCH_HEAD

RUN --mount=type=cache,target=/usr/local/share/.cache/yarn/v6 \
    yarn install --immutable

# --- Stage 3: Prepare a fresh-runtime org build with local doc-core ---
FROM org-base AS audit-runner

WORKDIR /patternfly-org
ENV NODE_OPTIONS="--max-old-space-size=8192"

COPY --from=doc-core-builder /tmp/patternfly-patternfly-doc-core-*.tgz /tmp/patternfly-doc-core.tgz

RUN yarn workspace site add @patternfly/patternfly-doc-core@file:/tmp/patternfly-doc-core.tgz \
    && yarn workspace site run init:docs

ENTRYPOINT [ \
  "/bin/sh", \
  "-ec", \
  "cd /patternfly-org; dist=packages/site/dist; yarn ci:build:doc-core; test -s \"${dist}/apiIndex.json\"; test -s \"${dist}/docs/apiIndex.json\"; mkdir -p /output; cp \"${dist}/apiIndex.json\" /output/apiIndex.dist-root.json; cp \"${dist}/docs/apiIndex.json\" /output/apiIndex.docs.json" \
]
