bl_info = {
    "name": "Interpolation Changer",
    "author": "Jonathan & Bridget",
    "version": (1, 4, 2),  # 1.4.2: Added recursive node group support
    "blender": (4, 3, 0),
    "location": "Shader Editor > Sidebar > Interpolation Tools",
    "description": "Quickly change interpolation methods for Image and Environment Texture nodes in materials, assets, and globally",
    "category": "Node",
}

import bpy
from typing import List


def find_texture_nodes(node_tree: bpy.types.NodeTree, visited=None) -> List[bpy.types.Node]:
    """Recursively find all Image and Environment Texture nodes with an image in a node tree."""
    if visited is None:
        visited = set()  # Track visited node trees to avoid infinite recursion

    texture_nodes = []
    if not node_tree or id(node_tree) in visited:
        return texture_nodes  # Skip if no tree or already visited

    visited.add(id(node_tree))  # Mark this node tree as visited

    for node in node_tree.nodes:
        if node.type in {'TEX_IMAGE', 'TEX_ENVIRONMENT'} and node.image:
            texture_nodes.append(node)
        elif node.type == 'GROUP' and node.node_tree:
            # Recursively search inside group nodes
            texture_nodes.extend(find_texture_nodes(node.node_tree, visited))

    return texture_nodes


class NODE_OT_set_interpolation(bpy.types.Operator):
    """Set the interpolation mode for Image and Environment Texture nodes in the active material."""
    bl_idname = "node.set_interpolation"
    bl_label = "Set Interpolation"
    interpolation_mode: bpy.props.StringProperty()

    def execute(self, context):
        obj = context.active_object
        if not obj or not obj.active_material:
            self.report({'WARNING'}, "No active object with a material found!")
            return {'CANCELLED'}

        material = obj.active_material
        if not material.use_nodes or not material.node_tree:
            self.report({'WARNING'}, "Active material has no nodes!")
            return {'CANCELLED'}

        texture_nodes = find_texture_nodes(material.node_tree)
        if not texture_nodes:
            self.report({'WARNING'}, "No texture nodes found in the active material!")
            return {'CANCELLED'}

        nodes_updated = 0
        for node in texture_nodes:
            if node.interpolation != self.interpolation_mode:  # Only update if different
                node.interpolation = self.interpolation_mode
                nodes_updated += 1

        self.report({'INFO'}, f"Set interpolation to {self.interpolation_mode} for {nodes_updated} node(s).")
        return {'FINISHED'}


class NODE_OT_set_interpolation_assets(bpy.types.Operator):
    """Set the interpolation mode for Image and Environment Texture nodes in all asset materials."""
    bl_idname = "node.set_interpolation_assets"
    bl_label = "Set Interpolation (Assets)"
    interpolation_mode: bpy.props.StringProperty()

    def execute(self, context):
        nodes_updated = 0
        materials = bpy.data.materials

        for material in materials:
            if material.asset_data and material.use_nodes and material.node_tree:
                texture_nodes = find_texture_nodes(material.node_tree)
                for node in texture_nodes:
                    if node.interpolation != self.interpolation_mode:  # Only update if different
                        node.interpolation = self.interpolation_mode
                        nodes_updated += 1

        if nodes_updated == 0:
            self.report({'WARNING'}, "No texture nodes needed updating in asset materials!")
            return {'CANCELLED'}

        self.report({'INFO'}, f"Set interpolation to {self.interpolation_mode} for {nodes_updated} node(s) in assets.")
        return {'FINISHED'}


class NODE_OT_set_interpolation_global(bpy.types.Operator):
    """Set the interpolation mode for all Image and Environment Texture nodes in the file."""
    bl_idname = "node.set_interpolation_global"
    bl_label = "Set Interpolation (Global)"
    interpolation_mode: bpy.props.StringProperty()

    def execute(self, context):
        nodes_updated = 0

        for material in bpy.data.materials:
            if material.use_nodes and material.node_tree:
                texture_nodes = find_texture_nodes(material.node_tree)
                for node in texture_nodes:
                    if node.interpolation != self.interpolation_mode:  # Only update if different
                        node.interpolation = self.interpolation_mode
                        nodes_updated += 1

        world = context.scene.world
        if world and world.use_nodes and world.node_tree:
            texture_nodes = find_texture_nodes(world.node_tree)
            for node in texture_nodes:
                if node.interpolation != self.interpolation_mode:  # Only update if different
                    node.interpolation = self.interpolation_mode
                    nodes_updated += 1

        if nodes_updated == 0:
            self.report({'WARNING'}, "No texture nodes needed updating in the file!")
            return {'CANCELLED'}

        self.report({'INFO'}, f"Set interpolation to {self.interpolation_mode} for {nodes_updated} node(s) globally.")
        return {'FINISHED'}


class NODE_PT_interpolation_panel(bpy.types.Panel):
    """Panel to manage interpolation of texture nodes."""
    bl_label = "Interpolation Changer"
    bl_idname = "NODE_PT_interpolation_panel"
    bl_space_type = 'NODE_EDITOR'
    bl_region_type = 'UI'
    bl_category = "Interpolation Tools"

    def draw(self, context):
        layout = self.layout

        # Active Material group
        layout.label(text="Active Material:")
        row = layout.row()
        row.operator("node.set_interpolation", text="Linear").interpolation_mode = 'Linear'
        row.operator("node.set_interpolation", text="Closest").interpolation_mode = 'Closest'
        row = layout.row()
        row.operator("node.set_interpolation", text="Cubic").interpolation_mode = 'Cubic'
        row.operator("node.set_interpolation", text="Smart").interpolation_mode = 'Smart'

        # Assets group
        layout.separator()
        layout.label(text="Assets:")
        row = layout.row()
        row.operator("node.set_interpolation_assets", text="Linear").interpolation_mode = 'Linear'
        row.operator("node.set_interpolation_assets", text="Closest").interpolation_mode = 'Closest'
        row = layout.row()
        row.operator("node.set_interpolation_assets", text="Cubic").interpolation_mode = 'Cubic'
        row.operator("node.set_interpolation_assets", text="Smart").interpolation_mode = 'Smart'

        # Global group
        layout.separator()
        layout.label(text="Global:")
        row = layout.row()
        row.operator("node.set_interpolation_global", text="Linear").interpolation_mode = 'Linear'
        row.operator("node.set_interpolation_global", text="Closest").interpolation_mode = 'Closest'
        row = layout.row()
        row.operator("node.set_interpolation_global", text="Cubic").interpolation_mode = 'Cubic'
        row.operator("node.set_interpolation_global", text="Smart").interpolation_mode = 'Smart'


# Registration
classes = [
    NODE_OT_set_interpolation,
    NODE_OT_set_interpolation_assets,
    NODE_OT_set_interpolation_global,
    NODE_PT_interpolation_panel,
]


def register():
    for cls in classes:
        bpy.utils.register_class(cls)


def unregister():
    for cls in classes:
        bpy.utils.unregister_class(cls)


if __name__ == "__main__":
    register()