import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
import { readAgentMessageContent } from "./agent-message-access.js";
//#region src/agent/memory/summary-generator.ts
init_logger();
const log = createLogger("SummaryGenerator");
const DEFAULT_OPTIONS = {
	maxUserRequests: 10,
	maxToolCalls: 50,
	deduplicateByFile: true,
	includeUsage: true
};
/**
* Categorize tool operation based on tool name
*/
function categorizeToolOperation(toolName) {
	const name = toolName.toLowerCase();
	if ([
		"read",
		"read_file",
		"read_multiple",
		"glob",
		"list_dir",
		"ls",
		"memory_get"
	].some((n) => name.includes(n))) return "read";
	if ([
		"write",
		"write_file",
		"write_multiple",
		"edit",
		"patch",
		"create",
		"mkdir"
	].some((n) => name.includes(n))) return "write";
	if ([
		"grep",
		"search",
		"find",
		"find_files",
		"memory_search",
		"web_search"
	].some((n) => name.includes(n))) return "search";
	if ([
		"bash",
		"shell",
		"exec",
		"run",
		"command"
	].some((n) => name.includes(n))) return "shell";
	return "other";
}
/**
* Extract text content from message
*/
function extractTextContent(content) {
	if (typeof content === "string") return content;
	if (Array.isArray(content)) return content.filter((c) => c.type === "text").map((c) => c.text || "").join("\n");
	return "";
}
/**
* Type guard: Check if message has tool calls (assistant message)
*/
function hasToolCalls(msg) {
	return msg.role === "assistant" && "toolCalls" in msg;
}
/**
* Type guard: Check if message is a tool result
*/
function isToolResult(msg) {
	return msg.role === "toolResult" && "name" in msg;
}
/**
* Deduplicate tool calls by file path (keep last operation per file)
*/
function deduplicateByFilePath(toolCalls) {
	const byFile = /* @__PURE__ */ new Map();
	const otherCalls = [];
	for (const call of toolCalls) if (call.filePath) byFile.set(call.filePath, call);
	else otherCalls.push(call);
	return [...Array.from(byFile.values()), ...otherCalls];
}
/**
* Generate structured summary from messages
*/
function generateStructuredSummary(messages, options = {}) {
	const opts = {
		...DEFAULT_OPTIONS,
		...options
	};
	const summary = {
		userRequests: [],
		toolCalls: [],
		keyDecisions: [],
		filesModified: [],
		totalToolCalls: 0,
		successfulToolCalls: 0,
		failedToolCalls: 0
	};
	let lastAssistantMessage = null;
	for (const msg of messages) {
		if (msg.role === "user") {
			const text = extractTextContent(readAgentMessageContent(msg));
			if (text.trim().length > 20) summary.userRequests.push(text.slice(0, 500));
		}
		if (hasToolCalls(msg)) {
			lastAssistantMessage = msg;
			const toolCalls = msg.toolCalls;
			if (toolCalls && toolCalls.length > 0) {
				summary.totalToolCalls += toolCalls.length;
				for (const call of toolCalls) {
					const toolSummary = {
						toolName: call.name,
						operation: categorizeToolOperation(call.name),
						success: true,
						filePath: String(call.args?.path || call.args?.file_path || call.args?.filePath || ""),
						timestamp: msg.timestamp
					};
					summary.toolCalls.push(toolSummary);
					if (["write", "edit"].includes(toolSummary.operation) && toolSummary.filePath) summary.filesModified.push(toolSummary.filePath);
				}
			}
		}
		if (isToolResult(msg)) {
			const toolMsg = msg;
			const toolName = toolMsg.toolName;
			const toolCall = summary.toolCalls.slice().reverse().find((tc) => tc.toolName === toolName && !tc.timestamp);
			if (toolCall) {
				const resultText = extractTextContent(readAgentMessageContent(toolMsg));
				const isError = resultText.toLowerCase().includes("error") || resultText.toLowerCase().includes("failed") || resultText.startsWith("Error:");
				toolCall.success = !isError;
				toolCall.briefResult = resultText.slice(0, 200);
				if (isError) summary.failedToolCalls++;
				else summary.successfulToolCalls++;
			}
		}
	}
	if (opts.deduplicateByFile) summary.toolCalls = deduplicateByFilePath(summary.toolCalls);
	if (summary.toolCalls.length > opts.maxToolCalls) summary.toolCalls = summary.toolCalls.slice(-opts.maxToolCalls);
	if (summary.userRequests.length > opts.maxUserRequests) summary.userRequests = summary.userRequests.slice(-opts.maxUserRequests);
	summary.filesModified = [...new Set(summary.filesModified)];
	if (lastAssistantMessage) summary.keyDecisions = extractKeyDecisions(lastAssistantMessage);
	log.debug({
		userRequests: summary.userRequests.length,
		toolCalls: summary.toolCalls.length,
		filesModified: summary.filesModified.length,
		totalToolCalls: summary.totalToolCalls,
		successfulToolCalls: summary.successfulToolCalls,
		failedToolCalls: summary.failedToolCalls
	}, "Generated structured summary");
	return summary;
}
/**
* Extract key decisions from assistant message
*/
function extractKeyDecisions(msg) {
	const content = extractTextContent(readAgentMessageContent(msg));
	const decisions = [];
	for (const pattern of [
		/(?:I'll|I will|Let's|We should|Decision:|Decided to|Chose to)\s+(.+?)(?:\.|\n)/gi,
		/(?:Based on|After analyzing|Given that)\s+(.+?)(?:\.|\n)/gi,
		/(?:The best approach|The solution|The answer) is\s+(.+?)(?:\.|\n)/gi
	]) {
		const matches = content.match(pattern);
		if (matches) decisions.push(...matches.slice(0, 5).map((m) => m.trim()));
	}
	return decisions.slice(0, 10);
}
/**
* Format structured summary as text for injection into context
*/
function formatSummaryAsText(summary, includeUsage = true) {
	const lines = [];
	lines.push("[Previous Conversation Summary]");
	if (summary.userRequests.length > 0) {
		lines.push("");
		lines.push("User Requests:");
		for (const req of summary.userRequests.slice(-5)) lines.push(`  - ${req.slice(0, 150)}${req.length > 150 ? "..." : ""}`);
	}
	if (summary.toolCalls.length > 0) {
		lines.push("");
		lines.push("Tool Operations:");
		const byType = /* @__PURE__ */ new Map();
		for (const call of summary.toolCalls) {
			const list = byType.get(call.operation) || [];
			list.push(call);
			byType.set(call.operation, list);
		}
		for (const [type, calls] of byType.entries()) {
			const files = calls.filter((c) => c.filePath).map((c) => c.filePath);
			const successCount = calls.filter((c) => c.success).length;
			lines.push(`  ${type.toUpperCase()}: ${calls.length} operations (${successCount}/${calls.length} successful)`);
			if (files.length > 0) lines.push(`    Files: ${files.slice(0, 10).join(", ")}${files.length > 10 ? "..." : ""}`);
		}
	}
	if (summary.filesModified.length > 0) {
		lines.push("");
		lines.push("Files Modified:");
		for (const file of summary.filesModified.slice(-10)) lines.push(`  - ${file}`);
	}
	if (summary.keyDecisions.length > 0) {
		lines.push("");
		lines.push("Key Decisions:");
		for (const decision of summary.keyDecisions.slice(-5)) lines.push(`  - ${decision}`);
	}
	if (includeUsage) {
		lines.push("");
		lines.push("Statistics:");
		lines.push(`  Total tool calls: ${summary.totalToolCalls}`);
		lines.push(`  Successful: ${summary.successfulToolCalls}`);
		lines.push(`  Failed: ${summary.failedToolCalls}`);
		lines.push(`  Files modified: ${summary.filesModified.length}`);
	}
	return lines.join("\n");
}
/**
* Generate compact summary message for context injection
*/
function createSummaryMessage(summary) {
	return {
		role: "user",
		content: [{
			type: "text",
			text: formatSummaryAsText(summary, true)
		}],
		timestamp: Date.now()
	};
}
//#endregion
export { createSummaryMessage, formatSummaryAsText, generateStructuredSummary };

//# sourceMappingURL=summary-generator.js.map