import { SerializedBlock, SerializedBlockTree } from "../adapters/reader/structure/block-types";

export interface BlockTreeNode extends SerializedBlock {
  children: BlockTreeNode[];
}

/**
 * Rebuilds the flat, preorder `SerializedBlock[]` wire format into a tree in
 * one linear pass. `blocks` is guaranteed preorder (parents precede
 * children) by the sender — see segment-page.ts's `flatten()`.
 */
export function buildBlockTree(tree: SerializedBlockTree): BlockTreeNode[] {
  const byId = new Map<number, BlockTreeNode>();
  const roots: BlockTreeNode[] = [];
  for (const block of tree.blocks) {
    const node: BlockTreeNode = { ...block, children: [] };
    byId.set(node.i, node);
    if (node.p == undefined) {
      roots.push(node);
    } else {
      const parent = byId.get(node.p);
      if (parent != undefined) {
        parent.children.push(node);
      } else {
        // Defensive: a parent id that isn't in the payload (shouldn't
        // happen given preorder + try/catch on the sender) — don't lose
        // the block, surface it at top level rather than dropping content.
        roots.push(node);
      }
    }
  }
  return roots;
}
