#!/bin/sh
# ==========================================
# scripts/build-editor.sh — Build CM6 Bundle
# ==========================================
# Shared by Dockerfile.frontend, Dockerfile (unified),
# and local development.
#
# Usage:
#   ./scripts/build-editor.sh              # → src/vendor/codemirror/
#   ./scripts/build-editor.sh /build/dist  # → /build/dist/ (Docker)
#
# Prerequisites: Node.js 20+, npm
# ==========================================
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
EDITOR_DIR="${SCRIPT_DIR}/../src/editor"
OUTPUT_DIR="${1:-${SCRIPT_DIR}/../src/vendor/codemirror}"

if [ ! -d "${EDITOR_DIR}" ]; then
    echo "❌ Editor source not found: ${EDITOR_DIR}"
    exit 1
fi

cd "${EDITOR_DIR}"

# Install dependencies if not already present (Docker will have run npm ci)
if [ ! -d node_modules ]; then
    echo "📦 Installing CM6 dependencies..."
    if [ -f package-lock.json ]; then
        npm ci --loglevel=warn
    else
        echo "  ⚠️  No package-lock.json — using npm install"
        npm install --loglevel=warn
    fi
fi

mkdir -p "${OUTPUT_DIR}"

echo "🔨 Building CM6 bundle..."
node build.mjs --outdir="${OUTPUT_DIR}"

echo "✅ CM6 bundle → ${OUTPUT_DIR}"
ls -lh "${OUTPUT_DIR}"/codemirror.bundle.* 2>/dev/null || true
