import bpy
import os

def set_smart_interpolation_in_nodes(nodes, context_name, context_type):
    """
    Recursively set interpolation to Smart for Image Texture and Environment Texture nodes.
    """
    for node in nodes:
        if node.type == 'TEX_IMAGE':  # Image Texture
            node.interpolation = 'Smart'
            print(f"Set Image Texture interpolation to Smart in {context_type}: {context_name}")
        elif node.type == 'TEX_ENVIRONMENT':  # Environment Texture
            node.interpolation = 'Smart'
            print(f"Set Environment Texture interpolation to Smart in {context_type}: {context_name}")
        
        if node.type == 'GROUP' and hasattr(node, 'node_tree') and node.node_tree:
            set_smart_interpolation_in_nodes(node.node_tree.nodes, context_name, context_type)

def set_smart_interpolation():
    # Check materials
    for mat in bpy.data.materials:
        if mat.use_nodes and mat.node_tree:
            set_smart_interpolation_in_nodes(mat.node_tree.nodes, mat.name, "material")
    
    # Check all worlds
    for world in bpy.data.worlds:
        if world.use_nodes and world.node_tree:
            set_smart_interpolation_in_nodes(world.node_tree.nodes, world.name, "world")

def process_blend_file(filepath):
    bpy.ops.wm.open_mainfile(filepath=filepath)
    set_smart_interpolation()
    bpy.ops.wm.save_mainfile(filepath=filepath)

def process_directory(directory):
    blend_files = []
    # Collect all .blend files first
    for subdir, _, files in os.walk(directory):
        for file in files:
            if file.lower().endswith(".blend"):  # Case-insensitive check
                full_path = os.path.join(subdir, file)
                blend_files.append(full_path)
                print(f"Found .blend file: {full_path} ✅")
    
    total_files = len(blend_files)
    if total_files == 0:
        print("No .blend files found! 😕")
        return
    
    # Process files with progress
    for i, filepath in enumerate(blend_files, 1):
        print(f"Processing file {i}/{total_files}: {filepath}")
        process_blend_file(filepath)
    print(f"Done! Processed {total_files} files. 🎉")

# Hardcode the directory with corrected path
root_dir = "S:\\Your\\Blend\\Files"  # Path to blend files/folders (it searches subfolders)
print("Starting processing... 🚀")
process_directory(root_dir)