from blends.models import (
    NId,
)
from blends.syntax.builders.method_invocation import (
    DirectChildren,
    build_method_invocation_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
    expr_id = graph.nodes[args.n_id]["label_field_function"]
    expr_id_child = None
    children: DirectChildren = {}

    if graph.nodes[expr_id]["label_type"] == "field_expression":
        if object_id := graph.nodes[expr_id].get("label_field_value"):
            children["object_id"] = object_id
        expr = node_to_str(graph, graph.nodes[expr_id]["label_field_field"])
        expr_id_child = graph.nodes[expr_id]["label_field_field"]
    elif graph.nodes[expr_id]["label_type"] == "call_expression":
        children["object_id"] = expr_id
        expr = ""
    else:
        expr = node_to_str(graph, expr_id)

    if expr_id_child:
        children["expression_id"] = expr_id_child

    arguments_id = graph.nodes[args.n_id].get("label_field_arguments")
    if arguments_id and graph.nodes[arguments_id]["label_type"] == "block":
        children["block_id"] = arguments_id
        return build_method_invocation_node(args, expr, children)

    if arguments_id:
        children["arguments_id"] = arguments_id

    return build_method_invocation_node(args, expr, children)
