import path from "node:path";
import { builtinModules } from "node:module";
import { readFileSync } from "node:fs";

import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import json from "@rollup/plugin-json";
import terser from "@rollup/plugin-terser";
import typescript from "@rollup/plugin-typescript";
import jison from "jison";

// Load dependencies
const pkgJson = JSON.parse(
  readFileSync(path.resolve(process.cwd(), "package.json"), "utf8")
);
const deps = Object.keys(pkgJson.dependencies || {});

// --- Jison plugin ------------------------------------------------------------

function jisonPlugin() {
  return {
    name: "jison",
    transform(src, id) {
      if (!id.endsWith(".jison")) return null;

      const parser = new jison.Generator(src, {
        moduleType: "js",
        "token-stack": true
      });

      const source = parser.generate({ moduleMain: "() => {}" });

      return {
        code: `${source}
          parser.parser = parser;
          export { parser };
          export default parser;
        `,
        map: null
      };
    }
  };
}

// --- Debian system module paths ---------------------------------------------


const debianCommonjsInclude = [
  /node_modules/,
 'srcforbuild',
];

// --- UMD globals -------------------------------------------------------------

const umdGlobals = {
  moment: "moment",
  "@braintree/sanitize-url": "sanitizeUrl",
  d3: "d3",
  dompurify: "DOMPurify",
  khroma: "khroma",
  stylis: "stylis",
  dagre: "dagre",
  graphlib: "graphlib",
  uuid: "uuid",
  "lodash/memoize": "_",
  "lodash.memoize": "_",
  "dagre-d3-es": "dagreD3",
  "dagre-d3/lib/label/add-html-label.js": "addHtmlLabel"
};

// --- Rollup config -----------------------------------------------------------

const entry = "srcforbuild/mermaid.ts";
const outDir = "dist";

export default [
  //
  // FULL BUNDLE (ESM + UMD)
  //
  {
    input: entry,
    external: () => false,

    output: [
      {
        file: `${outDir}/mermaid.esm.mjs`,
        format: "esm",
        sourcemap: true
      },
      {
        file: `${outDir}/mermaid.esm.min.mjs`,
        format: "esm",
        sourcemap: true,
        plugins: [terser()]
      },
      {
        file: `${outDir}/mermaid.js`,
        format: "umd",
        name: "mermaid",
        sourcemap: true,
        globals: umdGlobals
      },
      {
        file: `${outDir}/mermaid.min.js`,
        format: "umd",
        name: "mermaid",
        sourcemap: true,
        globals: umdGlobals,
        plugins: [terser()]
      }
    ],

    plugins: [
      jisonPlugin(),

      typescript({
        tsconfig: "./tsconfig.json",
        importHelpers: true,
        noEmitHelpers: true
      }),

      resolve({
        extensions: [".ts", ".js", ".jison"],
        mainFields: ["module", "main", "browser"],
//        resolveOnly: [/\.jison$/],
        moduleDirectories: ["node_modules"],
        preferBuiltins: false
      }),

      commonjs({
        include: debianCommonjsInclude,
        requireReturnsDefault: "auto",
        defaultIsModuleExports: true
      }),

      json()
    ]
  },

  //
  // CORE BUNDLE (ESM only)
  //
  {
    input: entry,

    external: id =>
      id.startsWith(".") ? false :
      id.startsWith("node:") ||
      builtinModules.includes(id) ||
      deps.includes(id),

    output: [
      {
        file: `${outDir}/mermaid.core.mjs`,
        format: "esm",
        sourcemap: true
      },
      {
        file: `${outDir}/mermaid.core.min.mjs`,
        format: "esm",
        sourcemap: true,
        plugins: [terser()]
      }
    ],

    plugins: [
      jisonPlugin(),

      typescript({
        tsconfig: "./tsconfig.json",
        importHelpers: true,
        noEmitHelpers: true
      }),

      resolve({
        extensions: [".ts", ".js", ".jison"],
        mainFields: ["module", "main", "browser"],
//        resolveOnly: [/\.jison$/],
        moduleDirectories: ["node_modules"],
        preferBuiltins: true
      }),

      commonjs({
        include: debianCommonjsInclude,
        requireReturnsDefault: "auto",
        defaultIsModuleExports: true
      }),

      json()
    ]
  }
];

