import type { PlaceholderMapping } from "../types"; export function mappingRoot(key: string, mapping: PlaceholderMapping): string { const initial = mapping[key]; if (!initial) throw new Error(`Unbekannte Zuordnung: ${key}`); const seen = new Set(); let current = key; while (mapping[current].merged_into) { if (seen.has(current)) throw new Error(`Zyklische Zuordnung: ${key}`); seen.add(current); const reference = mapping[current].merged_into!; const target = mapping[reference] ? reference : mapping[`<${reference.replace(/^<|>$/g, "")}>`] ? `<${reference.replace(/^<|>$/g, "")}>` : reference.replace(/^<|>$/g, ""); if (!mapping[target] || mapping[target].type !== initial.type) { throw new Error(`Ungültiger Hauptbegriff für ${key}: ${reference}`); } current = target; } return current; } /** Reverse lookups use the group's main term, while the saved variants remain intact. */ export function mappingForRestoration(mapping: PlaceholderMapping): PlaceholderMapping { return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [key, { type: entry.type, original: mapping[mappingRoot(key, mapping)].original, }])); } export function mergeMappingGroups(mapping: PlaceholderMapping, source: string, target: string): PlaceholderMapping { const from = mappingRoot(source, mapping); const into = mappingRoot(target, mapping); if (from === into) throw new Error("Diese Zuordnungen sind bereits zusammengefasst."); if (mapping[from].type !== mapping[into].type) { throw new Error("Nur Zuordnungen derselben Kategorie können zusammengefasst werden."); } return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [key, mappingRoot(key, mapping) === from ? { ...entry, merged_into: into } : { ...entry }, ])); } export function detachMappingGroup(mapping: PlaceholderMapping, key: string): PlaceholderMapping { if (!mapping[key]?.merged_into) throw new Error("Diese Zuordnung ist kein Verweis."); return { ...mapping, [key]: { ...mapping[key], merged_into: undefined } }; }