import { env } from "../../../../env.js";
import { getLogger } from "../../../../logger.js";
import { fromBlobUri, isBlobUri } from "./index.js";
import { parseMediaStorageKey } from "./storage-keys.js";

//#region src/domains/run/services/blob-storage/resolve-blob-uris.ts
const logger = getLogger("resolve-blob-uris");
function resolveMessageBlobUris(content, baseUrl) {
	if (!content.parts || content.parts.length === 0) return content;
	const apiBaseUrl = baseUrl || env.INKEEP_AGENTS_API_URL;
	const resolvedParts = content.parts.flatMap((part) => {
		if (part.kind === "file" && typeof part.data === "string" && isBlobUri(part.data)) {
			const key = fromBlobUri(part.data);
			const parsed = parseMediaStorageKey(key);
			if (parsed) {
				const proxyUrl = `${apiBaseUrl}/manage/tenants/${parsed.tenantId}/projects/${parsed.projectId}/conversations/${parsed.conversationId}/media/${encodeURIComponent(parsed.tail)}`;
				return [{
					...part,
					data: proxyUrl
				}];
			}
			logger.warn({ key }, "Malformed blob storage key, filtering part out");
			return [];
		}
		return [part];
	});
	return {
		...content,
		parts: resolvedParts
	};
}
function resolveMessagesListBlobUris(messages, baseUrl) {
	return messages.map((msg) => ({
		...msg,
		content: resolveMessageBlobUris(msg.content, baseUrl)
	}));
}

//#endregion
export { resolveMessageBlobUris, resolveMessagesListBlobUris };