import { createLogger } from "../../../src/utils/logger/index.js";
import { init_logger } from "../../../src/utils/logger.js";
import { init_session_key, parseSessionKey } from "../../../src/routing/session-key.js";
//#region extensions/telegram/src/workflow-progress.ts
init_session_key();
init_logger();
const log = createLogger("TelegramWorkflowProgress");
/** Telegram bot API: 4096 char hard cap; leave 96 chars of headroom for re-renders. */
const TELEGRAM_TEXT_MAX = 4e3;
/** Telegram bot edit rate ≈ 1/s per chat; broker default 5 s leaves ample headroom. */
const DEFAULT_THROTTLE_MS = 5e3;
function createTelegramWorkflowProgressCapability(accountManager) {
	return {
		channelId: "telegram",
		supportsEdit: true,
		defaultThrottleMs: DEFAULT_THROTTLE_MS,
		defaultMode: "edit",
		async postProgress(input) {
			const target = resolveTarget(input.sessionKey);
			if (!target) throw new Error(`telegram workflow progress: cannot route sessionKey "${input.sessionKey}"`);
			const bot = accountManager.getBot(target.accountId);
			if (!bot) throw new Error(`telegram workflow progress: no bot for accountId "${target.accountId}" (sessionKey "${input.sessionKey}")`);
			const text = clampForTelegram(input.text);
			if (input.previousMessageId && !input.isFinal) try {
				await bot.api.editMessageText(target.chatId, Number(input.previousMessageId), text);
				return { messageId: input.previousMessageId };
			} catch (err) {
				if (isMessageNotModified(err)) return { messageId: input.previousMessageId };
				if (isEditTargetGone(err)) log.debug({
					sessionKey: input.sessionKey,
					previousMessageId: input.previousMessageId
				}, "edit target gone; falling back to sendMessage");
				else throw err;
			}
			const sent = await bot.api.sendMessage(target.chatId, text, {
				message_thread_id: target.threadId ? Number(target.threadId) : void 0,
				disable_notification: !input.isFinal
			});
			return { messageId: String(sent.message_id) };
		}
	};
}
function resolveTarget(sessionKey) {
	const parsed = parseSessionKey(sessionKey);
	if (!parsed) return null;
	if (parsed.source !== "telegram") return null;
	if (!parsed.peerId) return null;
	return {
		accountId: parsed.accountId,
		chatId: parsed.peerId,
		threadId: parsed.threadId
	};
}
function clampForTelegram(text) {
	if (text.length <= TELEGRAM_TEXT_MAX) return text;
	return `${text.slice(0, TELEGRAM_TEXT_MAX - 1)}…`;
}
function isMessageNotModified(err) {
	return errorMessage(err).toLowerCase().includes("message is not modified");
}
function isEditTargetGone(err) {
	const msg = errorMessage(err).toLowerCase();
	return msg.includes("message to edit not found") || msg.includes("message can't be edited") || msg.includes("chat not found");
}
function errorMessage(err) {
	if (!err) return "";
	if (err instanceof Error) return err.message;
	return String(err);
}
//#endregion
export { createTelegramWorkflowProgressCapability };

//# sourceMappingURL=workflow-progress.js.map