from __future__ import annotations

"""Graph dispatch for neuraparse.

The :func:`build_graph` function selects an appropriate builder (or uses
all of them in sequence in later versions) to construct a
:class:`DocumentGraph` from a :class:`DocumentTree`.
"""

from typing import List

from ..core.models import DocumentGraph, DocumentTree
from .base import BaseGraphBuilder, GraphBuildError
from .semantic import SemanticGraphBuilder


_DEFAULT_BUILDERS: List[BaseGraphBuilder] = [
    # Use the semantic builder, which internally constructs the structural
    # graph and then enriches it.
    SemanticGraphBuilder(),
]


def build_graph(tree: DocumentTree, *, builders: List[BaseGraphBuilder] | None = None) -> DocumentGraph:
    """Build a :class:`DocumentGraph` from ``tree`` using available builders."""

    candidates = builders or _DEFAULT_BUILDERS
    for builder in candidates:
        if builder.supports(tree):
            return builder.build(tree)

    raise GraphBuildError("No graph builder available for document tree")

