import { createLogger } from "../../../../src/utils/logger/index.js";
import { init_logger } from "../../../../src/utils/logger.js";
import { renderTelegramHtmlText } from "../format.js";
import { createTelegramDraftStream } from "../draft-stream.js";
//#region extensions/telegram/src/adapters/streaming-adapter.ts
init_logger();
const log = createLogger("TelegramStreaming");
const DM_MIN_INITIAL_CHARS = 30;
function isProbablyPrivateChat(chatId) {
	const n = Number(chatId);
	if (Number.isFinite(n) && n < 0) return false;
	return true;
}
function createTelegramStreamingAdapter(deps) {
	const { accountManager } = deps;
	return { startStream(options) {
		const accountId = options.accountId ?? "default";
		const streamMode = accountManager.getAccount(accountId)?.streamMode ?? "partial";
		if (streamMode === "off" || streamMode === "block") return null;
		const bot = accountManager.getBot(accountId);
		if (!bot) {
			log.warn({ accountId }, "Streaming skipped: bot not available");
			return null;
		}
		const chatId = options.chatId;
		const threadParsed = options.threadId ? parseInt(options.threadId, 10) : NaN;
		const threadId = Number.isFinite(threadParsed) ? threadParsed : void 0;
		const replyParsed = options.replyToMessageId ? parseInt(options.replyToMessageId, 10) : NaN;
		const replyToMessageId = Number.isFinite(replyParsed) ? replyParsed : void 0;
		const isPrivate = isProbablyPrivateChat(chatId);
		const previewTransport = isPrivate ? "message" : "auto";
		const draft = createTelegramDraftStream({
			api: bot.api,
			chatId,
			threadId: Number.isFinite(threadId) ? threadId : void 0,
			replyToMessageId: Number.isFinite(replyToMessageId) ? replyToMessageId : void 0,
			previewTransport,
			minInitialChars: isPrivate ? DM_MIN_INITIAL_CHARS : void 0,
			renderText: (text) => ({
				text: renderTelegramHtmlText(text),
				parseMode: "HTML"
			}),
			warn: (m) => log.warn(m)
		});
		let skipFinalOutbound = false;
		const end = async () => {
			if (draft.previewMode?.() === "draft" && typeof draft.materialize === "function") {
				skipFinalOutbound = typeof await draft.materialize() === "number";
				return;
			}
			await draft.flush();
			await draft.stop();
			skipFinalOutbound = typeof draft.messageId() === "number";
		};
		const abort = async () => {
			await draft.clear();
			skipFinalOutbound = false;
		};
		return {
			update: (text) => draft.update(text),
			updateProgress: (text, stage, detail) => draft.updateWithProgress(text, stage, detail),
			setProgress: (stage, detail) => draft.setProgress(stage, detail),
			end,
			abort,
			messageId: () => draft.messageId(),
			skipFinalOutbound: () => skipFinalOutbound
		};
	} };
}
//#endregion
export { createTelegramStreamingAdapter };

//# sourceMappingURL=streaming-adapter.js.map