import { n as getSessionBindingService } from "./session-binding-service-XF56z3mS.js";
import "./session-binding-runtime-2CNlTNox.js";
import { a as resolveMatrixAccountConfig } from "./account-config-CGyz2xVg.js";
import { a as extractMatrixReactionAnnotation } from "./reaction-common-BjAtJ4Dp.js";
import { a as unregisterMatrixApprovalReactionTarget, i as resolveMatrixApprovalReactionTargetWithPersistence } from "./approval-reactions-CEZRtsEX.js";
import { i as resolveMatrixThreadRouting, r as resolveMatrixThreadRootId, t as resolveMatrixInboundRoute } from "./route-EHWxgm2B.js";
//#region extensions/matrix/src/matrix/monitor/reaction-events.ts
let approvalReactionAuthPromise;
let execApprovalResolverPromise;
function loadApprovalReactionAuth() {
	approvalReactionAuthPromise ??= import("./approval-reaction-auth-Bo2pT92G.js");
	return approvalReactionAuthPromise;
}
function loadExecApprovalResolver() {
	execApprovalResolverPromise ??= import("./exec-approval-resolver-B5zKGE_V.js");
	return execApprovalResolverPromise;
}
function resolveMatrixReactionNotificationMode(params) {
	const matrixConfig = params.cfg.channels?.matrix;
	return resolveMatrixAccountConfig({
		cfg: params.cfg,
		accountId: params.accountId
	}).reactionNotifications ?? matrixConfig?.reactionNotifications ?? "own";
}
async function maybeResolveMatrixApprovalReaction(params) {
	if (!params.target) return false;
	const approvalKind = params.target.approvalId.startsWith("plugin:") ? "plugin" : "exec";
	const { isMatrixApprovalReactionAuthorizedSender } = await loadApprovalReactionAuth();
	if (!isMatrixApprovalReactionAuthorizedSender({
		...params,
		approvalKind
	})) return false;
	const { isApprovalNotFoundError, resolveMatrixApproval } = await loadExecApprovalResolver();
	try {
		await resolveMatrixApproval({
			cfg: params.cfg,
			approvalId: params.target.approvalId,
			decision: params.target.decision,
			senderId: params.senderId
		});
		params.logVerboseMessage(`matrix: approval reaction resolved id=${params.target.approvalId} sender=${params.senderId} decision=${params.target.decision}`);
		return true;
	} catch (err) {
		if (isApprovalNotFoundError(err)) {
			unregisterMatrixApprovalReactionTarget({
				roomId: params.roomId,
				eventId: params.targetEventId
			});
			params.logVerboseMessage(`matrix: approval reaction ignored for expired approval id=${params.target.approvalId} sender=${params.senderId}`);
			return true;
		}
		params.logVerboseMessage(`matrix: approval reaction failed id=${params.target.approvalId} sender=${params.senderId}: ${String(err)}`);
		return true;
	}
}
async function handleInboundMatrixReaction(params) {
	const reaction = extractMatrixReactionAnnotation(params.event.content);
	if (!reaction?.eventId) return;
	if (params.senderId === params.selfUserId) return;
	const approvalTarget = await resolveMatrixApprovalReactionTargetWithPersistence({
		roomId: params.roomId,
		eventId: reaction.eventId,
		reactionKey: reaction.key
	});
	if (await maybeResolveMatrixApprovalReaction({
		cfg: params.cfg,
		accountId: params.accountId,
		senderId: params.senderId,
		target: approvalTarget,
		targetEventId: reaction.eventId,
		roomId: params.roomId,
		logVerboseMessage: params.logVerboseMessage
	})) return;
	const notificationMode = resolveMatrixReactionNotificationMode({
		cfg: params.cfg,
		accountId: params.accountId
	});
	if (notificationMode === "off") return;
	const targetEvent = await params.client.getEvent(params.roomId, reaction.eventId).catch((err) => {
		params.logVerboseMessage(`matrix: failed resolving reaction target room=${params.roomId} id=${reaction.eventId}: ${String(err)}`);
		return null;
	});
	const targetSender = targetEvent && typeof targetEvent.sender === "string" ? targetEvent.sender.trim() : "";
	if (!targetSender) return;
	if (notificationMode === "own" && targetSender !== params.selfUserId) return;
	const targetContent = targetEvent && targetEvent.content && typeof targetEvent.content === "object" ? targetEvent.content : void 0;
	const threadRootId = targetContent ? resolveMatrixThreadRootId({
		event: targetEvent,
		content: targetContent
	}) : void 0;
	const accountConfig = resolveMatrixAccountConfig({
		cfg: params.cfg,
		accountId: params.accountId
	});
	const thread = resolveMatrixThreadRouting({
		isDirectMessage: params.isDirectMessage,
		threadReplies: accountConfig.threadReplies ?? "inbound",
		dmThreadReplies: accountConfig.dm?.threadReplies,
		messageId: reaction.eventId,
		threadRootId
	});
	const { route, runtimeBindingId } = resolveMatrixInboundRoute({
		cfg: params.cfg,
		accountId: params.accountId,
		roomId: params.roomId,
		senderId: params.senderId,
		isDirectMessage: params.isDirectMessage,
		dmSessionScope: accountConfig.dm?.sessionScope ?? "per-user",
		threadId: thread.threadId,
		eventTs: params.event.origin_server_ts,
		resolveAgentRoute: params.core.channel.routing.resolveAgentRoute
	});
	if (runtimeBindingId) getSessionBindingService().touch(runtimeBindingId, params.event.origin_server_ts);
	const text = `Matrix reaction added: ${reaction.key} by ${params.senderLabel} on msg ${reaction.eventId}`;
	params.core.system.enqueueSystemEvent(text, {
		sessionKey: route.sessionKey,
		contextKey: `matrix:reaction:add:${params.roomId}:${reaction.eventId}:${params.senderId}:${reaction.key}`
	});
	params.logVerboseMessage(`matrix: reaction event enqueued room=${params.roomId} target=${reaction.eventId} sender=${params.senderId} emoji=${reaction.key}`);
}
//#endregion
export { handleInboundMatrixReaction, resolveMatrixReactionNotificationMode };
