import { env } from "../../../../env.js";
import { getLogger } from "../../../../logger.js";
import { fromBlobUri, getBlobStorageProvider, 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");
async function resolveMessageBlobUris(content, baseUrl, provider) {
	if (!content.parts || content.parts.length === 0) return content;
	const resolvedProvider = provider ?? getBlobStorageProvider();
	const apiBaseUrl = baseUrl || env.INKEEP_AGENTS_API_URL;
	const resolvedParts = await Promise.all(content.parts.map(async (part) => {
		if (part.kind === "file" && typeof part.data === "string" && isBlobUri(part.data)) {
			const key = fromBlobUri(part.data);
			if (resolvedProvider.getPresignedUrl) try {
				const presignedUrl = await resolvedProvider.getPresignedUrl(key);
				return {
					...part,
					data: presignedUrl
				};
			} catch (error) {
				logger.warn({
					key,
					error
				}, "Presigned URL generation failed, falling back to proxy URL");
			}
			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 null;
		}
		return part;
	}));
	return {
		...content,
		parts: resolvedParts.filter((p) => p !== null)
	};
}
async function resolveMessagesListBlobUris(messages, baseUrl) {
	const provider = getBlobStorageProvider();
	return Promise.all(messages.map(async (msg) => ({
		...msg,
		content: await resolveMessageBlobUris(msg.content, baseUrl, provider)
	})));
}

//#endregion
export { resolveMessageBlobUris, resolveMessagesListBlobUris };