import { getActiveContext } from "../context.js";
import { calculateCost } from "../utils/costs.js";

//#region src/integrations/anthropic-tools.ts
var AmplitudeToolLoop = class {
	_ai;
	_userId;
	_sessionId;
	_agentId;
	_env;
	_maxTurns;
	constructor(options) {
		this._ai = options.amplitudeAI;
		this._userId = options.userId ?? null;
		this._sessionId = options.sessionId ?? null;
		this._agentId = options.agentId ?? null;
		this._env = options.env ?? null;
		this._maxTurns = options.maxTurns ?? 10;
	}
	/**
	* Run a tool loop with the Anthropic API.
	*
	* This method orchestrates multi-turn tool_use conversations,
	* tracking each AI response and tool call along the way.
	*/
	async run(options) {
		const ctx = getActiveContext();
		const userId = this._userId ?? ctx?.userId ?? "unknown";
		const sessionId = this._sessionId ?? ctx?.sessionId ?? "tool-loop-session";
		const agentId = this._agentId ?? ctx?.agentId ?? void 0;
		const env = this._env ?? ctx?.env ?? void 0;
		const messages = [...options.messages];
		const allResponses = [];
		let currentTurnId = 1;
		for (const msg of messages) {
			const userText = _extractUserText(msg);
			if (msg.role === "user" && userText.length > 0) {
				this._ai.trackUserMessage({
					userId,
					content: userText,
					sessionId,
					agentId,
					env,
					turnId: currentTurnId
				});
				currentTurnId += 1;
			}
		}
		for (let turn = 0; turn < this._maxTurns; turn++) {
			const messagesApi = options.client.messages;
			const createFn = messagesApi.create;
			const startTime = performance.now();
			const response = await createFn.call(messagesApi, {
				model: options.model,
				messages,
				tools: options.tools,
				system: options.system
			});
			const latencyMs = performance.now() - startTime;
			allResponses.push(response);
			const content = _normalizeContentBlocks(response.content);
			const responseText = _extractAssistantText(content);
			const toolUseBlocks = content.filter((b) => b.type === "tool_use");
			const usage = response.usage;
			const cacheRead = usage?.cache_read_input_tokens ?? 0;
			const cacheCreation = usage?.cache_creation_input_tokens ?? 0;
			const rawInput = usage?.input_tokens ?? 0;
			const normalizedInput = cacheRead || cacheCreation ? rawInput + cacheRead + cacheCreation : rawInput;
			let costUsd;
			if (usage?.input_tokens != null && usage?.output_tokens != null) try {
				const cost = calculateCost({
					modelName: options.model,
					inputTokens: normalizedInput,
					outputTokens: usage.output_tokens,
					cacheReadInputTokens: cacheRead,
					cacheCreationInputTokens: cacheCreation,
					defaultProvider: "anthropic"
				});
				if (cost > 0) costUsd = cost;
			} catch {}
			this._ai.trackAiMessage({
				userId,
				content: responseText,
				sessionId,
				model: options.model,
				provider: "anthropic",
				latencyMs,
				turnId: currentTurnId,
				agentId,
				env,
				inputTokens: normalizedInput || void 0,
				outputTokens: usage?.output_tokens,
				cacheReadTokens: cacheRead || void 0,
				cacheCreationTokens: cacheCreation || void 0,
				totalCostUsd: costUsd
			});
			currentTurnId += 1;
			if (response.stop_reason !== "tool_use" || toolUseBlocks.length === 0) break;
			messages.push({
				role: "assistant",
				content
			});
			const toolResults = [];
			for (const toolUse of toolUseBlocks) {
				const toolName = String(toolUse.name);
				const toolInput = toolUse.input;
				const toolStartTime = performance.now();
				try {
					const output = await options.toolExecutor(toolName, toolInput);
					const toolLatencyMs = performance.now() - toolStartTime;
					this._ai.trackToolCall({
						userId,
						toolName,
						latencyMs: toolLatencyMs,
						success: true,
						sessionId,
						agentId,
						env,
						input: toolInput,
						output: output == null ? void 0 : String(output)
					});
					toolResults.push({
						type: "tool_result",
						tool_use_id: toolUse.id,
						content: output == null ? "" : String(output)
					});
				} catch (error) {
					const toolLatencyMs = performance.now() - toolStartTime;
					this._ai.trackToolCall({
						userId,
						toolName,
						latencyMs: toolLatencyMs,
						success: false,
						sessionId,
						agentId,
						env,
						input: toolInput,
						errorMessage: error instanceof Error ? error.message : String(error)
					});
					toolResults.push({
						type: "tool_result",
						tool_use_id: toolUse.id,
						content: `Error: ${error instanceof Error ? error.message : String(error)}`,
						is_error: true
					});
				}
			}
			messages.push({
				role: "user",
				content: toolResults
			});
		}
		return allResponses;
	}
};
function _extractUserText(msg) {
	if (typeof msg.content === "string") return msg.content;
	if (!Array.isArray(msg.content)) return "";
	return msg.content.map((block) => {
		if (typeof block === "string") return block;
		const item = block;
		return typeof item.text === "string" ? item.text : "";
	}).join("");
}
function _extractAssistantText(content) {
	if (!Array.isArray(content)) return "";
	return content.filter((b) => b.type === "text").map((b) => String(b.text ?? "")).join("");
}
function _normalizeContentBlocks(value) {
	if (!Array.isArray(value)) return [];
	return value.filter((v) => v != null && typeof v === "object");
}

//#endregion
export { AmplitudeToolLoop };
//# sourceMappingURL=anthropic-tools.js.map