import os
import re

# --- CONFIGURATION ---
# The root folder containing your speaker subfolders
TARGET_DIR = "/root/tts_arena/audios/parler" 
DRY_RUN = True  # Set to False to apply changes

def rename_files():
    # Regex to match: row_{number}_{Anything}.wav
    # Example: row_0_Adam.wav -> matches
    # Example: row_105_Sarah.wav -> matches
    filename_pattern = re.compile(r"^row_(\d+)_.*male\.wav$")
    
    renamed_count = 0

    print(f"Scanning directory: {TARGET_DIR} ...")
    print(f"Mode: {'DRY RUN (No changes)' if DRY_RUN else 'LIVE (Renaming files)'}\n")

    for root, dirs, files in os.walk(TARGET_DIR):
        for filename in files:
            match = filename_pattern.match(filename)
            if match:
                # Group 1 is the index (e.g., "0" or "105")
                index = match.group(1)
                
                # Construct new filename
                new_filename = f"row_{index}.wav"
                
                old_path = os.path.join(root, filename)
                new_path = os.path.join(root, new_filename)
                
                if DRY_RUN:
                    print(f"[Would Rename] {filename}  ->  {new_filename}")
                else:
                    try:
                        os.rename(old_path, new_path)
                        # print(f"[Renamed] {filename} -> {new_filename}") # Optional: less spam
                    except OSError as e:
                        print(f"❌ Error renaming {filename}: {e}")
                
                renamed_count += 1

    print("-" * 30)
    if DRY_RUN:
        print(f"Found {renamed_count} files to rename. Change DRY_RUN = False to apply.")
    else:
        print(f"Successfully renamed {renamed_count} files.")

if __name__ == "__main__":
    if not os.path.exists(TARGET_DIR):
        print(f"Error: Directory '{TARGET_DIR}' not found.")
    else:
        rename_files()