import { isToolResultDenied } from "../../utils/tool-result.js";

//#region src/domains/run/agents/generation/tool-result-for-model-input.ts
const MAX_TOOL_RESULT_TEXT_PART_CHARS = 1e5;
function truncateToolResultTextForModelInput(text) {
	if (text.length <= MAX_TOOL_RESULT_TEXT_PART_CHARS) return text;
	return `${text.slice(0, MAX_TOOL_RESULT_TEXT_PART_CHARS)}\n…[truncated]`;
}
function safeSerializeToolResultValueForModelInput(value) {
	try {
		return truncateToolResultTextForModelInput(JSON.stringify(value));
	} catch {
		return "[unserializable tool result value]";
	}
}
function mapMcpContentItemToModelInputPart(item) {
	if (!item || typeof item !== "object") return null;
	const contentItem = item;
	const type = contentItem.type;
	if (type === "text") {
		if (typeof contentItem.text === "string") return {
			type: "text",
			text: contentItem.text
		};
		if (contentItem.text !== void 0) return {
			type: "text",
			text: safeSerializeToolResultValueForModelInput(contentItem.text)
		};
		return null;
	}
	if (type === "image") {
		if (typeof contentItem.data === "string" && contentItem.data.trim() !== "") return {
			type: "image-data",
			data: contentItem.data,
			mediaType: typeof contentItem.mimeType === "string" && contentItem.mimeType.trim() !== "" ? contentItem.mimeType : "image/*"
		};
		if (typeof contentItem.url === "string" && contentItem.url.trim() !== "") return {
			type: "image-url",
			url: contentItem.url
		};
		return null;
	}
	return {
		type: "text",
		text: safeSerializeToolResultValueForModelInput(contentItem)
	};
}
function buildToolResultForModelInput(output) {
	if (isToolResultDenied(output)) return {
		type: "execution-denied",
		reason: output.reason
	};
	if (!output || typeof output !== "object") return {
		type: "json",
		value: output
	};
	const outputRecord = output;
	const content = outputRecord.content;
	if (!Array.isArray(content)) return {
		type: "json",
		value: output
	};
	const mappedContent = content.map((item) => mapMcpContentItemToModelInputPart(item)).filter((item) => item !== null);
	if (mappedContent.length === 0) return {
		type: "json",
		value: output
	};
	const meta = {};
	if ("_toolCallId" in outputRecord) meta._toolCallId = outputRecord._toolCallId;
	if ("_structureHints" in outputRecord) meta._structureHints = outputRecord._structureHints;
	const metaPart = Object.keys(meta).length > 0 ? {
		type: "text",
		text: safeSerializeToolResultValueForModelInput(meta)
	} : null;
	return {
		type: "content",
		value: metaPart ? [metaPart, ...mappedContent] : mappedContent
	};
}

//#endregion
export { buildToolResultForModelInput };