import { init_loader, loadConfig, saveConfig } from "../../../../src/config/loader.js";
import { logger } from "../util/logger.js";
import { normalizeWeixinAccountId } from "../auth/weixin-account-id.js";
import { clearContextTokensForAccount } from "../messaging/inbound.js";
import { clearStaleAccountsForUserId, registerWeixinAccountId, saveWeixinAccount } from "../auth/accounts.js";
import { getWeixinActiveLoginSnapshot, startWeixinLoginWithQr, waitForWeixinLogin } from "../auth/login-qr.js";
import { getWeixinLoginApiContext, mergeWeixinConfigAfterLogin } from "./qr-login.js";
//#region extensions/weixin/src/cli/gateway-qr-login.ts
init_loader();
const completedSessions = /* @__PURE__ */ new Map();
function rememberCompleted(sessionKey, state) {
	completedSessions.set(sessionKey, state);
	setTimeout(() => completedSessions.delete(sessionKey), 10 * 6e4);
}
function getWeixinGatewayQrLoginStatus(sessionKey) {
	const done = completedSessions.get(sessionKey);
	if (done) {
		if (done.ok === true) return {
			phase: "done",
			ok: true,
			accountId: done.accountId
		};
		return {
			phase: "done",
			ok: false,
			message: done.message
		};
	}
	const snap = getWeixinActiveLoginSnapshot(sessionKey);
	if (snap) return {
		phase: "polling",
		qrcodeUrl: snap.qrcodeUrl,
		qrStatus: snap.status
	};
	return {
		phase: "unknown",
		message: "No active login for this session. Start again or the QR may have expired."
	};
}
/**
* Begin QR login and wait in the background; poll with {@link getWeixinGatewayQrLoginStatus}.
*/
async function startWeixinGatewayQrLogin(opts) {
	const configPath = opts.configPath ?? process.env.XOPC_CONFIG_PATH;
	const cfg = loadConfig(configPath);
	const { baseUrl, routeTag } = getWeixinLoginApiContext(cfg, opts.account);
	const timeoutMs = opts.timeoutMs ?? 48e4;
	const verbose = Boolean(opts.verbose);
	const startResult = await startWeixinLoginWithQr({
		accountId: opts.account?.trim() || void 0,
		botType: "3",
		routeTag,
		verbose
	});
	if (!startResult.qrcodeUrl) return {
		ok: false,
		message: startResult.message || "Failed to get QR code"
	};
	const sessionKey = startResult.sessionKey;
	(async () => {
		const waitResult = await waitForWeixinLogin({
			sessionKey,
			timeoutMs,
			verbose,
			routeTag,
			botType: "3",
			silent: true
		});
		if (!waitResult.connected || !waitResult.botToken || !waitResult.accountId) {
			const message = waitResult.message || "Login did not complete";
			rememberCompleted(sessionKey, {
				phase: "done",
				ok: false,
				message
			});
			await opts.onPersisted?.({
				ok: false,
				message
			});
			return;
		}
		const normalizedId = normalizeWeixinAccountId(waitResult.accountId);
		try {
			saveWeixinAccount(normalizedId, {
				token: waitResult.botToken,
				baseUrl: waitResult.baseUrl?.trim() || baseUrl,
				userId: waitResult.userId
			});
			registerWeixinAccountId(normalizedId);
			if (waitResult.userId) clearStaleAccountsForUserId(normalizedId, waitResult.userId, clearContextTokensForAccount);
		} catch (err) {
			const message = `Saved login failed: ${String(err)}`;
			logger.error(message);
			rememberCompleted(sessionKey, {
				phase: "done",
				ok: false,
				message
			});
			await opts.onPersisted?.({
				ok: false,
				message
			});
			return;
		}
		try {
			await saveConfig(mergeWeixinConfigAfterLogin(cfg, normalizedId), configPath);
		} catch (err) {
			logger.warn(`Config merge failed (credentials saved on disk): ${String(err)}`);
		}
		await opts.onPersisted?.({
			ok: true,
			accountId: normalizedId,
			message: "OK"
		});
		rememberCompleted(sessionKey, {
			phase: "done",
			ok: true,
			accountId: normalizedId
		});
	})();
	return {
		ok: true,
		sessionKey,
		qrcodeUrl: startResult.qrcodeUrl
	};
}
//#endregion
export { getWeixinGatewayQrLoginStatus, startWeixinGatewayQrLogin };

//# sourceMappingURL=gateway-qr-login.js.map