import os
import shutil

def organize_files_by_month(source_directory):
    # Create a dictionary to map month numbers to their respective folders
    month_folders = {}

    # Iterate through each item in the source directory
    for item in os.listdir(source_directory):
        # Construct the full path to the item
        item_path = os.path.join(source_directory, item)

        # Check if the item is a directory and matches the expected date format (e.g., "0315")
        if os.path.isdir(item_path) and len(item) == 4 and item.isdigit():
            # Extract the month part from the folder name (first two digits)
            month = item[:2]

            # Create a folder for the month if it does not exist
            month_folder_path = os.path.join(source_directory, month)
            if month not in month_folders:
                if not os.path.exists(month_folder_path):
                    os.makedirs(month_folder_path)
                month_folders[month] = month_folder_path

            # Move all files from the day folder to the month folder, deleting Thumbs.db if found
            for file in os.listdir(item_path):
                file_path = os.path.join(item_path, file)
                if file == 'Thumbs.db':
                    os.remove(file_path)  # Delete Thumbs.db file
                    continue  # Skip to the next file

                # Generate a new destination path, checking for existing files or directories
                destination_path = os.path.join(month_folder_path, file)
                if os.path.exists(destination_path):
                    base, extension = os.path.splitext(file)
                    counter = 1
                    new_file = f"{base}_{counter}{extension}"
                    destination_path = os.path.join(month_folder_path, new_file)
                    while os.path.exists(destination_path):
                        counter += 1
                        new_file = f"{base}_{counter}{extension}"
                        destination_path = os.path.join(month_folder_path, new_file)

                shutil.move(file_path, destination_path)
            
            # Optionally, remove the now empty day folder
            os.rmdir(item_path)

# Example usage
source_directory = './2022'
organize_files_by_month(source_directory)
