import { isToolResultDenied } from "../../utils/tool-result.js";
import { makeMessageContentParts } from "../../services/blob-storage/file-upload.js";
import { buildPersistedMessageContent } from "../../services/blob-storage/file-upload-helpers.js";

//#region src/domains/run/agents/generation/tool-result-for-conversation-history.ts
function filterNonTextToolResultContentForConversationHistory(result) {
	if (!result || typeof result !== "object" || Array.isArray(result)) return result;
	if (!Array.isArray(result.content)) return result;
	const textContent = result.content.filter((item) => item?.type === "text" && "text" in item);
	return {
		...result,
		content: textContent
	};
}
function formatToolResultForConversationHistory(toolName, args, result, toolCallId) {
	const input = args ? JSON.stringify(args, null, 2) : "No input";
	if (isToolResultDenied(result)) return [
		`## Tool: ${toolName} [DENIED BY USER]`,
		"",
		`### TOOL_CALL_ID: ${toolCallId}`,
		"",
		`### Input`,
		input,
		"",
		`### Denial Reason`,
		result.reason ?? "Tool call was denied by the user."
	].join("\n");
	let parsedResult = result;
	if (typeof result === "string") try {
		parsedResult = JSON.parse(result);
	} catch (_e) {}
	const textOnlyResult = filterNonTextToolResultContentForConversationHistory(parsedResult && typeof parsedResult === "object" && !Array.isArray(parsedResult) ? {
		...parsedResult,
		result: parsedResult.result && typeof parsedResult.result === "object" && !Array.isArray(parsedResult.result) ? Object.fromEntries(Object.entries(parsedResult.result).filter(([key]) => key !== "_structureHints")) : parsedResult.result
	} : parsedResult);
	return `## Tool: ${toolName}

### 🔧 TOOL_CALL_ID: ${toolCallId}

### Input
${input}

### Output
${typeof textOnlyResult === "string" ? textOnlyResult : JSON.stringify(textOnlyResult, null, 2)}`;
}
function mapMcpContentItemToConversationHistoryPart(item) {
	if (!item || typeof item !== "object") return null;
	if (item.type === "text") {
		if (typeof item.text === "string") return {
			kind: "text",
			text: item.text
		};
		if (item.text !== void 0) return {
			kind: "text",
			text: JSON.stringify(item.text, null, 2)
		};
		return null;
	}
	if (item.type === "image" && typeof item.data === "string") return {
		kind: "file",
		file: {
			bytes: item.data,
			...typeof item.mimeType === "string" ? { mimeType: item.mimeType } : {}
		},
		metadata: { type: "image" }
	};
	if (item.type === "image" && typeof item.url === "string") return {
		kind: "file",
		file: {
			uri: item.url,
			...typeof item.mimeType === "string" ? { mimeType: item.mimeType } : {}
		},
		metadata: { type: "image" }
	};
	return {
		kind: "data",
		data: item
	};
}
function getToolResultPartsForConversationHistory(result) {
	if (!result || typeof result !== "object" || !Array.isArray(result.content)) return;
	const parts = result.content.map((item) => mapMcpContentItemToConversationHistoryPart(item)).filter((part) => part !== null);
	return parts.length > 0 ? parts : void 0;
}
async function buildToolResultForConversationHistory(ctx, toolName, args, result, toolCallId, conversationId, messageId) {
	const text = formatToolResultForConversationHistory(toolName, args, result, toolCallId);
	const parts = getToolResultPartsForConversationHistory(result);
	if (!parts || parts.length === 0) return { text };
	if (!parts.some((part) => part.kind === "file")) return {
		text,
		parts: makeMessageContentParts(parts)
	};
	return buildPersistedMessageContent(text, parts, {
		tenantId: ctx.config.tenantId,
		projectId: ctx.config.projectId,
		conversationId,
		messageId
	});
}

//#endregion
export { buildToolResultForConversationHistory };