import runDbClient_default from "../../../../data/db/runDbClient.js";
import { getLogger as getLogger$1 } from "../../../../logger.js";
import { isTextDocumentMimeType } from "../../utils/text-document-attachments.js";
import { isBlobUri } from "./index.js";
import { addLedgerArtifacts } from "@inkeep/agents-core";

//#region src/domains/run/services/blob-storage/attachment-artifacts.ts
const logger = getLogger$1("attachment-artifacts");
function extractContentHashFromBlobUri(blobUri) {
	return blobUri.match(/sha256-([a-f0-9]{3,64})(?:\.|$)/i)?.[1] ?? null;
}
function getBinaryType(mimeType) {
	return mimeType?.startsWith("image/") ? "image" : "file";
}
function getDefaultAttachmentName(source, index, filename) {
	if (filename) return filename;
	return source === "user-message" ? `User attachment ${index + 1}` : `Tool attachment ${index + 1}`;
}
function buildAttachmentDescription(source, mimeType) {
	const base = source === "user-message" ? "Binary file attached by the user" : "Binary file produced by tool";
	return mimeType ? `${base} (${mimeType})` : base;
}
const MESSAGE_ATTACHMENT_TOOL_CALL_PREFIX = "message_attachment:";
function buildMessageAttachmentToolCallId(messageId) {
	return `${MESSAGE_ATTACHMENT_TOOL_CALL_PREFIX}${messageId}`;
}
async function createAttachmentArtifacts(parts, ctx) {
	const artifacts = [];
	const refs = [];
	let fileIndex = 0;
	for (const part of parts) {
		if (part.kind !== "file") continue;
		const file = part.file;
		if (!("uri" in file) || !file.uri || !isBlobUri(file.uri)) continue;
		const filename = typeof part.metadata?.filename === "string" ? part.metadata.filename : void 0;
		const mimeType = file.mimeType || "application/octet-stream";
		if (isTextDocumentMimeType(mimeType)) continue;
		const binaryType = getBinaryType(mimeType);
		const contentHash = extractContentHashFromBlobUri(file.uri);
		const artifactId = contentHash ? `attachment_${ctx.messageId}_${contentHash}` : `attachment_${ctx.messageId}_${fileIndex + 1}`;
		artifacts.push({
			artifactId,
			type: "binary_attachment",
			name: getDefaultAttachmentName(ctx.source, fileIndex, filename),
			description: buildAttachmentDescription(ctx.source, mimeType),
			parts: [{
				kind: "data",
				data: {
					summary: {
						filename,
						mimeType,
						binaryType,
						source: ctx.source
					},
					full: {
						blobUri: file.uri,
						filename,
						mimeType,
						binaryType,
						source: ctx.source
					}
				}
			}],
			metadata: {
				visibility: "context",
				role: "binary_attachment",
				source: ctx.source
			},
			createdAt: (/* @__PURE__ */ new Date()).toISOString()
		});
		refs.push({
			artifactId,
			toolCallId: ctx.toolCallId,
			blobUri: file.uri
		});
		fileIndex += 1;
	}
	if (artifacts.length === 0) return [];
	await addLedgerArtifacts(runDbClient_default)({
		scopes: {
			tenantId: ctx.tenantId,
			projectId: ctx.projectId
		},
		contextId: ctx.conversationId,
		taskId: ctx.taskId,
		toolCallId: ctx.toolCallId,
		artifacts
	});
	logger.debug({
		conversationId: ctx.conversationId,
		messageId: ctx.messageId,
		taskId: ctx.taskId,
		toolCallId: ctx.toolCallId,
		source: ctx.source,
		artifactCount: artifacts.length
	}, "Created attachment artifacts");
	return refs;
}

//#endregion
export { MESSAGE_ATTACHMENT_TOOL_CALL_PREFIX, buildMessageAttachmentToolCallId, createAttachmentArtifacts };