import os
import re


# Constants for the old and new plugin names
OLD_NAME = 'orphic-block-function'
NEW_NAME = 'orphic-ui'

OLD_NAME_CAPITALIZED = 'OrphicBlockFunction'
NEW_NAME_CAPITALIZED = 'OrphicUI'

OLD_CONSTANT_PREFIX = 'ORPHIC_PLUGIN_BLOCK_AND_FUNCTION'
NEW_CONSTANT_PREFIX = 'ORPHIC_PLUGIN_UI'

OLD_CLASS_PREFIX = 'Orphic_Block_Function'
NEW_CLASS_PREFIX = 'Orphic_UI'

OLD_SLUG = 'orphic-block-function'
NEW_SLUG = 'orphic-ui'


def rename_files_and_update_content(directory):
    total_files = sum([len(files) for _, _, files in os.walk(directory)])
    processed_files = 0

    for root, dirs, files in os.walk(directory):
        if '.git' in dirs:
            dirs.remove('.git')
        
        for file in files:
            old_path = os.path.join(root, file)
            
            # Condition to skip processing this file
            if file == 'rename_plugin.py':
                print(f"Skipping {file}")
                continue
            
            # Skip binary files or files with unusual encodings
            if is_binary_file(old_path):
                print(f"Skipping binary file: {old_path}")
                processed_files += 1
                progress = (processed_files / total_files) * 100
                print(f"✅ -> {progress:.2f}%\n")
                continue
            
            new_file = file.replace(OLD_NAME, NEW_NAME).replace(OLD_NAME.capitalize(), NEW_NAME.capitalize())
            new_path = os.path.join(root, new_file)
            
            if old_path != new_path:
                os.rename(old_path, new_path)
            
            # Update file content
            try:
                with open(new_path, 'r', encoding='utf-8') as f:
                    content = f.read()
                
                # Replace all occurrences, case-sensitive for constants, case-insensitive for others
                content = re.sub(OLD_CONSTANT_PREFIX, NEW_CONSTANT_PREFIX, content)
                content = re.sub(OLD_CLASS_PREFIX, NEW_CLASS_PREFIX, content, flags=re.IGNORECASE)
                content = re.sub(OLD_SLUG, NEW_SLUG, content, flags=re.IGNORECASE)
                content = re.sub(OLD_NAME, NEW_NAME, content, flags=re.IGNORECASE)
                content = re.sub(OLD_NAME_CAPITALIZED, NEW_NAME_CAPITALIZED, content)
                
                # Write updated content back to file
                with open(new_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                
                processed_files += 1
                progress = (processed_files / total_files) * 100
                print(f"🚀 Renamed and updated: {old_path}\n🚀 -> {new_path}\n✅ -> {progress:.2f}%\n")
            except UnicodeDecodeError:
                # If UTF-8 fails, try alternative approach or skip file
                try:
                    # Try with error handling
                    with open(new_path, 'r', encoding='utf-8', errors='replace') as f:
                        content = f.read()
                    
                    # Replace all occurrences
                    content = re.sub(OLD_CONSTANT_PREFIX, NEW_CONSTANT_PREFIX, content)
                    content = re.sub(OLD_CLASS_PREFIX, NEW_CLASS_PREFIX, content, flags=re.IGNORECASE)
                    content = re.sub(OLD_SLUG, NEW_SLUG, content, flags=re.IGNORECASE)
                    content = re.sub(OLD_NAME, NEW_NAME, content, flags=re.IGNORECASE)
                    content = re.sub(OLD_NAME_CAPITALIZED, NEW_NAME_CAPITALIZED, content)
                    
                    # Write updated content back to file
                    with open(new_path, 'w', encoding='utf-8') as f:
                        f.write(content)
                    
                    processed_files += 1
                    progress = (processed_files / total_files) * 100
                    print(f"🚀 Renamed and updated (with encoding fix): {old_path}\n🚀 -> {new_path}\n✅ -> {progress:.2f}%\n")
                except Exception as e:
                    print(f"⚠️ Could not process file due to encoding issues: {new_path}")
                    print(f"   Error: {str(e)}")
                    processed_files += 1
                    progress = (processed_files / total_files) * 100
                    print(f"✅ -> {progress:.2f}%\n")
            except Exception as e:
                print(f"⚠️ Error processing file: {new_path}")
                print(f"   Error: {str(e)}")
                processed_files += 1
                progress = (processed_files / total_files) * 100
                print(f"✅ -> {progress:.2f}%\n")
    
    print(f"Done 100% enjoy !")

def is_binary_file(file_path):
    """Check if file is binary."""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            f.read(1024)
        return False
    except UnicodeDecodeError:
        return True

# Use the current working directory as the plugin directory
plugin_directory = os.getcwd()
rename_files_and_update_content(plugin_directory)