import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { homedir } from "node:os";
import { createJiti } from "jiti";
//#region src/config.ts
const DEFAULTS = {
	plannarFolder: ".plannar",
	exportsFolder: ".plannar/exports"
};
function applyDerivedDefaults(config, overrides) {
	if (!overrides.exportsFolder) config.exportsFolder = `${config.plannarFolder}/exports`;
	return config;
}
async function loadConfigFile(filePath) {
	if (!existsSync(filePath)) return null;
	if (filePath.endsWith(".json")) {
		const raw = readFileSync(filePath, "utf-8");
		return JSON.parse(raw);
	}
	const mod = await createJiti(import.meta.url).import(filePath);
	return mod.default ?? mod;
}
function merge(target, source) {
	const result = { ...target };
	for (const key of Object.keys(source)) {
		const sv = source[key];
		const tv = target[key];
		if (sv && typeof sv === "object" && !Array.isArray(sv) && tv && typeof tv === "object" && !Array.isArray(tv)) result[key] = merge(tv, sv);
		else result[key] = sv;
	}
	return result;
}
async function resolveConfig(cwd = process.cwd()) {
	const globalConfigDir = join(homedir(), ".config", "plannar");
	let globalConfig = null;
	for (const ext of [
		"js",
		"ts",
		"json"
	]) {
		globalConfig = await loadConfigFile(join(globalConfigDir, `plannar.config.${ext}`));
		if (globalConfig) break;
	}
	let localConfig = null;
	for (const ext of [
		"js",
		"ts",
		"json"
	]) {
		localConfig = await loadConfigFile(join(cwd, `plannar.config.${ext}`));
		if (localConfig) break;
	}
	let merged = { ...DEFAULTS };
	if (globalConfig) merged = merge(merged, globalConfig);
	if (localConfig) merged = merge(merged, localConfig);
	return applyDerivedDefaults(merged, { exportsFolder: Boolean(localConfig?.exportsFolder || globalConfig?.exportsFolder) });
}
//#endregion
export { resolveConfig as n, merge as t };
