const fs = require("node:fs");
const path = require("node:path");

function copyFile(src, dst) {
  fs.mkdirSync(path.dirname(dst), { recursive: true });
  fs.copyFileSync(src, dst);
}

function pkgRoot(pkg) {
  try {
    return path.dirname(require.resolve(`${pkg}/package.json`));
  } catch {
    const entry = require.resolve(pkg);
    let dir = path.dirname(entry);
    for (let i = 0; i < 8; i++) {
      if (fs.existsSync(path.join(dir, "package.json"))) return dir;
      dir = path.dirname(dir);
    }
    throw new Error(`Unable to locate package root: ${pkg}`);
  }
}

function main() {
  const root = path.resolve(__dirname, "..");
  const assets = path.join(root, "assets");

  // Mermaid bundle (browser).
  // Keep it local; no external fetches at runtime.
  copyFile(path.join(pkgRoot("mermaid"), "dist/mermaid.min.js"), path.join(assets, "js/mermaid.min.js"));

  // Paged.js bundle.
  copyFile(path.join(pkgRoot("pagedjs"), "dist/paged.polyfill.js"), path.join(assets, "js/paged.polyfill.js"));

  // Fonts: only include latin subsets required by the default CSS.
  const sansDir = path.join(pkgRoot("@fontsource/ibm-plex-sans"), "files");
  const monoDir = path.join(pkgRoot("@fontsource/ibm-plex-mono"), "files");

  copyFile(path.join(sansDir, "ibm-plex-sans-latin-400-normal.woff2"), path.join(assets, "fonts/ibm-plex-sans-latin-400-normal.woff2"));
  copyFile(path.join(sansDir, "ibm-plex-sans-latin-600-normal.woff2"), path.join(assets, "fonts/ibm-plex-sans-latin-600-normal.woff2"));
  copyFile(path.join(monoDir, "ibm-plex-mono-latin-400-normal.woff2"), path.join(assets, "fonts/ibm-plex-mono-latin-400-normal.woff2"));
}

main();
