from blends.ctx import ctx
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.models import (
    SyntaxGraphArgs,
)
from blends.syntax.readers.python.parameter import (
    emit_annotation_ref_nodes,
)
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["label_field_body"]

    parameters_id = n_attrs["label_field_parameters"]
    include_params = "__0__" in match_ast(args.ast_graph, parameters_id, "(", ")")

    if ctx.has_feature_flag("StackGraph"):
        return_type_id = n_attrs.get("label_field_return_type")
        if return_type_id:
            emit_annotation_ref_nodes(args, return_type_id)

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

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