const LANGUAGE_ALIASES = new Map([["ojs", "js"]]);

const normalizeLanguage = (language) => {
  if (!language) return language;

  const match = language.match(/^\{(.+)\}$/);
  if (!match) return language;

  const normalized = match[1].trim().toLowerCase();
  return LANGUAGE_ALIASES.get(normalized) ?? normalized;
};

const visit = (node) => {
  if (node.type === "code") {
    node.lang = normalizeLanguage(node.lang);
  }

  if (!Array.isArray(node.children)) return;

  for (const child of node.children) {
    visit(child);
  }
};

const remarkCodeFenceLanguages = () => (tree) => {
  visit(tree);
};

export default remarkCodeFenceLanguages;
