import { logger } from "../logger.mjs";
import { getProjectRequire } from "../utils/ESMxCJSHelpers.mjs";
import { parseFileContent } from "./parseFileContent.mjs";
import { transpileTSToMJSSync } from "./transpileTSToMJS.mjs";
import { extname } from "node:path";
import "node:fs/promises";
import { readFileSync } from "node:fs";

//#region ../@intlayer/cli/dist/esm/unmerged-dictionaries-entry/dist/esm/config/dist/esm/loadExternalFile/loadExternalFile.mjs
/**
* Load the content declaration from the given path
*
* Accepts JSON, JS, MJS and TS files as configuration
*/
const loadExternalFileSync = (filePath, options) => {
	const fileExtension = extname(filePath);
	const safeProjectRequire = options?.projectRequire ?? getProjectRequire();
	try {
		if (fileExtension === "json") {
			delete safeProjectRequire.cache[safeProjectRequire.resolve(filePath)];
			return safeProjectRequire(filePath);
		}
		const moduleResultString = transpileTSToMJSSync(readFileSync(filePath, "utf-8"), filePath);
		if (!moduleResultString) {
			logger("File could not be loaded.", { level: "error" });
			return;
		}
		const fileContent = parseFileContent(moduleResultString, {
			projectRequire: options?.projectRequire,
			envVarOptions: options?.envVarOptions,
			additionalEnvVars: options?.additionalEnvVars,
			mocks: options?.mocks,
			aliases: options?.aliases
		});
		if (typeof fileContent === "undefined") {
			logger(`File file could not be loaded. Path : ${filePath}`);
			return;
		}
		return fileContent;
	} catch (error) {
		logger([`Error: ${error.message} - `, JSON.stringify(error.stack, null, 2)], { level: "error" });
	}
};

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