import { createLogger } from "../../utils/logger/index.js";
import { init_logger } from "../../utils/logger.js";
//#region src/agent/tools/usage-analyzer.ts
init_logger();
const log = createLogger("ToolUsageAnalyzer");
const DEFAULT_CONFIG = {
	enabled: true,
	lowUsageThreshold: 5,
	veryLowUsageThreshold: 1,
	minCallsForAnalysis: 100,
	reportIntervalMs: 3600 * 1e3
};
var ToolUsageAnalyzer = class {
	stats = /* @__PURE__ */ new Map();
	config;
	totalCalls = 0;
	lastReportTime = 0;
	constructor(config = {}) {
		this.config = {
			...DEFAULT_CONFIG,
			...config
		};
	}
	/**
	* Record a tool usage event
	*/
	recordUsage(toolName, success, durationMs) {
		if (!this.config.enabled) return;
		const now = Date.now();
		let toolStats = this.stats.get(toolName);
		if (!toolStats) {
			toolStats = {
				toolName,
				calls: 0,
				successes: 0,
				failures: 0,
				avgDurationMs: 0,
				lastUsedTimestamp: 0,
				successRate: 0
			};
			this.stats.set(toolName, toolStats);
		}
		toolStats.calls++;
		toolStats.lastUsedTimestamp = now;
		if (success) toolStats.successes++;
		else toolStats.failures++;
		toolStats.avgDurationMs = (toolStats.avgDurationMs * (toolStats.calls - 1) + durationMs) / toolStats.calls;
		toolStats.successRate = toolStats.successes / toolStats.calls * 100;
		this.totalCalls++;
		if (now - this.lastReportTime > this.config.reportIntervalMs) {
			this.generateReport();
			this.lastReportTime = now;
		}
	}
	/**
	* Get usage stats for a specific tool
	*/
	getToolStats(toolName) {
		return this.stats.get(toolName);
	}
	/**
	* Get all tool usage stats
	*/
	getAllStats() {
		return new Map(this.stats);
	}
	/**
	* Get tools with low usage (below threshold)
	*/
	getLowUsageTools(threshold) {
		const thresholdPercent = threshold ?? this.config.lowUsageThreshold;
		const lowUsageTools = [];
		for (const [name, stats] of this.stats.entries()) if (stats.calls / this.totalCalls * 100 < thresholdPercent && stats.calls >= this.config.minCallsForAnalysis) lowUsageTools.push(name);
		return lowUsageTools;
	}
	/**
	* Get tools with low success rate
	*/
	getLowSuccessTools(threshold) {
		const thresholdPercent = threshold ?? 50;
		const lowSuccessTools = [];
		for (const [name, stats] of this.stats.entries()) if (stats.successRate < thresholdPercent && stats.calls >= this.config.minCallsForAnalysis) lowSuccessTools.push(name);
		return lowSuccessTools;
	}
	/**
	* Get recommendations for tool optimization
	*/
	getRecommendations() {
		const recommendations = {
			keep: [],
			review: [],
			remove: []
		};
		if (this.totalCalls < this.config.minCallsForAnalysis) {
			log.warn({ totalCalls: this.totalCalls }, "Not enough data for recommendations");
			return recommendations;
		}
		for (const [name, stats] of this.stats.entries()) {
			const usagePercent = stats.calls / this.totalCalls * 100;
			if (usagePercent >= this.config.lowUsageThreshold && stats.successRate >= 80) recommendations.keep.push(name);
			else if (usagePercent < this.config.veryLowUsageThreshold) recommendations.remove.push(name);
			else if (usagePercent < this.config.lowUsageThreshold || stats.successRate < 80) recommendations.review.push(name);
			else recommendations.keep.push(name);
		}
		return recommendations;
	}
	/**
	* Generate and log usage report
	*/
	generateReport() {
		if (!this.config.enabled) return;
		const report = {
			totalCalls: this.totalCalls,
			uniqueTools: this.stats.size,
			topTools: this.getTopTools(5),
			lowUsageTools: this.getLowUsageTools(),
			lowSuccessTools: this.getLowSuccessTools(),
			recommendations: this.getRecommendations()
		};
		log.info(report, "Tool Usage Report");
	}
	/**
	* Get top N most used tools
	*/
	getTopTools(n) {
		return Array.from(this.stats.values()).sort((a, b) => b.calls - a.calls).slice(0, n);
	}
	/**
	* Get usage summary as text
	*/
	getSummaryText() {
		const lines = [
			"Tool Usage Summary",
			`==================`,
			`Total Calls: ${this.totalCalls}`,
			`Unique Tools: ${this.stats.size}`,
			"",
			"Top Tools:"
		];
		const topTools = this.getTopTools(5);
		for (const tool of topTools) lines.push(`  - ${tool.toolName}: ${tool.calls} calls (${tool.successRate.toFixed(1)}% success)`);
		const recommendations = this.getRecommendations();
		if (recommendations.remove.length > 0) {
			lines.push("");
			lines.push("Consider Removing:");
			for (const tool of recommendations.remove) lines.push(`  - ${tool}`);
		}
		if (recommendations.review.length > 0) {
			lines.push("");
			lines.push("Review Needed:");
			for (const tool of recommendations.review) lines.push(`  - ${tool}`);
		}
		return lines.join("\n");
	}
	/**
	* Reset all stats
	*/
	reset() {
		this.stats.clear();
		this.totalCalls = 0;
		this.lastReportTime = 0;
		log.info("Tool usage stats reset");
	}
	/**
	* Export stats as JSON
	*/
	exportStats() {
		return JSON.stringify({
			totalCalls: this.totalCalls,
			generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
			tools: Array.from(this.stats.values()),
			recommendations: this.getRecommendations()
		}, null, 2);
	}
	/**
	* Get config
	*/
	getConfig() {
		return { ...this.config };
	}
	/**
	* Update config
	*/
	setConfig(config) {
		this.config = {
			...this.config,
			...config
		};
	}
};
//#endregion
export { ToolUsageAnalyzer };

//# sourceMappingURL=usage-analyzer.js.map