from blends.ctx import ctx
from blends.models import (
    NId,
)
from blends.stack.edges import (
    Edge,
    add_edge,
)
from blends.stack.node_helpers import (
    push_symbol_node_attributes,
)
from blends.syntax.builders.utils import (
    get_next_synthetic_node_id,
)
from blends.syntax.models import (
    SyntaxGraphArgs,
)


def build_member_access_node(
    args: SyntaxGraphArgs,
    member: str,
    expression: str,
    expression_id: NId,
) -> NId:
    args.syntax_graph.add_node(
        args.n_id,
        member=member,
        expression=expression,
        expression_id=expression_id,
        label_type="MemberAccess",
    )

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

    if ctx.has_feature_flag("StackGraph"):
        args.syntax_graph.update_node(
            args.n_id,
            push_symbol_node_attributes(symbol=member, is_reference=True),
        )
        dot_id = get_next_synthetic_node_id(args)
        args.syntax_graph.add_node(
            dot_id,
            label_type="SyntheticMemberDot",
            **push_symbol_node_attributes(symbol=".", is_reference=False),
        )
        add_edge(args.syntax_graph, Edge(source=args.n_id, sink=dot_id))
        add_edge(args.syntax_graph, Edge(source=dot_id, sink=child_id))

    return args.n_id
