from django_ltree.fields import PathValue
from django_ltree.models import TreeModel


def update_node_path(instance):
    if not getattr(instance.__class__, "node", None):
        raise AttributeError("Node not found in the instance class")

    related = instance.__class__.node.related
    field_name = related.target_field.name
    model = related.related_model

    new_path = PathValue(str(instance.pk))

    parent = instance.parent
    if parent:
        new_path = parent.node.path + new_path

    params = {field_name: instance, "defaults": {"path": new_path}}

    node, node_created = model.objects.get_or_create(**params)

    if not node_created:
        if node.path == new_path:
            return

        # обновляет path у всех потомков
        for nd in node.descendants():  # type: TreeModel
            path_length = len(node.path)
            nd.path = new_path + nd.path[path_length:]
            nd.save()

        node.path = new_path
        node.save()
