import type { OutlineItem } from './markdown'

export type OutlineTreeNode = OutlineItem & {
  id: string
  children: OutlineTreeNode[]
}

export function buildOutlineTree(items: OutlineItem[]): OutlineTreeNode[] {
  const root: OutlineTreeNode[] = []
  const stack: OutlineTreeNode[] = []
  for (const item of items) {
    const node: OutlineTreeNode = {
      ...item,
      id: `o-${item.line}`,
      children: []
    }
    while (stack.length > 0 && stack[stack.length - 1]!.level >= node.level) {
      stack.pop()
    }
    if (stack.length === 0) root.push(node)
    else stack[stack.length - 1]!.children.push(node)
    stack.push(node)
  }
  return root
}

export function collectBranchIds(nodes: OutlineTreeNode[]): string[] {
  const ids: string[] = []
  const walk = (list: OutlineTreeNode[]): void => {
    for (const n of list) {
      if (n.children.length > 0) {
        ids.push(n.id)
        walk(n.children)
      }
    }
  }
  walk(nodes)
  return ids
}
