import bpy


class GPEXP_OT_clear_render_tree(bpy.types.Operator):
    bl_idname = "gp.clear_render_tree"
    bl_label = "Clear Render Node Tree "
    bl_description = "Clear node tree from render scene"
    bl_options = {"REGISTER"}

    @classmethod
    def poll(cls, context):
        return True

    mode : bpy.props.StringProperty(default='NORMAL', options={'SKIP_SAVE'})

    def execute(self, context):

        render = bpy.data.scenes.get('Render')
        if not render:
            print('SKIP, no Render scene')
            return {"CANCELLED"}

        # clear all nodes in frames
        if render.use_nodes:
            for i in range(len(render.node_tree.nodes))[::-1]:

                # skip frames to delete later
                if render.node_tree.nodes[i].type == 'FRAME':
                    continue

                # skip unparented nodes
                if not render.node_tree.nodes[i].parent:
                    continue
                render.node_tree.nodes.remove(render.node_tree.nodes[i])

        # delete all framesWorki
        if render.use_nodes:
            for i in range(len(render.node_tree.nodes))[::-1]:
                if render.node_tree.nodes[i].type == 'FRAME':
                    render.node_tree.nodes.remove(render.node_tree.nodes[i])

        # clear all view_layers
        for vl in reversed(render.view_layers):
            if ' / ' in vl.name:
                render.view_layers.remove(vl)

        # clear all "NG_" nodegroups
        for ng in reversed(bpy.data.node_groups):
            if ng.name.startswith('NG_'):
                ng.use_fake_user = False
                bpy.data.node_groups.remove(ng)

        if self.mode == 'COMPLETE':
            bpy.data.scenes.remove(render)

        return {"FINISHED"}

classes=(
GPEXP_OT_clear_render_tree,
)

def register():
    for cls in classes:
        bpy.utils.register_class(cls)

def unregister():
    for cls in reversed(classes):
        bpy.utils.unregister_class(cls)