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

//#region src/integrations/llamaindex.ts
var AmplitudeLlamaIndexHandler = class {
	_ai;
	_userId;
	_sessionId;
	_agentId;
	_env;
	_startTimes = /* @__PURE__ */ new Map();
	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;
	}
	_getContext() {
		const ctx = getActiveContext();
		return {
			userId: this._userId ?? ctx?.userId ?? "unknown",
			sessionId: this._sessionId ?? ctx?.sessionId ?? void 0,
			agentId: this._agentId ?? ctx?.agentId ?? void 0,
			env: this._env ?? ctx?.env ?? void 0,
			traceId: ctx?.traceId ?? void 0
		};
	}
	onLLMStart(eventId) {
		this._startTimes.set(eventId, performance.now());
	}
	onLLMEnd(eventId, response) {
		const startTime = this._startTimes.get(eventId) ?? performance.now();
		this._startTimes.delete(eventId);
		const latencyMs = performance.now() - startTime;
		const ctx = this._getContext();
		const normalized = _normalizeLlamaLlmResponse(response);
		let costUsd;
		if (normalized.model !== "unknown" && normalized.inputTokens != null && normalized.outputTokens != null) try {
			const cost = calculateCost({
				modelName: normalized.model,
				inputTokens: normalized.inputTokens,
				outputTokens: normalized.outputTokens,
				cacheReadInputTokens: normalized.cacheReadTokens,
				cacheCreationInputTokens: normalized.cacheCreationTokens,
				defaultProvider: inferProvider(normalized.model)
			});
			if (cost > 0) costUsd = cost;
		} catch {}
		this._ai.trackAiMessage({
			userId: ctx.userId,
			content: normalized.content,
			sessionId: ctx.sessionId ?? "llamaindex-session",
			model: normalized.model,
			provider: "llamaindex",
			latencyMs,
			traceId: ctx.traceId,
			agentId: ctx.agentId,
			env: ctx.env,
			inputTokens: normalized.inputTokens,
			outputTokens: normalized.outputTokens,
			totalCostUsd: costUsd
		});
	}
	onEmbeddingStart(eventId) {
		this._startTimes.set(eventId, performance.now());
	}
	onEmbeddingEnd(eventId, response) {
		const startTime = this._startTimes.get(eventId) ?? performance.now();
		this._startTimes.delete(eventId);
		const latencyMs = performance.now() - startTime;
		const ctx = this._getContext();
		const normalized = _normalizeLlamaEmbeddingResponse(response);
		this._ai.trackEmbedding({
			userId: ctx.userId,
			model: normalized.model,
			provider: "llamaindex",
			latencyMs,
			sessionId: ctx.sessionId,
			traceId: ctx.traceId,
			agentId: ctx.agentId,
			env: ctx.env,
			inputTokens: normalized.inputTokens,
			dimensions: normalized.dimensions
		});
	}
	onToolStart(eventId) {
		this._startTimes.set(eventId, performance.now());
	}
	onToolEnd(eventId, response) {
		const startTime = this._startTimes.get(eventId) ?? performance.now();
		this._startTimes.delete(eventId);
		const latencyMs = performance.now() - startTime;
		const ctx = this._getContext();
		const normalized = _normalizeLlamaToolResponse(response);
		this._ai.trackToolCall({
			userId: ctx.userId,
			toolName: normalized.toolName,
			latencyMs,
			success: normalized.success,
			sessionId: ctx.sessionId,
			traceId: ctx.traceId,
			agentId: ctx.agentId,
			env: ctx.env,
			output: normalized.output
		});
	}
};
function createAmplitudeLlamaIndexHandler(options) {
	return new AmplitudeLlamaIndexHandler(options);
}
function _normalizeLlamaLlmResponse(response) {
	const resp = response != null && typeof response === "object" ? response : {};
	const message = resp.message;
	const content = (typeof resp.content === "string" ? resp.content : void 0) ?? (typeof message?.content === "string" ? message.content : "") ?? "";
	const usage = resp.usage ?? {};
	const outputTokens = _toNumber(resp.outputTokens ?? usage.output_tokens ?? usage.completion_tokens);
	const promptTokens = _toNumber(usage.prompt_tokens);
	if (promptTokens != null) {
		const details = usage.prompt_tokens_details;
		const cached = _toNumber(details?.cached_tokens) ?? 0;
		return {
			content,
			model: String(resp.model ?? message?.model ?? "unknown"),
			inputTokens: _toNumber(resp.inputTokens) ?? promptTokens,
			outputTokens,
			cacheReadTokens: cached,
			cacheCreationTokens: 0
		};
	}
	const rawInput = _toNumber(usage.input_tokens);
	const cacheRead = _toNumber(usage.cache_read_input_tokens) ?? 0;
	const cacheCreation = _toNumber(usage.cache_creation_input_tokens) ?? 0;
	const totalInput = rawInput != null && (cacheRead > 0 || cacheCreation > 0) ? rawInput + cacheRead + cacheCreation : _toNumber(resp.inputTokens) ?? rawInput;
	return {
		content,
		model: String(resp.model ?? message?.model ?? "unknown"),
		inputTokens: totalInput,
		outputTokens,
		cacheReadTokens: cacheRead,
		cacheCreationTokens: cacheCreation
	};
}
function _normalizeLlamaEmbeddingResponse(response) {
	const resp = response != null && typeof response === "object" ? response : {};
	const usage = resp.usage ?? {};
	return {
		model: String(resp.model ?? "unknown"),
		inputTokens: _toNumber(resp.inputTokens ?? usage.input_tokens),
		dimensions: _toNumber(resp.dimensions ?? resp.vectorSize ?? resp.embedding_dimensions)
	};
}
function _normalizeLlamaToolResponse(response) {
	const resp = response != null && typeof response === "object" ? response : {};
	return {
		toolName: String(resp.toolName ?? resp.name ?? "llamaindex-tool"),
		success: Boolean(resp.success ?? resp.error == null),
		output: resp.output ?? resp.result
	};
}
function _toNumber(value) {
	return typeof value === "number" ? value : void 0;
}

//#endregion
export { AmplitudeLlamaIndexHandler, createAmplitudeLlamaIndexHandler };
//# sourceMappingURL=llamaindex.js.map