import os
import json
import re
import shutil

def sanitize_filename(filename):
    """Sanitize the filename to avoid spaces and special characters, and convert to lowercase."""
    sanitized = re.sub(r'[^a-z0-9_-]', '_', filename.lower())  # replace invalid characters with _
    return sanitized

def rename_files_and_update_json(json_file, folder_path, output_json_file):
    with open(json_file, 'r') as file:
        data = json.load(file)

    # Create a new dictionary to store updated file paths
    updated_data = data.copy()

    # Loop through each song in the "all" block
    for song in updated_data['all']:
        original_filename = song['filename']
        original_path = os.path.join(folder_path, original_filename)

        # Check if the file exists in the directory
        if os.path.exists(original_path):
            # Sanitize the new filename (using the title from the JSON data)
            new_filename = sanitize_filename(song['title']) + os.path.splitext(original_filename)[1]
            new_path = os.path.join(folder_path, new_filename)

            # Rename the file
            os.rename(original_path, new_path)

            # Update the filename in the JSON data to the new filename
            song['filename'] = new_filename

    # Write the updated JSON structure to a new file
    with open(output_json_file, 'w') as file:
        json.dump(updated_data, file, indent=4)

    print(f"Files have been renamed and the updated JSON has been saved to {output_json_file}")

# Example usage:
json_file = 'playlist.json'  # Path to the original JSON file
folder_path = './'  # Path to the folder containing the files
output_json_file = 'updated_playlist.json'  # Path to save the updated JSON file

rename_files_and_update_json(json_file, folder_path, output_json_file)
