import { ConfigSchema, init_schema } from "../../../../src/config/schema.js";
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 { DEFAULT_BASE_URL, clearStaleAccountsForUserId, registerWeixinAccountId, resolveWeixinAccount, saveWeixinAccount } from "../auth/accounts.js";
import { startWeixinLoginWithQr, waitForWeixinLogin } from "../auth/login-qr.js";
//#region extensions/weixin/src/cli/qr-login.ts
init_schema();
init_loader();
function getWeixinLoginApiContext(cfg, accountHint) {
	const routeTagRaw = (cfg.channels?.weixin)?.routeTag;
	const sectionRouteTag = typeof routeTagRaw === "number" ? String(routeTagRaw) : typeof routeTagRaw === "string" && routeTagRaw.trim() ? routeTagRaw.trim() : void 0;
	if (accountHint?.trim()) try {
		const r = resolveWeixinAccount(cfg, accountHint);
		return {
			baseUrl: r.baseUrl,
			routeTag: r.routeTag ?? sectionRouteTag
		};
	} catch {}
	return {
		baseUrl: DEFAULT_BASE_URL,
		routeTag: sectionRouteTag
	};
}
function mergeWeixinConfigAfterLogin(cfg, normalizedAccountId) {
	const prev = cfg.channels?.weixin;
	const prevAccounts = prev?.accounts ?? {};
	const merged = {
		...cfg,
		channels: {
			...cfg.channels,
			weixin: {
				...prev ?? {},
				enabled: true,
				accounts: {
					...prevAccounts,
					[normalizedAccountId]: {
						...prevAccounts[normalizedAccountId] ?? {},
						enabled: true
					}
				}
			}
		}
	};
	return ConfigSchema.parse(merged);
}
/**
* Run interactive Weixin QR login (terminal QR + long-poll until confirmed or timeout).
*/
async function runWeixinQrLoginCli(opts) {
	const configPath = opts.configPath ?? process.env.XOPC_CONFIG_PATH;
	const cfg = opts.existingConfig ?? loadConfig(configPath);
	const { baseUrl, routeTag } = getWeixinLoginApiContext(cfg, opts.account);
	const timeoutMs = opts.timeoutMs ?? 48e4;
	const verbose = Boolean(opts.verbose);
	console.log("\n🔐 Weixin QR login");
	console.log(`   API base: ${baseUrl}\n`);
	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"
	};
	console.log("Scan this QR code with WeChat:\n");
	try {
		const qrcodeTerminal = await import(
			/* @vite-ignore */
			"qrcode-terminal"
);
		await new Promise((resolve) => {
			qrcodeTerminal.default.generate(startResult.qrcodeUrl, { small: true }, (qr) => {
				console.log(qr);
				resolve();
			});
		});
	} catch {
		console.log("Open this URL in a browser to scan:\n");
		console.log(startResult.qrcodeUrl);
	}
	console.log("\nWaiting for confirmation...\n");
	const waitResult = await waitForWeixinLogin({
		sessionKey: startResult.sessionKey,
		timeoutMs,
		verbose,
		routeTag,
		botType: "3"
	});
	if (!waitResult.connected || !waitResult.botToken || !waitResult.accountId) return {
		ok: false,
		message: waitResult.message || "Login did not complete"
	};
	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) {
		logger.error(`Failed to save Weixin account: ${String(err)}`);
		return {
			ok: false,
			message: `Saved login failed: ${String(err)}`
		};
	}
	if (opts.writeConfig !== false) try {
		await saveConfig(mergeWeixinConfigAfterLogin(cfg, normalizedId), configPath);
	} catch (err) {
		logger.warn(`Config merge failed (credentials saved on disk): ${String(err)}`);
	}
	console.log(`\n✅ Weixin connected as account "${normalizedId}".`);
	console.log("   Restart the gateway if it is already running.\n");
	return {
		ok: true,
		accountId: normalizedId,
		message: "OK"
	};
}
//#endregion
export { getWeixinLoginApiContext, mergeWeixinConfigAfterLogin, runWeixinQrLoginCli };

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