import os
import re

def fix_file(filepath):
    with open(filepath, 'r', encoding='utf-8') as f:
        content = f.read()

    # Split by class to be surgical
    classes = re.split(r'^(class\s+.*)$', content, flags=re.MULTILINE)
    
    new_content = []
    if len(classes) > 0:
        new_content.append(classes[0]) # Header
        
    for i in range(1, len(classes), 2):
        class_header = classes[i]
        class_body = classes[i+1] if i+1 < len(classes) else ""
        
        # Determine if it's a View or a Modal
        is_view = "disnake.ui.View" in class_header or "(disnake.ui.View)" in class_header or "super().__init__(timeout=" in class_body
        is_modal = "disnake.ui.Modal" in class_header or "(disnake.ui.Modal)" in class_header or "super().__init__(title=" in class_body
        
        if is_view:
            # Views use add_item
            class_body = class_body.replace("self.append_component(", "self.add_item(")
            # Ensure super().__init__ doesn't have components=[] if it's a view
            class_body = class_body.replace("super().__init__(components=[],", "super().__init__(")
            class_body = class_body.replace("super().__init__(components=[], ", "super().__init__(")
        
        if is_modal:
            # Modals use append_component
            class_body = class_body.replace("self.add_item(", "self.append_component(")
            # Modals MUST have components=[] in super().__init__ if not already there
            # (My previous sed might have added it correctly)
            pass

        new_content.append(class_header)
        new_content.append(class_body)

    final_content = "".join(new_content)
    if final_content != content:
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(final_content)
        return True
    return False

for root, dirs, files in os.walk('commandes'):
    for file in files:
        if file.endswith('.py'):
            path = os.path.join(root, file)
            if fix_file(path):
                print(f"Fixed {path}")
