# ==========================================
# Chat Switchboard - Frontend Dockerfile
# ==========================================
# Static SPA served by nginx. In k8s, the
# Ingress routes /api/ and /ws to the backend
# service directly.
#
# Supports path-based deployment via BASE_PATH
# env var (e.g. /dev, /test, or empty for root).
# The entrypoint generates the nginx config and
# injects BASE_PATH into index.html at startup.
#
# v0.22.6+: Set BACKEND_URL to proxy page routes
# (/, /login, /admin, /editor, /notes, /settings)
# to the Go backend for server-rendered templates.
# When unset, page routes fall through to SPA.
#
# Build context: repo root
# ==========================================

# Stage 1: Download vendor libs (vendor/ is gitignored)
FROM node:20-alpine AS vendor
WORKDIR /tmp
RUN npm pack marked@16.3.0 dompurify@3.2.4 mermaid@11.4.1 katex@0.16.11 2>/dev/null && \
    mkdir -p /vendor/mermaid /vendor/katex/fonts && \
    tar xzf marked-*.tgz  -C /tmp && cp /tmp/package/lib/marked.umd.js  /vendor/marked.min.js && \
    rm -rf /tmp/package && \
    tar xzf dompurify-*.tgz -C /tmp && cp /tmp/package/dist/purify.min.js /vendor/purify.min.js && \
    rm -rf /tmp/package && \
    tar xzf mermaid-*.tgz -C /tmp && cp /tmp/package/dist/mermaid.min.js /vendor/mermaid/mermaid.min.js && \
    rm -rf /tmp/package && \
    tar xzf katex-*.tgz -C /tmp && \
    cp /tmp/package/dist/katex.min.js /vendor/katex/katex.min.js && \
    cp /tmp/package/dist/katex.min.css /vendor/katex/katex.min.css && \
    cp -r /tmp/package/dist/fonts/* /vendor/katex/fonts/ && \
    rm -rf /tmp/package /tmp/*.tgz

# Stage 2: CM6 editor bundle (esbuild → single IIFE)
FROM node:20-alpine AS cm6-build
WORKDIR /build
COPY src/editor/ /build/src/editor/
COPY scripts/build-editor.sh /build/scripts/build-editor.sh
RUN cd /build/src/editor && npm ci --loglevel=warn
RUN sh /build/scripts/build-editor.sh /build/dist

# Stage 3: nginx + entrypoint
FROM nginx:1-alpine

# Remove default config — entrypoint generates it
RUN rm -f /etc/nginx/conf.d/default.conf

COPY src/ /usr/share/nginx/html/
COPY --from=vendor /vendor/ /usr/share/nginx/html/vendor/
COPY --from=cm6-build /build/dist/ /usr/share/nginx/html/vendor/codemirror/
COPY VERSION /VERSION
COPY docker-entrypoint-fe.sh /docker-entrypoint-fe.sh
RUN chmod +x /docker-entrypoint-fe.sh

EXPOSE 80

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost/healthz 2>/dev/null || \
        wget --no-verbose --tries=1 --spider http://localhost/ || exit 1

ENTRYPOINT ["/docker-entrypoint-fe.sh"]
