import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import terser from "@rollup/plugin-terser";
import fs from "node:fs";
import path from "node:path";


// Inline regex-based externalizer for Debian + node_modules Moment
function externalizeMoment() {
  return {
    name: "externalize-moment",
    async resolveId(source, importer) {
      const resolved = await this.resolve(source, importer, { skipSelf: true });
      if (!resolved || !resolved.id) return null;

      const id = resolved.id;

      // Inline regex: match any path ending in moment or moment.js
      if (/(?:^|\/)moment(?:\.js)?$/.test(id)) {
//        console.log("[externalizeMoment] external:", id);
        return { id : 'moment', external: true };
      }

      return null;
    }
  };
}

const localeDir = "src/locale";
const locales = fs.readdirSync(localeDir).filter(f => f.endsWith(".js"));

const globalsLocale = id => "moment";

const basePlugins = [
  resolve({
    moduleDirectories: ["src", "node_modules"]
  }),
  commonjs({
    requireReturnsDefault: "auto",
    extensions: [".js"]
  }),
];

const debugIds = {
  name: "debug-ids",
  resolveId(source, importer) {
    console.log("[resolveId]", { source, importer });
    return null;
  }
};

// ------------------------------------------------------------
// Helper: build locale bundles using two loops
// ------------------------------------------------------------
function buildLocale(name, input) {
  const formats = [
    { fmt: "umd", ext: "js", min: [false, true], opts: { name: `moment_locale_${name}`, strict: false, globals: globalsLocale } },
    { fmt: "cjs", ext: "cjs", min: [false], opts: { exports: "auto", globals: { moment: "moment" } } },
    { fmt: "esm", ext: "mjs", min: [false], opts: { globals: { moment: "moment" } } }
  ];

  const builds = [];

  for (const { fmt, ext, opts, min } of formats) {
    for (const mini of [false, true]) {
      const map = fmt == 'esm' ? false : true;
      const file = mini
        ? `dist/locale/${name}.min.${ext}`
        : `dist/locale/${name}.${ext}`;

      const plugins = [
//        fmt === "cjs" ? debugIds : null,
        ...basePlugins,
        externalizeMoment(),
        mini ? terser() : null,
      ].filter(Boolean);

      builds.push({
        input,
        output: {
          file,
          format: fmt,
          sourcemap: map,
          ...opts
        },
        external: () => false,
        plugins
      });
    }
  }

  return builds;
}

// ------------------------------------------------------------
// Main Moment.js builds (UMD / CJS / ESM + min)
// ------------------------------------------------------------
const momentBuilds = (() => {
  const formats = [
    { fmt: "umd", ext: "js", min: [false, true], opts: { name: "moment", strict: false } },
    { fmt: "cjs", ext: "cjs", min: [false], opts: { exports: "auto" } },
    { fmt: "esm", ext: "mjs", min: [false], opts: {} }
  ];

  const builds = [];

  for (const { fmt, ext, opts, min } of formats) {
    const map = fmt == 'esm' ? false : true;
    for (const mini of min) {
      const file = mini
        ? `dist/moment.min.${ext}`
        : `dist/moment.${ext}`;

      const plugins = [
        ...basePlugins,
        mini ? terser() : null
      ].filter(Boolean);

      builds.push({
        input: "src/moment.js",
        output: {
          file,
          format: fmt,
          sourcemap: map,
          ...opts
        },
        external: () => false,
        plugins
      });
    }
  }

  return builds;
})();


// ------------------------------------------------------------
// Combined locale bundle (generated-locales.js)
// ------------------------------------------------------------
const combinedLocaleBuilds = (() => {
  const input = "src/src-moment-locales.js";
  const name = "locales"; // bundle name prefix

  const formats = [
    { fmt: "umd", ext: "js", min: [false, true], opts: { name: `moment_${name}`, strict: false, globals: globalsLocale } },
    { fmt: "cjs", ext: "cjs", min: [false], opts: { exports: "auto", globals: { moment: "moment" } } },
    { fmt: "esm", ext: "mjs", min: [false], opts: { globals: { moment: "moment" } } }
  ];

  const builds = [];

  for (const { fmt, ext, opts, min} of formats) {
    for (const mini of min) {
      const map = fmt == 'esm' ? false : true;
      const file = mini
        ? `min/${name}.min.${ext}`
        : `min/${name}.${ext}`;

      const plugins = [
        ...basePlugins,
        externalizeMoment(),
        mini ? terser() : null
      ].filter(Boolean);

      builds.push({
        input,
        output: {
          file,
          format: fmt,
          sourcemap: map,
          ...opts
        },
        external: () => false,
        plugins
      });
    }
  }

  return builds;
})();

// ------------------------------------------------------------
// Combined Moment + Locales bundle (moment-locale.*)
// ------------------------------------------------------------
const momentLocaleBuilds = (() => {
  const input = "src/src-moment-locales.js";
  const name = "moment-with-locales";

  const formats = [
    { fmt: "umd", ext: "js", min: [false, true], opts: { name: "moment", strict: false } },
    { fmt: "cjs", ext: "cjs", min: [false], opts: { exports: "auto" } },
    { fmt: "esm", ext: "mjs", min: [false], opts: {} }
  ];

  const builds = [];

  for (const { fmt, ext, opts, min } of formats) {
    for (const mini of min) {
      const map = fmt == 'esm' ? false : true;
      const file = mini
        ? `min/${name}.min.${ext}`
        : `min/${name}.${ext}`;

      const plugins = [
        ...basePlugins,
        // IMPORTANT: do NOT externalize moment here
        mini ? terser() : null
      ].filter(Boolean);

      builds.push({
        input,
        output: {
          file,
          format: fmt,
          sourcemap: map,
          ...opts
        },
        external: () => false, // moment is bundled
        plugins
      });
    }
  }

  return builds;
})();



// ------------------------------------------------------------
// Export final config
// ------------------------------------------------------------
export default [
  ...momentBuilds,
  ...combinedLocaleBuilds,
  ...momentLocaleBuilds,
  ...locales.flatMap(locale => {
    const name = path.basename(locale, ".js");
    const input = `src/locale/${locale}`;
    return buildLocale(name, input);
  }),
];

