import { logger } from "../util/logger.js";
import { normalizeWeixinAccountId } from "./weixin-account-id.js";
import { resolveWeixinRootDir } from "../storage/state-dir.js";
import fs from "node:fs";
import path from "node:path";
//#region extensions/weixin/src/auth/accounts.ts
const DEFAULT_BASE_URL = "https://ilinkai.weixin.qq.com";
const CDN_BASE_URL = "https://novac2c.cdn.weixin.qq.com/c2c";
function resolveWeixinStateDir() {
	return resolveWeixinRootDir();
}
function resolveAccountIndexPath() {
	return path.join(resolveWeixinStateDir(), "accounts.json");
}
function listIndexedWeixinAccountIds() {
	const filePath = resolveAccountIndexPath();
	try {
		if (!fs.existsSync(filePath)) return [];
		const raw = fs.readFileSync(filePath, "utf-8");
		const parsed = JSON.parse(raw);
		if (!Array.isArray(parsed)) return [];
		return parsed.filter((id) => typeof id === "string" && id.trim() !== "");
	} catch {
		return [];
	}
}
function registerWeixinAccountId(accountId) {
	const dir = resolveWeixinStateDir();
	fs.mkdirSync(dir, { recursive: true });
	const existing = listIndexedWeixinAccountIds();
	if (existing.includes(accountId)) return;
	const updated = [...existing, accountId];
	fs.writeFileSync(resolveAccountIndexPath(), JSON.stringify(updated, null, 2), "utf-8");
}
function unregisterWeixinAccountId(accountId) {
	const existing = listIndexedWeixinAccountIds();
	const updated = existing.filter((id) => id !== accountId);
	if (updated.length !== existing.length) fs.writeFileSync(resolveAccountIndexPath(), JSON.stringify(updated, null, 2), "utf-8");
}
function clearStaleAccountsForUserId(currentAccountId, userId, onClearContextTokens) {
	if (!userId) return;
	const allIds = listIndexedWeixinAccountIds();
	for (const id of allIds) {
		if (id === currentAccountId) continue;
		if (loadWeixinAccount(id)?.userId?.trim() === userId) {
			logger.info(`clearStaleAccountsForUserId: removing stale account=${id} (same userId=${userId})`);
			onClearContextTokens?.(id);
			clearWeixinAccount(id);
			unregisterWeixinAccountId(id);
		}
	}
}
function resolveAccountsDir() {
	return path.join(resolveWeixinStateDir(), "accounts");
}
function resolveAccountPath(accountId) {
	return path.join(resolveAccountsDir(), `${accountId}.json`);
}
function readAccountFile(filePath) {
	try {
		if (fs.existsSync(filePath)) return JSON.parse(fs.readFileSync(filePath, "utf-8"));
	} catch {}
	return null;
}
function loadWeixinAccount(accountId) {
	return readAccountFile(resolveAccountPath(accountId));
}
function saveWeixinAccount(accountId, update) {
	const dir = resolveAccountsDir();
	fs.mkdirSync(dir, { recursive: true });
	const existing = loadWeixinAccount(accountId) ?? {};
	const token = update.token?.trim() || existing.token;
	const baseUrl = update.baseUrl?.trim() || existing.baseUrl;
	const userId = update.userId !== void 0 ? update.userId.trim() || void 0 : existing.userId?.trim() || void 0;
	const data = {
		...token ? {
			token,
			savedAt: (/* @__PURE__ */ new Date()).toISOString()
		} : {},
		...baseUrl ? { baseUrl } : {},
		...userId ? { userId } : {}
	};
	const filePath = resolveAccountPath(accountId);
	fs.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf-8");
	try {
		fs.chmodSync(filePath, 384);
	} catch {}
}
function clearWeixinAccount(accountId) {
	const dir = resolveAccountsDir();
	const accountFiles = [
		`${accountId}.json`,
		`${accountId}.sync.json`,
		`${accountId}.context-tokens.json`
	];
	for (const file of accountFiles) try {
		fs.unlinkSync(path.join(dir, file));
	} catch {}
	try {
		fs.unlinkSync(resolveFrameworkAllowFromPath(accountId));
	} catch {}
}
function weixinSection(cfg) {
	return cfg.channels?.weixin;
}
function listWeixinAccountIds(cfg) {
	const section = weixinSection(cfg);
	const fromConfig = section?.accounts ? Object.keys(section.accounts) : [];
	if (!section || section.enabled !== true) return fromConfig;
	const indexed = listIndexedWeixinAccountIds();
	return [...new Set([...indexed, ...fromConfig])];
}
function resolveWeixinAccount(cfg, accountId) {
	const raw = accountId?.trim();
	if (!raw) throw new Error("weixin: accountId is required");
	const id = normalizeWeixinAccountId(raw);
	const section = weixinSection(cfg);
	const fromAccount = section?.accounts?.[id];
	const { accounts: _omit, ...sectionRest } = section ?? {};
	const accountCfg = {
		...sectionRest,
		...fromAccount ?? {}
	};
	const accountData = loadWeixinAccount(id);
	const token = accountData?.token?.trim() || void 0;
	const stateBaseUrl = accountData?.baseUrl?.trim() || "";
	const routeTagRaw = accountCfg.routeTag;
	const routeTag = typeof routeTagRaw === "number" ? String(routeTagRaw) : typeof routeTagRaw === "string" && routeTagRaw.trim() ? routeTagRaw.trim() : void 0;
	const channelEnabled = section?.enabled === true;
	return {
		accountId: id,
		baseUrl: stateBaseUrl || "https://ilinkai.weixin.qq.com",
		cdnBaseUrl: accountCfg.cdnBaseUrl?.trim() || "https://novac2c.cdn.weixin.qq.com/c2c",
		token,
		enabled: channelEnabled && accountCfg.enabled !== false,
		configured: Boolean(token),
		name: accountCfg.name?.trim() || void 0,
		dmPolicy: accountCfg.dmPolicy ?? "open",
		allowFrom: accountCfg.allowFrom ?? [],
		streamMode: accountCfg.streamMode,
		routeTag,
		debug: accountCfg.debug ?? false
	};
}
function resolveFrameworkAllowFromPath(accountId) {
	const base = "xopc-weixin".replace(/[\\/:*?"<>|]/g, "_");
	const safeAccount = accountId.trim().toLowerCase().replace(/[\\/:*?"<>|]/g, "_").replace(/\.\./g, "_");
	const { join } = path;
	return join(process.env.XOPC_CREDENTIALS_DIR?.trim() ? process.env.XOPC_CREDENTIALS_DIR : join(resolveWeixinRootDir(), "credentials"), `${base}-${safeAccount}-allowFrom.json`);
}
//#endregion
export { CDN_BASE_URL, DEFAULT_BASE_URL, clearStaleAccountsForUserId, clearWeixinAccount, listIndexedWeixinAccountIds, listWeixinAccountIds, loadWeixinAccount, normalizeWeixinAccountId, registerWeixinAccountId, resolveFrameworkAllowFromPath, resolveWeixinAccount, saveWeixinAccount, unregisterWeixinAccountId };

//# sourceMappingURL=accounts.js.map