import { c as normalizeOptionalString } from "./string-coerce-DKw2K5wM.js";
import { t as createSubsystemLogger } from "./subsystem-DmpKP7hZ.js";
import { l as buildPluginApprovalResolvedMessage, s as buildPluginApprovalExpiredMessage } from "./plugin-approvals-BAd_Vwt-.js";
import { t as buildChannelApprovalNativeTargetKey } from "./approval-native-target-key-CygHVcC3.js";
import "./runtime-env-BlzZ_kGU.js";
import "./string-coerce-runtime-qOd7_06l.js";
import { c as buildExecApprovalPendingReplyPayload } from "./exec-approval-reply-6AFPZo6b.js";
import { r as createChannelApprovalNativeRuntimeAdapter } from "./approval-handler-runtime-DlJt2uSQ.js";
import "./approval-handler-runtime-50KHaLCb.js";
import "./approval-native-runtime-B6wDYiFb.js";
import { n as buildApprovalResolvedReplyPayload, r as buildPluginApprovalPendingReplyPayload } from "./approval-renderers-DAW7yrG8.js";
import "./approval-reply-runtime-BkuDLvaB.js";
import "./approval-runtime-BleisJsg.js";
import { c as parseIMessageTarget, o as normalizeIMessageHandle } from "./targets-7lgbAW-k.js";
import { c as unregisterIMessageApprovalReactionTarget, n as normalizeIMessageMessagingTarget, o as registerIMessageApprovalReactionTarget, r as addIMessageApprovalReactionHintToText } from "./normalize-DzKnkoZh.js";
import { t as replaceApprovalIdPlaceholder } from "./approval-text-mTq6_6px.js";
import { t as sendMessageIMessage } from "./send-DL6Fu9ZP.js";
//#region extensions/imessage/src/approval-handler.runtime.ts
const log = createSubsystemLogger("imessage/approvals");
function buildPendingPayload(params) {
	const allowedDecisions = params.view.actions.map((action) => action.decision);
	return {
		text: addIMessageApprovalReactionHintToText({
			text: replaceApprovalIdPlaceholder((params.approvalKind === "plugin" ? buildPluginApprovalPendingReplyPayload({
				request: params.request,
				nowMs: params.nowMs,
				allowedDecisions
			}) : buildExecApprovalPendingReplyPayload({
				approvalId: params.request.id,
				approvalSlug: params.request.id.slice(0, 8),
				approvalCommandId: params.request.id,
				warningText: params.view.approvalKind === "exec" ? params.view.warningText ?? void 0 : void 0,
				ask: params.view.approvalKind === "exec" ? params.view.ask ?? null : null,
				agentId: params.view.approvalKind === "exec" ? params.view.agentId ?? null : null,
				sessionKey: params.view.approvalKind === "exec" ? params.view.sessionKey ?? null : null,
				command: params.view.approvalKind === "exec" ? params.view.commandText : "",
				cwd: params.view.approvalKind === "exec" ? params.view.cwd ?? void 0 : void 0,
				host: params.view.approvalKind === "exec" && params.view.host === "node" ? "node" : "gateway",
				nodeId: params.view.approvalKind === "exec" ? params.view.nodeId ?? void 0 : void 0,
				allowedDecisions,
				expiresAtMs: params.request.expiresAtMs,
				nowMs: params.nowMs
			})).text, params.request.id),
			allowedDecisions
		}),
		allowedDecisions
	};
}
function buildResolvedText(params) {
	if (params.view.approvalKind === "plugin") return buildPluginApprovalResolvedMessage(params.resolved);
	const resolvedByText = params.resolved.resolvedBy ? ` Resolved by ${params.resolved.resolvedBy}.` : "";
	return buildApprovalResolvedReplyPayload({
		approvalId: params.request.id,
		approvalSlug: params.request.id.slice(0, 8),
		text: `✅ Exec approval ${params.resolved.decision}.${resolvedByText} ID: ${params.request.id}`
	}).text ?? "";
}
function buildExpiredText(params) {
	if (params.view.approvalKind === "plugin") return buildPluginApprovalExpiredMessage(params.request);
	return `⏱️ Exec approval expired. ID: ${params.request.id}`;
}
function resolvePreparedAccountId(params) {
	return normalizeOptionalString(params.plannedAccountId) ?? normalizeOptionalString(params.contextAccountId);
}
function buildConversationKeyForTarget(to) {
	try {
		const parsed = parseIMessageTarget(to);
		if (parsed.kind === "chat_id") return { chatId: parsed.chatId };
		if (parsed.kind === "chat_guid") return { chatGuid: parsed.chatGuid };
		if (parsed.kind === "chat_identifier") return { chatIdentifier: parsed.chatIdentifier };
		const handle = normalizeIMessageHandle(parsed.to);
		return handle ? { handle } : null;
	} catch {
		return null;
	}
}
const imessageApprovalNativeRuntime = createChannelApprovalNativeRuntimeAdapter({
	eventKinds: ["exec", "plugin"],
	availability: {
		isConfigured: ({ context }) => Boolean(context),
		shouldHandle: ({ context }) => Boolean(context)
	},
	presentation: {
		buildPendingPayload: ({ request, approvalKind, nowMs, view }) => buildPendingPayload({
			request,
			approvalKind,
			nowMs,
			view
		}),
		buildResolvedResult: ({ request, resolved, view }) => ({
			kind: "update",
			payload: { text: buildResolvedText({
				request,
				resolved,
				view
			}) }
		}),
		buildExpiredResult: ({ request, view }) => ({
			kind: "update",
			payload: { text: buildExpiredText({
				request,
				view
			}) }
		})
	},
	transport: {
		prepareTarget: ({ plannedTarget, accountId }) => {
			const to = normalizeIMessageMessagingTarget(plannedTarget.target.to);
			if (!to) return null;
			const prepared = {
				to,
				accountId: resolvePreparedAccountId({
					plannedAccountId: plannedTarget.target.accountId,
					contextAccountId: accountId
				})
			};
			return {
				dedupeKey: `${prepared.accountId ?? ""}:${buildChannelApprovalNativeTargetKey({ to: prepared.to })}`,
				target: prepared
			};
		},
		deliverPending: async ({ cfg, preparedTarget, pendingPayload }) => {
			const guid = (await sendMessageIMessage(preparedTarget.to, pendingPayload.text, {
				config: cfg,
				...preparedTarget.accountId ? { accountId: preparedTarget.accountId } : {}
			})).guid;
			if (!guid) return null;
			const conversation = buildConversationKeyForTarget(preparedTarget.to);
			if (!conversation) return null;
			return {
				...preparedTarget.accountId ? { accountId: preparedTarget.accountId } : {},
				to: preparedTarget.to,
				conversation,
				messageId: guid
			};
		},
		updateEntry: async ({ cfg, entry, payload }) => {
			await sendMessageIMessage(entry.to, payload.text, {
				config: cfg,
				...entry.accountId ? { accountId: entry.accountId } : {},
				replyToId: entry.messageId
			});
		}
	},
	interactions: {
		bindPending: ({ entry, request, view, pendingPayload }) => {
			const accountId = entry.accountId?.trim();
			if (!accountId) {
				log.error(`imessage approvals: refusing to bind reaction target for ${request.id}; missing accountId in prepared entry`);
				return null;
			}
			const ttlMs = view.expiresAtMs - Date.now();
			if (ttlMs <= 0) {
				log.error(`imessage approvals: refusing to bind reaction target for ${request.id}; approval already expired at bind time`);
				return null;
			}
			return registerIMessageApprovalReactionTarget({
				accountId,
				conversation: entry.conversation,
				messageId: entry.messageId,
				approvalId: request.id,
				allowedDecisions: pendingPayload.allowedDecisions,
				ttlMs
			}) ? true : null;
		},
		unbindPending: ({ entry }) => {
			const accountId = entry.accountId?.trim();
			if (!accountId) return;
			unregisterIMessageApprovalReactionTarget({
				accountId,
				conversation: entry.conversation,
				messageId: entry.messageId
			});
		},
		cancelDelivered: ({ entry }) => {
			const accountId = entry.accountId?.trim();
			if (!accountId) return;
			unregisterIMessageApprovalReactionTarget({
				accountId,
				conversation: entry.conversation,
				messageId: entry.messageId
			});
		}
	},
	observe: { onDeliveryError: ({ error, request }) => {
		log.error(`imessage approvals: failed to send request ${request.id}: ${String(error)}`);
	} }
});
//#endregion
export { imessageApprovalNativeRuntime };
