import {
  logger
} from "./chunk-L2JZBH6K.js";
import {
  cleanup,
  getEventCatalogConfigFile
} from "./chunk-6QENHZZP.js";

// src/generate.js
import path from "path";
function getDefaultExport(importedModule) {
  if (importedModule === null || typeof importedModule !== "object") {
    throw new Error("Invalid module");
  }
  if (typeof importedModule.default === "object" && importedModule.default !== null) {
    return importedModule.default.default || importedModule.default;
  }
  if (typeof importedModule.default !== "undefined") {
    return importedModule.default;
  }
  return importedModule;
}
var generate = async (PROJECT_DIRECTORY) => {
  try {
    const config = await getEventCatalogConfigFile(PROJECT_DIRECTORY);
    const { generators = [] } = config;
    if (!generators.length) {
      logger.info("No configured generators found, skipping generation", "generator");
      return;
    }
    const errors = [];
    for (const generator of generators) {
      let plugin = generator[0];
      const pluginConfig = generator[1];
      if (plugin.startsWith("./")) {
        plugin = path.join(PROJECT_DIRECTORY, plugin);
      }
      if (plugin.includes("<rootDir>")) {
        plugin = plugin.replace("<rootDir>", PROJECT_DIRECTORY);
      }
      try {
        const importedGenerator = await import(plugin);
        const generator2 = getDefaultExport(importedGenerator);
        await generator2({ eventCatalogConfig: {} }, pluginConfig);
      } catch (error) {
        logger.error(`Failed to run generator "${plugin}":`, "generator");
        console.error(error);
        errors.push({ plugin, error });
      }
    }
    await cleanup(PROJECT_DIRECTORY);
    if (errors.length > 0) {
      logger.error(`${errors.length} generator(s) failed:`, "generator");
      for (const { plugin } of errors) {
        logger.error(`  - ${plugin}`, "generator");
      }
    }
  } catch (error) {
    console.error(error);
    await cleanup(PROJECT_DIRECTORY);
  }
};

export {
  generate
};
