import type { TraceNode, TraceNodeEvent } from '@/common/interface/trace'

type Tree = TraceNode | TraceNodeEvent

function hasChildren(n: Tree): n is TraceNode {
  return Array.isArray((n as any).children)
}

function dfs(node: Tree, targetId: string, directParent: Tree | null): Tree | null {
  if ((node as any).id === targetId) return directParent
  if (!hasChildren(node)) return null

  for (const child of node.children!) {
    const res = dfs(child, targetId, node as any)
    if (res !== null) return res
  }
  return null
}

export function findDirectParent(root: Tree, targetId: string): Tree | null {
  return dfs(root, targetId, null)
}
