import os
import re

def downgrade_glsl_version(directory):
    # Target standard Minecraft shader file extensions
    extensions = ('.vsh', '.fsh', '.gsh', '.csh', '.glsl', '.inc')
    updated_count = 0
    
    print(f"Scanning directory: {os.path.abspath(directory)}\n")
    
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith(extensions):
                filepath = os.path.join(root, file)
                
                try:
                    with open(filepath, 'r', encoding='utf-8') as f:
                        content = f.read()
                    
                    # Regex to find "#version 460" or "#version 460 compatibility" 
                    # and replace it with "#version 410 compatibility"
                    # It handles variations in spacing automatically
                    new_content, count = re.subn(
                        r'^#version\s+460(?:\s+compatibility)?', 
                        '#version 410 compatibility', 
                        content, 
                        flags=re.MULTILINE
                    )
                    
                    if count > 0:
                        with open(filepath, 'w', encoding='utf-8') as f:
                            f.write(new_content)
                        print(f"Updated ({count} occurrence/s): {os.path.relpath(filepath, directory)}")
                        updated_count += 1
                        
                except Exception as e:
                    print(f"Error reading {file}: {e}")

    print(f"\nFinished! Updated {updated_count} file(s).")

if __name__ == "__main__":
    # You can hardcode your shader pack path here or press Enter to run it in the current folder
    target_dir = input("Enter the path to your shader folder (or press Enter for current directory): ").strip()
    
    if not target_dir:
        target_dir = '.'
        
    downgrade_glsl_version(target_dir)