import { init_agent_scope, listAgentEntries, normalizeAgentId, resolveAgentHomeDir, resolveAgentWorkspaceDir, resolveDefaultAgentId } from "../agent/agent-scope.js";
import { existsSync } from "node:fs";
import { rm } from "node:fs/promises";
//#region src/commands/agents.config.ts
/**
* Mutate `agents.list` / bindings when adding or removing agents.
*/
init_agent_scope();
function findAgentEntryIndex(list, agentId) {
	const id = normalizeAgentId(agentId);
	return list.findIndex((e) => normalizeAgentId(e.id) === id);
}
function applyAgentConfig(cfg, params) {
	const agentId = normalizeAgentId(params.agentId);
	const name = params.name?.trim();
	const list = listAgentEntries(cfg);
	const index = findAgentEntryIndex(list, agentId);
	const base = index >= 0 ? list[index] : {
		id: agentId,
		enabled: true
	};
	const nextEntry = {
		...base,
		enabled: base.enabled ?? true,
		...name ? { name } : {},
		...params.description?.trim() ? { description: params.description.trim() } : {},
		...params.workspace ? { workspace: params.workspace } : {},
		...params.agentDir ? { agentDir: params.agentDir } : {},
		...params.model ? { model: { primary: params.model } } : {}
	};
	const nextList = [...list];
	if (index >= 0) nextList[index] = nextEntry;
	else {
		if (nextList.length === 0 && agentId !== normalizeAgentId(resolveDefaultAgentId(cfg))) nextList.push({
			id: resolveDefaultAgentId(cfg),
			enabled: true
		});
		nextList.push(nextEntry);
	}
	return {
		...cfg,
		agents: {
			...cfg.agents,
			list: nextList
		}
	};
}
function pruneAgentConfig(cfg, agentId) {
	const id = normalizeAgentId(agentId);
	const nextAgentsList = listAgentEntries(cfg).filter((e) => normalizeAgentId(e.id) !== id);
	const nextAgents = nextAgentsList.length > 0 ? nextAgentsList : void 0;
	const bindings = cfg.bindings ?? [];
	const filteredBindings = bindings.filter((b) => normalizeAgentId(b.agentId) !== id);
	return {
		config: {
			...cfg,
			agents: nextAgents ? {
				...cfg.agents,
				list: nextAgents
			} : {
				...cfg.agents,
				list: void 0
			},
			bindings: filteredBindings
		},
		removedBindings: bindings.length - filteredBindings.length
	};
}
async function removeAgentDirsFromDisk(cfg, id) {
	const aid = normalizeAgentId(id);
	if (aid === "main") throw new Error("Refusing to delete the main agent home on disk from this command.");
	const home = resolveAgentHomeDir(cfg, aid);
	const ws = resolveAgentWorkspaceDir(cfg, aid);
	if (existsSync(home)) await rm(home, {
		recursive: true,
		force: true
	});
	if (existsSync(ws) && ws !== home) await rm(ws, {
		recursive: true,
		force: true
	});
}
//#endregion
export { applyAgentConfig, findAgentEntryIndex, listAgentEntries, pruneAgentConfig, removeAgentDirsFromDisk };

//# sourceMappingURL=agents.config.js.map