import { isBlobUri } from "./index.js";

//#region src/domains/run/services/blob-storage/artifact-binary-sanitizer.ts
const CIRCULAR_REFERENCE_PLACEHOLDER = "[Circular Reference]";
function isInlineBinaryPart(value) {
	if (typeof value !== "object" || value === null) return false;
	const v = value;
	return (v.type === "image" || v.type === "file") && typeof v.data === "string" && !isBlobUri(v.data) && !v.data.startsWith("http");
}
function stripBinaryDataForObservability(value) {
	const inStack = /* @__PURE__ */ new WeakSet();
	const visit = (current) => {
		if (isInlineBinaryPart(current)) {
			const part = current;
			const approxBytes = Math.round(part.data.length * .75);
			return {
				...part,
				data: `[binary data ~${approxBytes} bytes, mimeType: ${part.mimeType ?? "unknown"}]`
			};
		}
		if (Array.isArray(current)) {
			if (inStack.has(current)) return CIRCULAR_REFERENCE_PLACEHOLDER;
			inStack.add(current);
			try {
				return current.map(visit);
			} finally {
				inStack.delete(current);
			}
		}
		if (current !== null && typeof current === "object") {
			if (inStack.has(current)) return CIRCULAR_REFERENCE_PLACEHOLDER;
			inStack.add(current);
			try {
				const result = {};
				for (const [k, v] of Object.entries(current)) result[k] = visit(v);
				return result;
			} finally {
				inStack.delete(current);
			}
		}
		return current;
	};
	return visit(value);
}

//#endregion
export { stripBinaryDataForObservability };