from blends.models import (
    NId,
)
from blends.query import (
    adj_ast,
    match_ast,
    match_ast_d,
    match_ast_group_d,
)
from blends.syntax.builders.method_declaration import (
    DirectChildren,
    ListChildren,
    build_method_declaration_node,
)
from blends.syntax.models import (
    SyntaxGraphArgs,
)
from blends.utilities.text_nodes import (
    node_to_str,
)


def reader(args: SyntaxGraphArgs) -> NId:
    graph = args.ast_graph
    n_attrs = graph.nodes[args.n_id]
    if declaration_n_id := match_ast_d(graph, args.n_id, "identifier"):
        graph.nodes[args.n_id]["label_l"] = graph.nodes[declaration_n_id]["label_l"]
    name = node_to_str(graph, n_attrs["label_field_name"])
    block_id = n_attrs.get("label_field_body")
    n_access_mod = [
        adj[0]
        for node in adj_ast(graph, args.n_id, label_type="modifier")
        if (adj := adj_ast(graph, node))
    ]

    parameters_id = n_attrs["label_field_parameters"]
    if "__0__" not in match_ast(graph, parameters_id, "(", ")"):
        parameters_id = None

    attributes_ids = match_ast_group_d(graph, args.n_id, "attribute_list")

    direct: DirectChildren = {}
    if block_id:
        direct["block_id"] = block_id
    if parameters_id:
        direct["parameters_id"] = parameters_id

    list_children: ListChildren = {}
    if attributes_ids:
        list_children["modifiers_ids"] = attributes_ids

    access_modifiers = (
        " ".join(graph.nodes[i].get("label_text", "") for i in n_access_mod)
        if n_access_mod
        else None
    )

    return build_method_declaration_node(args, name, direct, list_children, access_modifiers)
