import { r as writeJsonArray, t as readJsonArray } from "./json-store-WWsFzXub.js";
import { t as hybridSearch } from "./hybrid-search-BmHttLrR.js";
import path from "path";
import { randomBytes } from "crypto";
//#region src/core/sop.ts
function globalPath(dataDir) {
	return path.join(dataDir, ".agentic", "sops.json");
}
function customerPath(dataDir, slug) {
	return path.join(dataDir, "customers", slug, "sops.json");
}
function readFile(p) {
	return readJsonArray(p, "sops");
}
function writeFile(p, sops) {
	writeJsonArray(p, "sops", sops);
}
function addSop(dataDir, s) {
	const sop = {
		id: `sop_${randomBytes(5).toString("hex")}`,
		scope: s.scope,
		...s.slug ? { slug: s.slug } : {},
		title: s.title,
		triggers: s.triggers,
		...s.tags ? { tags: s.tags } : {},
		body: s.body,
		createdAt: (/* @__PURE__ */ new Date()).toISOString()
	};
	const p = s.scope === "global" ? globalPath(dataDir) : customerPath(dataDir, s.slug ?? "");
	writeFile(p, [...readFile(p), sop]);
	return sop;
}
function loadSops(dataDir, slug) {
	const global = readFile(globalPath(dataDir));
	if (!slug) return global;
	return [...global, ...readFile(customerPath(dataDir, slug))];
}
/**
* Find SOPs relevant to a task. Hybrid-search over title+triggers+body; among
* matches, customer-specific SOPs are returned before global ones.
*/
async function findSops(dataDir, query, slug) {
	const sops = loadSops(dataDir, slug);
	const ranked = hybridSearch(query, sops.map((s) => ({
		id: s.id,
		text: `${s.title} ${s.triggers.join(" ")} ${(s.tags ?? []).join(" ")} ${s.body}`
	})));
	const byId = new Map(sops.map((s) => [s.id, s]));
	const matched = ranked.map((r, i) => ({
		sop: byId.get(r.id),
		rank: i
	})).filter((x) => x.sop);
	matched.sort((a, b) => {
		const ac = a.sop.scope === "customer" ? 0 : 1;
		const bc = b.sop.scope === "customer" ? 0 : 1;
		return ac !== bc ? ac - bc : a.rank - b.rank;
	});
	return matched.map((x) => x.sop);
}
//#endregion
export { findSops as n, loadSops as r, addSop as t };

//# sourceMappingURL=sop-BV7ICAFR.js.map