#!/usr/bin/env node
// Copy node_modules/tinymce/ → client/lib/tinymce/ so the editor can
// load entirely from local assets (no jsDelivr, no Tiny Cloud). TinyMCE
// itself resolves plugins/themes/icons relative to its own script's src
// URL, so the whole package directory has to be reachable as a sibling
// tree — single-file copies aren't enough.
import fs from "node:fs";
import path from "node:path";

const root = path.resolve(import.meta.dirname, "..");
const src = path.join(root, "node_modules", "tinymce");
const dst = path.join(root, "client", "lib", "tinymce");

if (!fs.existsSync(src)) {
    console.error(`build-tinymce: source not found at ${src} — run npm install first`);
    process.exit(1);
}

// Mirror via recursive copy, skipping .d.ts / .map (not needed at runtime,
// they add ~3MB).
function copyTree(s, d) {
    const stat = fs.statSync(s);
    if (stat.isDirectory()) {
        fs.mkdirSync(d, { recursive: true });
        for (const name of fs.readdirSync(s)) copyTree(path.join(s, name), path.join(d, name));
    } else {
        if (s.endsWith(".d.ts") || s.endsWith(".map")) return;
        fs.copyFileSync(s, d);
    }
}

fs.rmSync(dst, { recursive: true, force: true });
copyTree(src, dst);

let count = 0, bytes = 0;
function tally(p) {
    const st = fs.statSync(p);
    if (st.isDirectory()) for (const n of fs.readdirSync(p)) tally(path.join(p, n));
    else { count++; bytes += st.size; }
}
tally(dst);
console.log(`build-tinymce: copied ${count} files (${(bytes / 1024 / 1024).toFixed(1)} MB) → client/lib/tinymce/`);
