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 { getContextToken } from "./messaging/inbound.js";
import { resolveWeixinAccount } from "./auth/accounts.js";
import { sendMessageWeixin } from "./messaging/send.js";
import { ensureWeixinContextTokenForOutbound } from "./messaging/context-token-init.js";
//#region extensions/weixin/src/workflow-progress.ts
init_session_key();
init_logger();
const log = createLogger("WeixinWorkflowProgress");
const WEIXIN_TEXT_MAX = 4e3;
/**
* Conservative throttle — only enforced when the user overrides the default
* `final-only` mode to `append`. Set so back-to-back workflows can't spam.
*/
const DEFAULT_THROTTLE_MS = 6e4;
function createWeixinWorkflowProgressCapability(opts) {
	return {
		channelId: "weixin",
		supportsEdit: false,
		defaultThrottleMs: DEFAULT_THROTTLE_MS,
		defaultMode: "final-only",
		async postProgress(input) {
			const cfg = opts.getConfig();
			if (!cfg) throw new Error("weixin workflow progress: no config loaded");
			const target = resolveTarget(input.sessionKey);
			if (!target) throw new Error(`weixin workflow progress: cannot route sessionKey "${input.sessionKey}"`);
			let account;
			try {
				account = resolveWeixinAccount(cfg, target.accountId);
			} catch (err) {
				throw new Error(`weixin workflow progress: cannot resolve account "${target.accountId}": ${errorMessage(err)}`);
			}
			if (!account.configured || !account.token) throw new Error(`weixin workflow progress: account "${target.accountId}" not configured / logged in`);
			let ctxTok = getContextToken(account.accountId, target.to)?.trim();
			if (!ctxTok) ctxTok = (await ensureWeixinContextTokenForOutbound(account.accountId, target.to, account))?.trim();
			if (!ctxTok) {
				log.debug({
					sessionKey: input.sessionKey,
					accountId: account.accountId
				}, "no context token for recipient; skipping workflow progress send");
				return { messageId: "" };
			}
			const text = clampForWeixin(decorateForWeixin(input.text, input.mode, input.isFinal));
			return { messageId: (await sendMessageWeixin({
				to: target.to,
				text,
				opts: {
					baseUrl: account.baseUrl,
					token: account.token,
					routeTag: account.routeTag,
					contextToken: ctxTok
				}
			})).messageId };
		}
	};
}
function resolveTarget(sessionKey) {
	const parsed = parseSessionKey(sessionKey);
	if (!parsed) return null;
	if (parsed.source !== "weixin") return null;
	if (!parsed.peerId) return null;
	return {
		accountId: parsed.accountId || "default",
		to: parsed.peerId
	};
}
function clampForWeixin(text) {
	if (text.length <= WEIXIN_TEXT_MAX) return text;
	return `${text.slice(0, WEIXIN_TEXT_MAX - 1)}…`;
}
/**
* Add a one-line header on append-mode messages so the user can tell mid-run
* snapshots apart from the final summary — WeChat has no editMessage, so they
* pile up as separate messages and look identical without a marker.
*
*   - `final-only` mode: no header (default; one summary message per run).
*   - `append` mode + mid-run: "▾ 工作流进展" header so the user knows more
*     updates are coming.
*   - `append` mode + final: "✓ 工作流完成" header to mark the conclusion.
*
* `edit` mode is never reached on WeChat (`supportsEdit: false`), so we don't
* branch on it. Unknown / missing mode falls through to no header — safe
* default for hand-rolled callers and tests.
*/
function decorateForWeixin(text, mode, isFinal) {
	if (mode !== "append") return text;
	return `${isFinal ? "✓ 工作流完成" : "▾ 工作流进展"}\n${text}`;
}
function errorMessage(err) {
	if (!err) return "";
	if (err instanceof Error) return err.message;
	return String(err);
}
//#endregion
export { createWeixinWorkflowProgressCapability };

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