import { applyModuleOverridesToModules } from "@open-mercato/shared/modules/overrides";
import { invalidateDictionaryCache } from "../i18n/dictionary-cache.js";
import { createLogger } from "../logger/index.js";
const logger = createLogger("shared").child({ component: "modules-registry" });
const GLOBAL_KEY = "__openMercatoModulesRegistry__";
function getGlobalModules() {
  return globalThis[GLOBAL_KEY] ?? null;
}
function setGlobalModules(modules) {
  ;
  globalThis[GLOBAL_KEY] = modules;
}
function hasRuntimeContracts(entry) {
  return Object.keys(entry).some((key) => key !== "id" && key !== "translations");
}
function isI18nOnlyRegistration(modules) {
  return modules.length > 0 && modules.every((entry) => !hasRuntimeContracts(entry));
}
function mergeI18nModules(existing, incoming) {
  const incomingById = new Map(incoming.map((entry) => [entry.id, entry]));
  const existingIds = new Set(existing.map((entry) => entry.id));
  const merged = existing.map((entry) => {
    const i18nModule = incomingById.get(entry.id);
    if (!i18nModule?.translations) return entry;
    return {
      ...entry,
      translations: i18nModule.translations
    };
  });
  for (const entry of incoming) {
    if (!existingIds.has(entry.id)) merged.push(entry);
  }
  return merged;
}
function registerModules(modules) {
  const existing = getGlobalModules();
  if (existing !== null && process.env.NODE_ENV === "development") {
    logger.debug("Modules re-registered (this may occur during HMR)");
  }
  const nextModules = applyModuleOverridesToModules(modules);
  const shouldMergeI18nOnly = existing !== null && existing.some(hasRuntimeContracts) && isI18nOnlyRegistration(nextModules);
  setGlobalModules(shouldMergeI18nOnly ? mergeI18nModules(existing, nextModules) : nextModules);
  invalidateDictionaryCache();
}
function getModules() {
  const modules = getGlobalModules();
  if (!modules) {
    throw new Error("[Bootstrap] Modules not registered. Call registerModules() at bootstrap.");
  }
  return modules;
}
export {
  getModules,
  registerModules
};
//# sourceMappingURL=registry.js.map
