import { defaultLocale, locales } from "./config.js";
import { resolveForcedLocale, resolveLocaleFromAcceptLanguage } from "./locale.js";
import { createFallbackTranslator, createTranslator } from "./translate.js";
import { tryGetModules } from "../modules/registry.js";
import { loadAppDictionary } from "./app-dictionaries.js";
import { getCachedDictionary, setCachedDictionary } from "./dictionary-cache.js";
import { registerModules, getModules } from "../modules/registry.js";
import { registerAppDictionaryLoader } from "./app-dictionaries.js";
import { invalidateDictionaryCache } from "./dictionary-cache.js";
function flattenDictionary(source, prefix = "") {
  if (!source || typeof source !== "object" || Array.isArray(source)) return {};
  const result = {};
  for (const [key, value] of Object.entries(source)) {
    if (!key) continue;
    const nextKey = prefix ? `${prefix}.${key}` : key;
    if (typeof value === "string") {
      result[nextKey] = value;
    } else if (value && typeof value === "object" && !Array.isArray(value)) {
      Object.assign(result, flattenDictionary(value, nextKey));
    }
  }
  return result;
}
async function detectLocale() {
  const forced = resolveForcedLocale(process.env);
  if (forced) return forced;
  try {
    const { cookies, headers } = await import("next/headers");
    try {
      const c = (await cookies()).get("locale")?.value;
      if (c && locales.includes(c)) return c;
    } catch {
    }
    try {
      const accept = (await headers()).get("accept-language") || "";
      const match = resolveLocaleFromAcceptLanguage(accept);
      if (match) return match;
    } catch {
    }
  } catch {
  }
  return defaultLocale;
}
async function loadDictionary(locale) {
  const cached = getCachedDictionary(locale);
  if (cached) return cached;
  const baseRaw = await loadAppDictionary(locale);
  const merged = { ...flattenDictionary(baseRaw) };
  const modules = tryGetModules() ?? [];
  for (const m of modules) {
    const dict = m.translations?.[locale];
    if (dict) Object.assign(merged, flattenDictionary(dict));
  }
  setCachedDictionary(locale, merged);
  return merged;
}
async function resolveTranslations() {
  const locale = await detectLocale();
  const dict = await loadDictionary(locale);
  const t = createTranslator(dict);
  const translate = createFallbackTranslator(dict);
  return { locale, dict, t, translate };
}
try {
  require("server-only");
} catch {
}
export {
  detectLocale,
  getModules,
  invalidateDictionaryCache,
  loadDictionary,
  registerAppDictionaryLoader,
  registerModules,
  resolveTranslations
};
//# sourceMappingURL=server.js.map
