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";
import { resolveFeishuAccount } from "./state/accounts.js";
import { createFeishuClient } from "./transport/client/client.js";
import { editMessageFeishu } from "./outbound/actions.js";
//#region extensions/feishu/src/workflow-progress.ts
init_session_key();
init_logger();
const log = createLogger("FeishuWorkflowProgress");
const FEISHU_TEXT_MAX = 4e3;
const DEFAULT_THROTTLE_MS = 5e3;
function createFeishuWorkflowProgressCapability(opts) {
	return {
		channelId: "feishu",
		supportsEdit: true,
		defaultThrottleMs: DEFAULT_THROTTLE_MS,
		defaultMode: "edit",
		async postProgress(input) {
			const cfg = opts.getConfig();
			if (!cfg) throw new Error("feishu workflow progress: no config loaded");
			const target = resolveTarget(input.sessionKey);
			if (!target) throw new Error(`feishu workflow progress: cannot route sessionKey "${input.sessionKey}"`);
			const account = resolveFeishuAccount(cfg, target.accountId);
			if (!account.configured) throw new Error(`feishu workflow progress: account "${target.accountId}" not configured (sessionKey "${input.sessionKey}")`);
			const text = clampForFeishu(input.text);
			if (input.previousMessageId && !input.isFinal) try {
				await editMessageFeishu({
					cfg,
					accountId: target.accountId,
					messageId: 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 fresh send");
				else throw err;
			}
			const { api } = createFeishuClient(account);
			const receiveIdType = isOpenId(target.peerId) ? "open_id" : "chat_id";
			const messageId = extractMessageId(await api.im.message.create({
				params: { receive_id_type: receiveIdType },
				data: {
					receive_id: target.peerId,
					msg_type: "text",
					content: JSON.stringify({ text })
				}
			}));
			if (!messageId) throw new Error("feishu workflow progress: send succeeded but no message_id returned");
			return { messageId };
		}
	};
}
function resolveTarget(sessionKey) {
	const parsed = parseSessionKey(sessionKey);
	if (!parsed) return null;
	if (parsed.source !== "feishu") return null;
	if (!parsed.peerId) return null;
	return {
		accountId: parsed.accountId || "default",
		peerId: parsed.peerId
	};
}
function clampForFeishu(text) {
	if (text.length <= FEISHU_TEXT_MAX) return text;
	return `${text.slice(0, FEISHU_TEXT_MAX - 1)}…`;
}
function isOpenId(peerId) {
	return peerId.toLowerCase().startsWith("ou_");
}
function extractMessageId(res) {
	if (!res || typeof res !== "object") return void 0;
	const rec = res;
	const data = rec.data;
	const fromData = typeof data?.message_id === "string" ? data.message_id : void 0;
	if (fromData) return fromData;
	return typeof rec.message_id === "string" ? rec.message_id : void 0;
}
function isMessageNotModified(err) {
	const msg = errorMessage(err).toLowerCase();
	return msg.includes("not_modified") || msg.includes("not modified");
}
function isEditTargetGone(err) {
	const msg = errorMessage(err).toLowerCase();
	return msg.includes("message_not_found") || msg.includes("message not found") || msg.includes("not exist");
}
function errorMessage(err) {
	if (!err) return "";
	if (err instanceof Error) return err.message;
	return String(err);
}
//#endregion
export { createFeishuWorkflowProgressCapability };

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