import { calculateBreakdownTotal, estimateTokens } from "../../utils/token-estimator.js";
import { createDefaultConversationHistoryConfig, getConversationHistoryWithCompression } from "../../data/conversations.js";
import { getPrimaryModel, getSummarizerModel } from "./model-config.js";

//#region src/domains/run/agents/generation/conversation-history.ts
async function buildConversationHistory(ctx, contextId, taskId, userMessage, streamRequestId, initialContextBreakdown) {
	let conversationHistory = "";
	const historyConfig = ctx.config.conversationHistoryConfig ?? createDefaultConversationHistoryConfig();
	if (historyConfig && historyConfig.mode !== "none") {
		if (historyConfig.mode === "full") {
			const filters = {
				delegationId: ctx.delegationId,
				isDelegated: ctx.isDelegatedAgent
			};
			conversationHistory = await getConversationHistoryWithCompression({
				tenantId: ctx.config.tenantId,
				projectId: ctx.config.projectId,
				conversationId: contextId,
				currentMessage: userMessage,
				options: historyConfig,
				filters,
				summarizerModel: getSummarizerModel(ctx.config),
				baseModel: getPrimaryModel(ctx.config),
				streamRequestId,
				fullContextSize: initialContextBreakdown.total
			});
		} else if (historyConfig.mode === "scoped") conversationHistory = await getConversationHistoryWithCompression({
			tenantId: ctx.config.tenantId,
			projectId: ctx.config.projectId,
			conversationId: contextId,
			currentMessage: userMessage,
			options: historyConfig,
			filters: {
				subAgentId: ctx.config.id,
				taskId,
				delegationId: ctx.delegationId,
				isDelegated: ctx.isDelegatedAgent
			},
			summarizerModel: getSummarizerModel(ctx.config),
			baseModel: getPrimaryModel(ctx.config),
			streamRequestId,
			fullContextSize: initialContextBreakdown.total
		});
	}
	const conversationHistoryTokens = estimateTokens(conversationHistory);
	const updatedContextBreakdown = {
		components: {
			...initialContextBreakdown.components,
			conversationHistory: conversationHistoryTokens
		},
		total: initialContextBreakdown.total
	};
	calculateBreakdownTotal(updatedContextBreakdown);
	return {
		conversationHistory,
		contextBreakdown: updatedContextBreakdown
	};
}
function buildInitialMessages(systemPrompt, conversationHistory, userMessage, imageParts) {
	const messages = [];
	messages.push({
		role: "system",
		content: systemPrompt
	});
	if (conversationHistory.trim() !== "") messages.push({
		role: "user",
		content: conversationHistory
	});
	const userContent = buildUserMessageContent(userMessage, imageParts);
	messages.push({
		role: "user",
		content: userContent
	});
	return messages;
}
function buildUserMessageContent(text, imageParts) {
	if (!imageParts || imageParts.length === 0) return text;
	const content = [{
		type: "text",
		text
	}];
	for (const part of imageParts) {
		const file = part.file;
		const imagePart = {
			type: "image",
			image: "uri" in file && file.uri ? new URL(file.uri) : `data:${file.mimeType || "image/*"};base64,${file.bytes}`,
			...part.metadata?.detail && { experimental_providerMetadata: { openai: { imageDetail: part.metadata.detail } } }
		};
		content.push(imagePart);
	}
	return content;
}

//#endregion
export { buildConversationHistory, buildInitialMessages, buildUserMessageContent };