import { init_paths, resolveBundledExtensionsDir, resolveExtensionsDir } from "../config/paths.js";
import { isRecord } from "../utils/is-record.js";
import { normalizeConfiguredMcpServers } from "../config/mcp-config-normalize.js";
import { existsSync, readFileSync, readdirSync } from "node:fs";
import { join } from "node:path";
//#region src/extensions/bundle-mcp.ts
init_paths();
function extractMcpServerMap(raw) {
	if (!isRecord(raw)) return {};
	const nested = isRecord(raw.mcpServers) ? raw.mcpServers : isRecord(raw.servers) ? raw.servers : raw;
	if (!isRecord(nested)) return {};
	const result = {};
	for (const [serverName, serverRaw] of Object.entries(nested)) {
		if (!isRecord(serverRaw)) continue;
		result[serverName] = { ...serverRaw };
	}
	return result;
}
function readMcpJsonFile(filePath) {
	if (!existsSync(filePath)) return {};
	try {
		return extractMcpServerMap(JSON.parse(readFileSync(filePath, "utf-8")));
	} catch {
		return {};
	}
}
function isExtensionEnabled(extensionId, cfg) {
	if ((cfg?.extensions?.disabled ?? []).includes(extensionId)) return false;
	const enabled = cfg?.extensions?.enabled;
	if (Array.isArray(enabled) && enabled.length > 0) return enabled.includes(extensionId);
	return true;
}
function scanExtensionsRoot(root, cfg, merged, diagnostics) {
	if (!existsSync(root)) return;
	for (const entry of readdirSync(root, { withFileTypes: true })) {
		if (!entry.isDirectory()) continue;
		const extensionId = entry.name;
		if (!isExtensionEnabled(extensionId, cfg)) continue;
		const servers = readMcpJsonFile(join(join(root, extensionId), ".mcp.json"));
		for (const [name, server] of Object.entries(servers)) {
			const key = merged[name] ? `${extensionId}__${name}` : name;
			if (merged[name] && !merged[`${extensionId}__${name}`]) diagnostics.push({
				extensionId,
				message: `MCP server "${name}" renamed to "${key}" due to name collision.`
			});
			merged[key] = server;
		}
	}
}
function loadEnabledBundleMcpConfig(params) {
	params.workspaceDir;
	const merged = {};
	const diagnostics = [];
	scanExtensionsRoot(resolveExtensionsDir(), params.cfg, merged, diagnostics);
	const bundled = resolveBundledExtensionsDir();
	if (bundled) scanExtensionsRoot(bundled, params.cfg, merged, diagnostics);
	return {
		config: { mcpServers: merged },
		diagnostics
	};
}
function hasAnyMcpServers(cfg) {
	const user = normalizeConfiguredMcpServers(cfg?.mcp?.servers);
	if (Object.keys(user).length > 0) return true;
	const bundle = loadEnabledBundleMcpConfig({ cfg });
	return Object.keys(bundle.config.mcpServers).length > 0;
}
//#endregion
export { hasAnyMcpServers, loadEnabledBundleMcpConfig };

//# sourceMappingURL=bundle-mcp.js.map