FROM node:20-bookworm AS sdk-builder
WORKDIR /workspace/cyclops-cs

RUN apt-get update \
    && apt-get install --yes --no-install-recommends build-essential curl pkg-config \
    && rm -rf /var/lib/apt/lists/* \
    && curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs \
      | sh -s -- -y --profile minimal --default-toolchain 1.97.0

ENV PATH="/root/.cargo/bin:${PATH}"

COPY cyclops-cs/ .
RUN ./scripts/build-browser-sdk-binding.sh

# Build stage — produces /app/dist (Vite output).
FROM node:20-alpine AS builder
WORKDIR /app

# pnpm via corepack (matches the repo's pnpm-based workflow).
RUN corepack enable && corepack prepare pnpm@10.12.3 --activate

# Build the runtime-neutral design dependency from its canonical source. The
# root Docker context is required because this package is a sibling of the app.
COPY packages/cua-design/package.json /packages/cua-design/package.json
COPY packages/cua-design/assets /packages/cua-design/assets
COPY packages/cua-design/src /packages/cua-design/src
COPY packages/cua-design/scripts /packages/cua-design/scripts
RUN node /packages/cua-design/scripts/build.mjs

# Install deps first (better layer caching). patches/ must be present before
# install so pnpm can apply pnpm.patchedDependencies (e.g. the @novnc BGR fix).
COPY cyclops-cs/package.json cyclops-cs/pnpm-lock.yaml cyclops-cs/pnpm-workspace.yaml ./
COPY cyclops-cs/patches ./patches
RUN pnpm install --frozen-lockfile

# Build.
COPY cyclops-cs/ .
COPY --from=sdk-builder /workspace/cyclops-cs/sdk-bindings/ts-uniffi-browser/ts/index.web.ts ./sdk-bindings/ts-uniffi-browser/ts/index.web.ts
COPY --from=sdk-builder /workspace/cyclops-cs/sdk-bindings/ts-uniffi-browser/ts/wasm-bindgen ./sdk-bindings/ts-uniffi-browser/ts/wasm-bindgen
ARG VITE_CUA_REVIEW_VISUAL_PREVIEW=false
ENV VITE_CUA_REVIEW_VISUAL_PREVIEW=${VITE_CUA_REVIEW_VISUAL_PREVIEW}
RUN pnpm build:app

# Runtime stage — nginx serves static files and proxies /api to the backend.
FROM nginx:1.27-alpine AS runtime

# In-cluster DNS for the cyclops-cs-backend Service (sibling Deployment
# in the same namespace). Override if the backend is reached at a
# different hostname.
#
# Use the short Service name, NOT the FQDN. nginx:alpine uses musl;
# with ndots:5 the 4-dot FQDN can't be resolved at config-parse time
# and nginx crashloops with "host not found in upstream". The short
# name resolves through the search list at runtime.
ENV CYCLOPS_CS_BACKEND=http://cyclops-cs-backend:8080

# Default Keycloak runtime config for the SPA. Overridden via the
# CYCLOPS_CS_CONFIG_JSON env var (JSON object as a string) at deploy
# time — nginx envsubst inlines it into /config.js, which the SPA
# loads before the React bundle (window.__CYCLOPS_CS_CFG__).
ENV CYCLOPS_CS_CONFIG_JSON='{"kcUrl":"https://auth.cua.ai","kcRealm":"cyclops-cs","kcClientId":"cyclops-cs-spa"}'

COPY cyclops-cs/nginx.conf /etc/nginx/templates/default.conf.template
COPY --from=builder /app/dist /usr/share/nginx/html
