import { writeFileIfChanged } from "../writeFileIfChanged.mjs";
import { getFileHash } from "../utils/getFileHash.mjs";
import { basename, extname, join, relative } from "node:path";
import { mkdir } from "node:fs/promises";
import { normalizePath } from "@intlayer/config";
import fg from "fast-glob";

//#region ../@intlayer/webpack/dist/esm/chokidar/dist/esm/createType/createModuleAugmentation.mjs
/** Returns lines like: [Locales.FRENCH]: 1; */
const formatLocales = (locales) => locales.map((locale) => `    "${locale}": 1;`).join("\n");
/** Generate the content of the module augmentation file */
const generateTypeIndexContent = (typeFiles, configuration) => {
	const { content, internationalization } = configuration;
	const { moduleAugmentationDir } = content;
	const { locales, requiredLocales, strictMode } = internationalization;
	let fileContent = "import \"intlayer\";\n";
	const dictionariesRef = typeFiles.map((dictionaryPath) => ({
		relativePath: `./${relative(moduleAugmentationDir, dictionaryPath)}`,
		id: basename(dictionaryPath, extname(dictionaryPath)),
		hash: `_${getFileHash(dictionaryPath)}`
	}));
	for (const dictionary of dictionariesRef) fileContent += `import ${dictionary.hash} from '${dictionary.relativePath}';\n`;
	fileContent += "\n";
	const formattedDictionaryMap = dictionariesRef.map((dictionary) => `    "${dictionary.id}": typeof ${dictionary.hash};`).join("\n");
	const declared = locales;
	const requiredSanitized = requiredLocales?.length ? requiredLocales.filter((requiredLocales$1) => declared.includes(requiredLocales$1)) : declared;
	const formattedDeclaredLocales = formatLocales(declared);
	const formattedRequiredLocales = formatLocales(requiredSanitized);
	const strictKey = strictMode === "strict" ? "strict" : strictMode === "inclusive" ? "inclusive" : "loose";
	/**
	* Module augmentation that ONLY adds keys to registries.
	* No types/aliases redefined here—avoids merge conflicts.
	*/
	fileContent += `declare module 'intlayer' {\n`;
	fileContent += `  interface __DictionaryRegistry {\n${formattedDictionaryMap}\n  }\n\n`;
	fileContent += `  interface __DeclaredLocalesRegistry {\n${formattedDeclaredLocales}\n  }\n\n`;
	fileContent += `  interface __RequiredLocalesRegistry {\n${formattedRequiredLocales}\n  }\n\n`;
	fileContent += `  interface __StrictModeRegistry { mode: '${strictKey}' }\n`;
	fileContent += `}\n`;
	return fileContent;
};
/** Generate the index file merging all the types */
const createModuleAugmentation = async (configuration) => {
	const { moduleAugmentationDir, typesDir } = configuration.content;
	await mkdir(moduleAugmentationDir, { recursive: true });
	const tsContent = generateTypeIndexContent(await fg(normalizePath(`${typesDir}/*.ts`), { ignore: ["**/*.d.ts"] }), configuration);
	await writeFileIfChanged(join(moduleAugmentationDir, "intlayer.d.ts"), tsContent);
};

//#endregion
export { createModuleAugmentation };
//# sourceMappingURL=createModuleAugmentation.mjs.map