from blends.models import (
    NId,
)
from blends.query import (
    match_ast,
)
from blends.syntax.builders.method_declaration import (
    DirectChildren,
    build_method_declaration_node,
)
from blends.syntax.metadata.java import (
    add_method_to_metadata,
)
from blends.syntax.models import (
    SyntaxGraphArgs,
)
from blends.syntax.readers.java.class_declaration import (
    extract_modifiers,
)
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]
    name_id = n_attrs["label_field_name"]
    name = node_to_str(graph, name_id)

    block_id = n_attrs.get("label_field_body")

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

    modifiers_id, access_modifiers = extract_modifiers(graph, args.n_id)

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

    if args.syntax_graph.nodes.get(NId(0)):
        add_method_to_metadata(args, name)

    return build_method_declaration_node(args, name, direct, {}, access_modifiers)
