const require_message_coercion = require("../message-coercion.cjs");
const require_messages = require("../../client/stream/messages.cjs");
const require_namespace = require("../namespace.cjs");
const require_assembled_to_message = require("../assembled-to-message.cjs");
const require_message_reconciliation = require("../message-reconciliation.cjs");
const require_runtime = require("./runtime.cjs");
//#region src/stream/projections/messages.ts
function messagesProjection(namespace) {
	const ns = [...namespace];
	return {
		key: `messages|${require_namespace.namespaceKey(ns)}`,
		namespace: ns,
		initial: [],
		open({ thread, store, rootBus }) {
			const assembler = new require_messages.MessageAssembler();
			const roleByKey = /* @__PURE__ */ new Map();
			const indexById = /* @__PURE__ */ new Map();
			const streamMessageIds = /* @__PURE__ */ new Set();
			let valuesMessageIds = /* @__PURE__ */ new Set();
			if (require_namespace.isRootNamespace(ns) && rootBus.channels.includes("messages")) {
				const unsubscribe = rootBus.subscribe((event) => {
					if (event.method !== "messages") return;
					if (!require_namespace.isRootNamespace(event.params.namespace)) return;
					applyEvent(event);
				});
				return { dispose() {
					unsubscribe();
				} };
			}
			let disposed = false;
			const pendingMessages = [];
			let dirty = false;
			let flushScheduled = false;
			const flushChannel = typeof MessageChannel !== "undefined" ? new MessageChannel() : null;
			const flush = () => {
				flushScheduled = false;
				if (!dirty || disposed) return;
				dirty = false;
				store.setValue(pendingMessages.slice());
			};
			if (flushChannel != null) flushChannel.port1.onmessage = flush;
			const scheduleFlush = () => {
				dirty = true;
				if (flushScheduled) return;
				flushScheduled = true;
				if (flushChannel != null) flushChannel.port2.postMessage(null);
				else setTimeout(flush, 0);
			};
			const applyValuesEvent = (event) => {
				const data = event.params.data;
				if (data == null || typeof data !== "object" || Array.isArray(data)) return;
				const rawMessages = data.messages;
				if (!Array.isArray(rawMessages) || rawMessages.length === 0) return;
				const reconciliation = require_message_reconciliation.reconcileMessagesFromValues({
					valueMessages: require_message_coercion.ensureMessageInstances(rawMessages),
					currentMessages: pendingMessages,
					currentIndexById: indexById,
					previousValueMessageIds: valuesMessageIds,
					streamedMessageIds: streamMessageIds,
					preferValuesMessage: require_message_reconciliation.shouldPreferValuesMessageForToolCalls
				});
				valuesMessageIds = reconciliation.valueMessageIds;
				const reconciledMessages = [...reconciliation.messages];
				pendingMessages.length = 0;
				for (const message of reconciledMessages) pendingMessages.push(message);
				indexById.clear();
				for (const [id, idx] of require_message_reconciliation.buildMessageIndex(pendingMessages)) indexById.set(id, idx);
				scheduleFlush();
			};
			const applyEvent = (event) => {
				const data = event.params.data;
				if (data.event === "message-start") {
					const startData = data;
					const role = startData.role ?? "ai";
					const extendedRole = startData.role ?? role;
					const maybeToolCallId = startData.tool_call_id;
					if (startData.id != null) roleByKey.set(startData.id, {
						role: extendedRole,
						toolCallId: maybeToolCallId
					});
				}
				const update = assembler.consume(event);
				if (update == null) return;
				const msg = update.message;
				const id = msg.id;
				if (id == null) return;
				const captured = roleByKey.get(id) ?? { role: "ai" };
				const base = require_assembled_to_message.assembledMessageToBaseMessage(msg, captured.role, { toolCallId: captured.toolCallId });
				streamMessageIds.add(id);
				const existingIdx = indexById.get(id);
				if (existingIdx == null) {
					indexById.set(id, pendingMessages.length);
					pendingMessages.push(base);
				} else pendingMessages[existingIdx] = base;
				scheduleFlush();
			};
			let runtime;
			const openSubscription = () => {
				runtime = require_runtime.openProjectionSubscription({
					thread,
					channels: ["messages", "values"],
					namespace: ns,
					onEvent(event) {
						if (event.method === "messages") applyEvent(event);
						else if (event.method === "values") applyValuesEvent(event);
					}
				});
			};
			(async () => {
				if (!(await rootBus.trySeedFromHistory?.({
					kind: "messages",
					namespace: ns,
					store
				}) === true) && !disposed) openSubscription();
			})();
			return { async dispose() {
				disposed = true;
				if (flushChannel != null) {
					flushChannel.port1.onmessage = null;
					flushChannel.port1.close();
					flushChannel.port2.close();
				}
				await runtime?.dispose();
			} };
		}
	};
}
//#endregion
exports.messagesProjection = messagesProjection;

//# sourceMappingURL=messages.cjs.map