from blends.ctx import ctx
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 (
            ctx.has_feature_flag("ScopeIndex")
            and (variable := args.syntax_graph.nodes.get(declaration_id, {}).get("variable"))
            and (scope_stack := args.metadata.get("scope_stack"))
        ):
            args.syntax_graph.symbol_index.setdefault(variable, {})[scope_stack[-1]] = args.n_id

    return args.n_id
