import { createLogger } from "../../../utils/logger/index.js";
import { init_logger } from "../../../utils/logger.js";
import { join, relative } from "path";
import { existsSync, readFileSync } from "fs";
//#region src/agent/prompt/memory/index.ts
init_logger();
const log = createLogger("MemorySearch");
const CURATED_MEMORY_FILENAMES = new Set(["MEMORY.md", "USER.md"]);
function getDailyMemoryPath(baseDir, date) {
	const d = date || /* @__PURE__ */ new Date();
	return join(baseDir, `memory`, `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}.md`);
}
function getLongTermMemoryPath(baseDir) {
	return join(baseDir, "MEMORY.md");
}
function getCuratedMemoryPaths(memoriesDir) {
	if (!memoriesDir) return [];
	return [join(memoriesDir, "MEMORY.md"), join(memoriesDir, "USER.md")].filter((p) => existsSync(p));
}
function getAllMemoryPaths(baseDir, memoriesDir) {
	const paths = [];
	paths.push(...getCuratedMemoryPaths(memoriesDir));
	const longTermPath = getLongTermMemoryPath(baseDir);
	if (existsSync(longTermPath)) paths.push(longTermPath);
	if (existsSync(join(baseDir, "memory"))) {
		const today = /* @__PURE__ */ new Date();
		for (let i = 0; i < 30; i++) {
			const date = new Date(today);
			date.setDate(date.getDate() - i);
			const path = getDailyMemoryPath(baseDir, date);
			if (existsSync(path)) paths.push(path);
		}
	}
	return paths;
}
function parseMemoryFile(path) {
	return {
		path,
		content: readFileSync(path, "utf-8"),
		modified: (existsSync(path) ? { mtime: /* @__PURE__ */ new Date() } : { mtime: /* @__PURE__ */ new Date() }).mtime
	};
}
function fuzzyMatch(query, text) {
	const queryLower = query.toLowerCase();
	const textLower = text.toLowerCase();
	if (textLower.includes(queryLower)) return 1;
	const queryWords = queryLower.split(/\s+/);
	const textWords = textLower.split(/\s+/);
	let matchedWords = 0;
	for (const qWord of queryWords) if (textWords.some((tWord) => tWord.includes(qWord) || qWord.includes(tWord))) matchedWords++;
	return matchedWords / queryWords.length;
}
function searchInContent(query, content, options = {}) {
	const { maxResults = 5, minScore = .3 } = options;
	const lines = content.split("\n");
	const matches = [];
	for (let i = 0; i < lines.length; i++) {
		const score = fuzzyMatch(query, lines[i]);
		if (score >= minScore) matches.push({
			line: lines[i],
			index: i,
			score
		});
	}
	matches.sort((a, b) => b.score - a.score);
	if (matches.length === 0) return null;
	const topMatches = matches.slice(0, maxResults);
	const lineNumbers = topMatches.map((m) => m.index + 1);
	return {
		file: "",
		lines: topMatches.map((m) => m.line).join("\n"),
		score: topMatches[0].score,
		lineNumbers
	};
}
async function memorySearch(baseDir, query, options = {}) {
	const { maxResults = 5, minScore = .3, memoriesDir } = options;
	const paths = getAllMemoryPaths(baseDir, memoriesDir);
	const results = [];
	for (const path of paths) try {
		const match = searchInContent(query, parseMemoryFile(path).content, options);
		if (match) {
			match.file = relative(baseDir, path);
			if (match.score >= minScore) results.push(match);
		}
	} catch {
		log.warn({ path }, "Could not read memory file");
	}
	results.sort((a, b) => b.score - a.score);
	return results.slice(0, maxResults * 3);
}
function memoryGet(baseDir, path, from, lines, memoriesDir) {
	let fullPath = path.startsWith("/") ? path : join(baseDir, path);
	if (!existsSync(fullPath) && memoriesDir) {
		const filename = path.split(/[/\\]/).pop() ?? path;
		if (CURATED_MEMORY_FILENAMES.has(filename)) {
			const candidatePath = join(memoriesDir, filename);
			if (existsSync(candidatePath)) fullPath = candidatePath;
		}
	}
	if (!existsSync(fullPath)) return null;
	const allLines = readFileSync(fullPath, "utf-8").split("\n");
	const start = from || 1;
	const end = Math.min(start + (lines || 10) - 1, allLines.length);
	return {
		content: allLines.slice(start - 1, end).join("\n"),
		lineNumbers: {
			start,
			end
		}
	};
}
//#endregion
export { memoryGet, memorySearch };

//# sourceMappingURL=index.js.map