from blends.ctx import ctx
from blends.models import NId
from blends.query import adj_ast
from blends.syntax.builders.parameter import build_parameter_node
from blends.syntax.builders.parameter_list import build_parameter_list_node
from blends.syntax.models import SyntaxGraphArgs

_IGNORED_PARAMETER_TYPES = {",", "keyword_separator"}


def reader(args: SyntaxGraphArgs) -> NId:
    graph = args.ast_graph
    _, *c_ids, _ = adj_ast(graph, args.n_id)

    if ctx.has_feature_flag("StackGraph"):
        return _build_stack_graph_parameter_list(args, c_ids)

    return build_parameter_list_node(
        args,
        c_ids=(
            _id for _id in c_ids if graph.nodes[_id]["label_type"] not in _IGNORED_PARAMETER_TYPES
        ),
    )


def _build_stack_graph_parameter_list(args: SyntaxGraphArgs, c_ids: list[NId]) -> NId:
    graph = args.ast_graph
    args.syntax_graph.add_node(args.n_id, label_type="ParameterList")

    for c_id in c_ids:
        label_type = graph.nodes[c_id]["label_type"]
        if label_type in _IGNORED_PARAMETER_TYPES:
            continue

        if label_type == "identifier":
            child_id = build_parameter_node(
                args=args.fork_n_id(c_id),
                variable=graph.nodes[c_id]["label_text"],
                variable_type=None,
                value_id=None,
            )
        else:
            child_id = args.generic(args.fork_n_id(c_id))

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

    return args.n_id
