import { TranslationService } from "../services/translation.service";
function deepMergeMessages(target, source) {
  const result = { ...target };
  for (const key of Object.keys(source)) {
    const sourceValue = source[key];
    const targetValue = result[key];
    if (sourceValue !== null && typeof sourceValue === "object" && !Array.isArray(sourceValue) && targetValue !== null && typeof targetValue === "object" && !Array.isArray(targetValue)) {
      result[key] = deepMergeMessages(
        targetValue,
        sourceValue
      );
    } else if (sourceValue !== void 0) {
      result[key] = sourceValue;
    }
  }
  return result;
}
function getLocaleFallbackChain(locale) {
  const chain = [locale];
  if (locale.includes("-")) {
    chain.push(locale.split("-")[0]);
  }
  if (!chain.includes("en")) {
    chain.push("en");
  }
  return chain;
}
async function loadCoreTranslations(locale) {
  try {
    const coreMessages = await import(`../../messages/${locale}/index.ts`);
    return coreMessages.default || coreMessages;
  } catch {
    return {};
  }
}
let registeredThemeMessages = {};
function registerThemeMessages(locale, messages) {
  registeredThemeMessages[locale] = messages;
}
async function loadThemeTranslations(locale) {
  const activeTheme = process.env.NEXT_PUBLIC_ACTIVE_THEME;
  if (activeTheme) {
    const registryMessages = await TranslationService.load(activeTheme, locale);
    if (Object.keys(registryMessages).length > 0) {
      return registryMessages;
    }
  }
  if (registeredThemeMessages[locale]) {
    return registeredThemeMessages[locale];
  }
  return {};
}
async function loadEntityTranslationsFromRegistry(locale) {
  const activeTheme = process.env.NEXT_PUBLIC_ACTIVE_THEME || "default";
  try {
    const entityTranslations = await TranslationService.loadAllEntities(activeTheme, locale);
    return entityTranslations;
  } catch (error) {
    console.warn(`[translations] Failed to load entity translations for ${locale}:`, error);
    return {};
  }
}
async function loadMergedTranslations(locale) {
  const fallbackChain = getLocaleFallbackChain(locale);
  let mergedMessages = {};
  for (const fallbackLocale of [...fallbackChain].reverse()) {
    try {
      const coreMessages = await loadCoreTranslations(fallbackLocale);
      mergedMessages = deepMergeMessages(mergedMessages, coreMessages);
    } catch {
    }
  }
  try {
    const themeMessages = await loadThemeTranslations(locale);
    mergedMessages = deepMergeMessages(mergedMessages, themeMessages);
  } catch {
    console.warn(`[translations] No theme messages for ${locale}`);
  }
  try {
    const entityMessages = await loadEntityTranslationsFromRegistry(locale);
    if (Object.keys(entityMessages).length > 0) {
      mergedMessages = deepMergeMessages(mergedMessages, entityMessages);
    }
  } catch {
  }
  return mergedMessages;
}
export {
  loadMergedTranslations,
  registerThemeMessages
};
