const IMPORT_RE = /(?:\n|^)import (.*) from ['"](.*)['"]/g;
const EXPORT_DEFAULT_ARRAY_RE = /\nexport default\s*\[([\s\S]*)\]/;
function setup({ nuxt }) {
  if (!nuxt.options.dev || nuxt.options.test)
    return;
  nuxt.hook("app:templates", (app) => {
    app.templates.filter((i) => i.filename?.startsWith("plugins/")).forEach((i) => {
      if (!i.getContents)
        return;
      const original = i.getContents;
      i.getContents = async (...args) => {
        let content = await original(...args);
        const PAYLOAD_KEY = "__NUXT_DEVTOOLS_PLUGINS_METRIC__";
        const WRAPPER_KEY = "__DEVTOOLS_WRAPPER__";
        if (content.includes(PAYLOAD_KEY))
          return content;
        const snippets = `
if (!globalThis.${PAYLOAD_KEY}) {
  Object.defineProperty(globalThis, '${PAYLOAD_KEY}', {
    value: [],
    enumerable: false,
    configurable: true,
  })
}

function ${WRAPPER_KEY} (plugin, src) {
  if (!plugin)
    return plugin

  return defineNuxtPlugin({
    ...plugin,
    async setup (...args) {
      const start = performance.now()
      const result = await plugin.apply(this, args)
      const end = performance.now()
      globalThis.${PAYLOAD_KEY}.push({
        src,
        start,
        end,
        duration: end - start,
      })
      return result
    }
  })
}
`;
        const imports = Array.from(content.matchAll(IMPORT_RE), ([, name, path]) => ({ name, path }));
        content = content.replace(EXPORT_DEFAULT_ARRAY_RE, (_, itemsRaw) => {
          const items = itemsRaw.split(",").map((i2) => i2.trim()).map((i2) => {
            const importItem = imports.find(({ name }) => name === i2);
            if (!importItem)
              return i2;
            return `${WRAPPER_KEY}(${i2}, ${JSON.stringify(importItem.path)})`;
          });
          return `
${snippets}
export default [
${items.join(",\n")}
]
`;
        });
        content = `import { defineNuxtPlugin } from "#imports"
${content}`;
        return content;
      };
    });
  });
}

export { setup };
