from blends.models import (
    NId,
)
from blends.syntax.models import (
    SyntaxGraphArgs,
)


def build_using_statement_node(
    args: SyntaxGraphArgs,
    block_id: NId,
    declaration_id: NId | None,
) -> NId:
    args.syntax_graph.add_node(
        args.n_id,
        block_id=block_id,
        label_type="UsingStatement",
    )

    args.syntax_graph.add_edge(
        args.n_id,
        args.generic(args.fork_n_id(block_id)),
        label_ast="AST",
    )

    if declaration_id:
        args.syntax_graph.update_node_attribute(args.n_id, "declaration_id", declaration_id)
        args.syntax_graph.add_edge(
            args.n_id,
            args.generic(args.fork_n_id(declaration_id)),
            label_ast="AST",
        )
        if scope_stack := args.metadata.get("scope_stack"):
            decl_node = args.syntax_graph.nodes.get(declaration_id, {})
            variable = decl_node.get("variable")
            if not variable and (var_id := decl_node.get("variable_id")):
                variable = args.syntax_graph.nodes.get(var_id, {}).get("symbol")
            if variable:
                args.syntax_graph.symbol_index.setdefault(variable, {}).setdefault(
                    scope_stack[-1], []
                ).append(args.n_id)

    return args.n_id
