import { visit } from "unist-util-visit";
import crypto from "node:crypto";

function toText(node) {
  if (!node) return "";
  if (node.type === "text") return node.value || "";
  const children = node.children || [];
  return children.map(toText).join("");
}

export default function rehypeParagraphIds() {
  return (tree) => {
    let i = 0;
    visit(tree, "element", (node) => {
      if (node.tagName !== "p") return;

      const text = toText(node).trim();
      if (!text) return;

      const norm = text.replace(/\s+/g, " ").toLowerCase();
      const hash = crypto.createHash("sha1").update(norm).digest("hex").slice(0, 8);

      node.properties = node.properties || {};
      if (!node.properties.id) node.properties.id = `p-${i}-${hash}`;
      i += 1;
    });
  };
}
