import { createInboundDebouncer, hasControlCommand } from "../../../../../src/infra/debounce.js";
//#region extensions/feishu/src/transport/reliability/inbound-pipeline.ts
function mergeTextInbound(items) {
	const last = items[items.length - 1];
	const mergedContent = items.map((i) => (i.inbound.content ?? "").trim()).filter(Boolean).join("\n\n");
	const lastMeta = { ...last.inbound.metadata ?? {} };
	const ids = items.map((i) => i.inbound.metadata?.messageId).filter((x) => typeof x === "string" && x.trim().length > 0);
	return {
		...last.inbound,
		content: mergedContent,
		metadata: {
			...lastMeta,
			messageId: lastMeta.messageId,
			feishuMergedCount: items.length,
			...ids.length > 0 ? { feishuMergedMessageIds: ids } : {}
		}
	};
}
function worksToInboundMessages(items) {
	if (items.length === 0) return [];
	const first = items[0];
	if (first.kind !== "text") return items.map((i) => i.inbound);
	if (items.length === 1) return [first.inbound];
	return [mergeTextInbound(items)];
}
function createFeishuInboundPipeline(options) {
	const { bus, defaultDebounceMs, onError } = options;
	const debouncer = createInboundDebouncer({
		debounceMs: defaultDebounceMs,
		buildKey: (item) => `${item.accountId}:${item.chatId}`,
		shouldDebounce: (item) => item.kind === "text" && item.debounceMs > 0 && !hasControlCommand(item.inbound.content ?? ""),
		resolveDebounceMs: (item) => item.kind === "text" ? item.debounceMs : 0,
		onFlush: async (items) => {
			const messages = worksToInboundMessages(items);
			for (const msg of messages) await bus.publishInbound(msg);
		},
		onError
	});
	return {
		async enqueue(work) {
			await debouncer.enqueue(work);
		},
		flushAll: () => debouncer.flushAll(),
		flushKey: (accountId, chatId) => debouncer.flushKey(`${accountId}:${chatId}`)
	};
}
//#endregion
export { createFeishuInboundPipeline };

//# sourceMappingURL=inbound-pipeline.js.map