import { n as logger } from "./logger-Dyl4VcLO.js";
import { t as escapeRegExp } from "./regex-Jt5DatPi.js";
import path from "path";
import fs from "fs";
import matter from "gray-matter";
import chokidar from "chokidar";
//#region src/sync/transcript-watcher.ts
function watchTranscripts(opts) {
	const { paths, extensions, onFile } = opts;
	const watcher = chokidar.watch(paths, {
		ignored: (p, stats) => {
			if (stats?.isDirectory()) return false;
			return !extensions.some((ext) => p.endsWith(ext));
		},
		awaitWriteFinish: {
			stabilityThreshold: 2e3,
			pollInterval: 100
		},
		ignoreInitial: false,
		persistent: true
	});
	watcher.on("add", (filePath) => {
		onFile(filePath).catch((err) => {
			logger.error("transcript-watcher", "error processing file", {
				filePath,
				error: err.message
			});
		});
	});
	return watcher;
}
async function processTranscriptFile(filePath, slug, dataDir) {
	const source = `file://${filePath}`;
	const { readInteractions, appendInteraction } = await import("./interactions-writer-B2y-73lh.js");
	if ((await readInteractions(dataDir, slug)).includes(source)) return;
	const content = fs.readFileSync(filePath, "utf-8");
	const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
	const filename = filePath.split("/").pop() ?? filePath;
	await appendInteraction(dataDir, slug, {
		date,
		type: "Meeting",
		with: filename,
		subject: filename,
		summary: content.slice(0, 500) + (content.length > 500 ? "..." : ""),
		nextSteps: [],
		sourceRef: source,
		synced: (/* @__PURE__ */ new Date()).toISOString()
	});
	const { indexInLanceDB } = await import("./lancedb-CswQEE5K.js");
	await indexInLanceDB(dataDir, slug, content.slice(0, 2e3), source, {
		date,
		type: "Meeting"
	}).catch((err) => {
		logger.error("transcript-watcher", "LanceDB index failed", { error: err.message });
	});
}
function readCustomerName(customersDir, slug) {
	const mainFactsPath = path.join(customersDir, slug, "main_facts.md");
	if (!fs.existsSync(mainFactsPath)) return slug;
	try {
		const raw = matter(fs.readFileSync(mainFactsPath, "utf-8"));
		return typeof raw.data["name"] === "string" ? raw.data["name"] : slug;
	} catch {
		return slug;
	}
}
function fuzzyMatchCustomer(filePath, content, candidates) {
	const filename = path.basename(filePath).toLowerCase();
	const contentPreview = content.toLowerCase().slice(0, 5e3);
	let best = null;
	for (const { slug, name } of candidates) {
		let score = 0;
		const nameLower = name.toLowerCase();
		const slugLower = slug.toLowerCase();
		if (filename.includes(slugLower) || filename.includes(nameLower.replace(/\s+/g, "-"))) score += 10;
		score += contentPreview.match(new RegExp(escapeRegExp(nameLower), "g"))?.length ?? 0;
		if (score > 0 && (!best || score > best.score)) best = {
			slug,
			score
		};
	}
	return best ? { slug: best.slug } : null;
}
async function processTranscriptFileAutoMatch(filePath, dataDir) {
	const customersDir = path.join(dataDir, "customers");
	if (!fs.existsSync(customersDir)) {
		await recordUnmatched(dataDir, filePath, "no_customers_defined");
		return;
	}
	const slugs = fs.readdirSync(customersDir).filter((s) => {
		try {
			return fs.statSync(path.join(customersDir, s)).isDirectory();
		} catch {
			return false;
		}
	});
	if (slugs.length === 0) {
		await recordUnmatched(dataDir, filePath, "no_customers_defined");
		return;
	}
	const matchedSlug = await matchCustomer(filePath, fs.readFileSync(filePath, "utf-8"), slugs.map((slug) => ({
		slug,
		name: readCustomerName(customersDir, slug)
	})));
	if (matchedSlug) await processTranscriptFile(filePath, matchedSlug, dataDir);
	else await recordUnmatched(dataDir, filePath, "no_customer_match");
}
/**
* Resolve a transcript to a customer slug. Prefers LLM recognition (when an
* ANTHROPIC_API_KEY is configured) and falls back to the filename/content
* heuristic. The LLM result is only trusted when it names a known candidate
* with at least medium confidence — guarding against hallucinated slugs.
*/
async function matchCustomer(filePath, content, candidates) {
	try {
		const { recognizeCustomer } = await import("./llm-DSX1-wFu.js");
		const llm = await recognizeCustomer(content, candidates);
		if (llm.slug && llm.confidence !== "low" && candidates.some((c) => c.slug === llm.slug)) return llm.slug;
	} catch (err) {
		logger.warn("transcript-watcher", "LLM recognition failed, using heuristic", { error: err.message });
	}
	return fuzzyMatchCustomer(filePath, content, candidates)?.slug ?? null;
}
async function recordUnmatched(dataDir, filePath, reason) {
	const { appendUnmatched } = await import("./unmatched-transcripts-C92zAoM4.js");
	appendUnmatched(dataDir, {
		filePath,
		addedAt: (/* @__PURE__ */ new Date()).toISOString(),
		reason
	});
	logger.info("transcript-watcher", "unmatched transcript", {
		filePath,
		reason
	});
}
//#endregion
export { processTranscriptFile, processTranscriptFileAutoMatch, watchTranscripts };

//# sourceMappingURL=transcript-watcher-BoClrJAz.js.map