# import os
# import re

# # --- CONFIGURATION ---
# # The root folder containing your speaker subfolders
# TARGET_DIR = "/root/tts_arena/audios/parler" 
# DRY_RUN = False  # 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"^(\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()

import os
import re

# --- CONFIGURATION ---
TARGET_DIR = "/root/tts_arena/audios/parler" 
DRY_RUN = False  # Set to True first to verify, then False to apply

def rename_files():
    # Regex to match current state: row_{number}.wav
    filename_pattern = re.compile(r"^row_(\d+)\.wav$")
    
    # We collect matches in a list first to sort them safely
    # (row_1 needs to move to row_0 BEFORE row_2 moves to row_1)
    files_to_rename = []

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

    # 1. Collect all valid files
    for root, dirs, files in os.walk(TARGET_DIR):
        for filename in files:
            match = filename_pattern.match(filename)
            if match:
                current_index = int(match.group(1))
                
                # Store tuple: (current_index, filename, root_path)
                files_to_rename.append({
                    "index": current_index,
                    "filename": filename,
                    "root": root
                })

    # 2. Sort by index ASCENDING (Low to High)
    # This ensures row_1 moves out of the way before row_2 tries to take its spot
    files_to_rename.sort(key=lambda x: x["index"])

    renamed_count = 0

    # 3. Process renames
    for item in files_to_rename:
        current_index = item["index"]
        filename = item["filename"]
        root = item["root"]

        # Reduce index by 1
        new_index = current_index - 1
        
        # Optional: Prevent negative numbers if row_0 already exists and you run this accidentally
        if new_index < 0:
            print(f"⚠️ Skipping {filename}: New index would be negative ({new_index}).")
            continue

        new_filename = f"row_{new_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}") 
            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 shifted indices for {renamed_count} files.")

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