import { Ai as redactIdentifier, Bs as resolveWhatsAppAccount, Hi as loadConfig, Vs as resolveWhatsAppMediaMaxBytes, gr as generateSecureUuid } from "./model-auth-DvR9nmjM.js";
import { T as createSubsystemLogger, U as getChildLogger, a as escapeRegExp, v as toWhatsappJid } from "./utils-BkOxPe01.js";
import "./paths-Dmn791zP.js";
import "./paths-CjjtVeOA.js";
import { _ as createDedupeCache, d as requireActiveWebListener } from "./dispatch-5HmuWXBR.js";
import "./send-XalDM8sQ.js";
import "./send-R53RJFlR.js";
import "./env-BMuFkZ5k.js";
import "./github-copilot-token-DYNOohx9.js";
import "./send-CFs4fcUA.js";
import "./fetch-guard-CYJpzHWP.js";
import "./deliver-p96fxVjK.js";
import "./diagnostic-CXg9EFRL.js";
import "./pi-model-discovery-LEoCS8UY.js";
import "./audio-transcription-runner-C52tcw2A.js";
import "./image-BCkpZBVi.js";
import "./api-key-rotation-5A6d55d3.js";
import "./local-roots-BhgVWKpf.js";
import "./proxy-fetch-DVwCClqP.js";
import "./tokens-DnfM6GLC.js";
import "./commands-registry-RD8J2kV-.js";
import { a as loadWebMedia, s as resolveMarkdownTableMode } from "./ir-LkYRnMOS.js";
import "./render-Cky8fVYO.js";
import "./channel-activity-D7MNCltt.js";
import "./send-CJI5Sw2v.js";
import "./outbound-attachment-BqCUF302.js";
import "./fetch-B923u9ph.js";
import "./send-2YlHdzYN.js";
import "./sqlite-BObSRUyC.js";
import { t as convertMarkdownTables } from "./tables-CEMi_FCZ.js";
import "./fetch-Dx2GlVfM.js";
import "./skill-commands-DFQ3VKVg.js";
import "./manager-CHngt-qT.js";
import "node:crypto";
//#endregion
//#region src/markdown/whatsapp.ts
/**
* Convert standard Markdown formatting to WhatsApp-compatible markup.
*
* WhatsApp uses its own formatting syntax:
*   bold:          *text*
*   italic:        _text_
*   strikethrough: ~text~
*   monospace:     ```text```
*
* Standard Markdown uses:
*   bold:          **text** or __text__
*   italic:        *text* or _text_
*   strikethrough: ~~text~~
*   code:          `text` (inline) or ```text``` (block)
*
* The conversion preserves fenced code blocks and inline code,
* then converts bold and strikethrough markers.
*/
/** Placeholder tokens used during conversion to protect code spans. */
const FENCE_PLACEHOLDER = "\0FENCE";
const INLINE_CODE_PLACEHOLDER = "\0CODE";
/**
* Convert standard Markdown bold/italic/strikethrough to WhatsApp formatting.
*
* Order of operations matters:
* 1. Protect fenced code blocks (```...```) — already WhatsApp-compatible
* 2. Protect inline code (`...`) — leave as-is
* 3. Convert **bold** → *bold* and __bold__ → *bold*
* 4. Convert ~~strike~~ → ~strike~
* 5. Restore protected spans
*
* Italic *text* and _text_ are left alone since WhatsApp uses _text_ for italic
* and single * is already WhatsApp bold — no conversion needed for single markers.
*/
function markdownToWhatsApp(text) {
	if (!text) return text;
	const fences = [];
	let result = text.replace(/```[\s\S]*?```/g, (match) => {
		fences.push(match);
		return `${FENCE_PLACEHOLDER}${fences.length - 1}`;
	});
	const inlineCodes = [];
	result = result.replace(/`[^`\n]+`/g, (match) => {
		inlineCodes.push(match);
		return `${INLINE_CODE_PLACEHOLDER}${inlineCodes.length - 1}`;
	});
	result = result.replace(/\*\*(.+?)\*\*/g, "*$1*");
	result = result.replace(/__(.+?)__/g, "*$1*");
	result = result.replace(/~~(.+?)~~/g, "~$1~");
	result = result.replace(new RegExp(`${escapeRegExp(INLINE_CODE_PLACEHOLDER)}(\\d+)`, "g"), (_, idx) => inlineCodes[Number(idx)] ?? "");
	result = result.replace(new RegExp(`${escapeRegExp(FENCE_PLACEHOLDER)}(\\d+)`, "g"), (_, idx) => fences[Number(idx)] ?? "");
	return result;
}
//#endregion
//#region src/web/outbound.ts
const outboundLog = createSubsystemLogger("gateway/channels/whatsapp").child("outbound");
async function sendMessageWhatsApp(to, body, options) {
	let text = body;
	const correlationId = generateSecureUuid();
	const startedAt = Date.now();
	const { listener: active, accountId: resolvedAccountId } = requireActiveWebListener(options.accountId);
	const cfg = options.cfg ?? loadConfig();
	const account = resolveWhatsAppAccount({
		cfg,
		accountId: resolvedAccountId ?? options.accountId
	});
	const tableMode = resolveMarkdownTableMode({
		cfg,
		channel: "whatsapp",
		accountId: resolvedAccountId ?? options.accountId
	});
	text = convertMarkdownTables(text ?? "", tableMode);
	text = markdownToWhatsApp(text);
	const redactedTo = redactIdentifier(to);
	const logger = getChildLogger({
		module: "web-outbound",
		correlationId,
		to: redactedTo
	});
	try {
		const jid = toWhatsappJid(to);
		const redactedJid = redactIdentifier(jid);
		let mediaBuffer;
		let mediaType;
		let documentFileName;
		if (options.mediaUrl) {
			const media = await loadWebMedia(options.mediaUrl, {
				maxBytes: resolveWhatsAppMediaMaxBytes(account),
				localRoots: options.mediaLocalRoots
			});
			const caption = text || void 0;
			mediaBuffer = media.buffer;
			mediaType = media.contentType;
			if (media.kind === "audio") mediaType = media.contentType === "audio/ogg" ? "audio/ogg; codecs=opus" : media.contentType ?? "application/octet-stream";
			else if (media.kind === "video") text = caption ?? "";
			else if (media.kind === "image") text = caption ?? "";
			else {
				text = caption ?? "";
				documentFileName = media.fileName;
			}
		}
		outboundLog.info(`Sending message -> ${redactedJid}${options.mediaUrl ? " (media)" : ""}`);
		logger.info({
			jid: redactedJid,
			hasMedia: Boolean(options.mediaUrl)
		}, "sending message");
		await active.sendComposingTo(to);
		const accountId = Boolean(options.accountId?.trim()) ? resolvedAccountId : void 0;
		const sendOptions = options.gifPlayback || accountId || documentFileName ? {
			...options.gifPlayback ? { gifPlayback: true } : {},
			...documentFileName ? { fileName: documentFileName } : {},
			accountId
		} : void 0;
		const messageId = (sendOptions ? await active.sendMessage(to, text, mediaBuffer, mediaType, sendOptions) : await active.sendMessage(to, text, mediaBuffer, mediaType))?.messageId ?? "unknown";
		const durationMs = Date.now() - startedAt;
		outboundLog.info(`Sent message ${messageId} -> ${redactedJid}${options.mediaUrl ? " (media)" : ""} (${durationMs}ms)`);
		logger.info({
			jid: redactedJid,
			messageId
		}, "sent message");
		return {
			messageId,
			toJid: jid
		};
	} catch (err) {
		logger.error({
			err: String(err),
			to: redactedTo,
			hasMedia: Boolean(options.mediaUrl)
		}, "failed to send via web session");
		throw err;
	}
}
//#endregion
//#region src/web/auto-reply/loggers.ts
const whatsappLog = createSubsystemLogger("gateway/channels/whatsapp");
whatsappLog.child("inbound");
whatsappLog.child("outbound");
whatsappLog.child("heartbeat");
createDedupeCache({
	ttlMs: 20 * 6e4,
	maxSize: 5e3
});
//#endregion
export { sendMessageWhatsApp };
