//#region src/redact.ts
function toAlpha(n) {
	let result = "";
	let num = n;
	do {
		result = String.fromCharCode(97 + num % 26) + result;
		num = Math.floor(num / 26) - 1;
	} while (num >= 0);
	return result;
}
function normalizePhone(phone) {
	return phone.replace(/[\s\-().+]/g, "");
}
function buildRedactionMap(users, vendors) {
	const forward = /* @__PURE__ */ new Map();
	const reverse = /* @__PURE__ */ new Map();
	const sortedUsers = [...users.values()].sort((a, b) => a.id.localeCompare(b.id));
	const sortedVendors = [...vendors.values()].sort((a, b) => a.id.localeCompare(b.id));
	let userIdx = 0;
	for (const u of sortedUsers) {
		const pseudoBase = `{user_${toAlpha(userIdx)}}`;
		let added = false;
		if (u.email) {
			forward.set(u.email, pseudoBase);
			if (!added) {
				reverse.set(pseudoBase, u.email);
				added = true;
			}
		}
		if (u.phone) {
			const normalized = normalizePhone(u.phone);
			forward.set(normalized, pseudoBase);
			if (!added) reverse.set(pseudoBase, normalized);
		}
		userIdx++;
	}
	let vendorIdx = 0;
	for (const v of sortedVendors) {
		const pseudoBase = `{vendor_${toAlpha(vendorIdx)}}`;
		let added = false;
		if (v.ownerEmail) {
			forward.set(v.ownerEmail, pseudoBase);
			if (!added) {
				reverse.set(pseudoBase, v.ownerEmail);
				added = true;
			}
		}
		if (v.ownerPhone) {
			const normalized = normalizePhone(v.ownerPhone);
			forward.set(normalized, pseudoBase);
			if (!added) reverse.set(pseudoBase, normalized);
		}
		vendorIdx++;
	}
	return {
		forward,
		reverse
	};
}
function redactForPrompt(text, map) {
	if (map.forward.size === 0) return text;
	const emailKeys = [];
	const phoneKeys = [];
	for (const key of map.forward.keys()) if (/^\d+$/.test(key)) phoneKeys.push(key);
	else emailKeys.push(key);
	emailKeys.sort((a, b) => b.length - a.length);
	phoneKeys.sort((a, b) => b.length - a.length);
	let result = text;
	for (const email of emailKeys) {
		const pseudoId = map.forward.get(email);
		const escaped = email.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
		result = result.replace(new RegExp(escaped, "g"), pseudoId);
	}
	for (const digits of phoneKeys) {
		const pseudoId = map.forward.get(digits);
		const digitParts = digits.split("").map((d) => d.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\s\\-().]*");
		const phoneRegex = new RegExp(`\\+?${digitParts}`, "g");
		result = result.replace(phoneRegex, pseudoId);
	}
	return result;
}
function substitutePseudoIds(text, map) {
	if (map.reverse.size === 0) return text;
	let result = text;
	for (const [pseudoId, original] of map.reverse.entries()) {
		const escaped = pseudoId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
		result = result.replace(new RegExp(escaped, "g"), original);
	}
	return result;
}
//#endregion
export { buildRedactionMap, redactForPrompt, substitutePseudoIds };
