import os
import shutil
import hashlib

def clean_empty_folders(directory):
    for foldername, subfolders, filenames in os.walk(directory, topdown=False):
        for subfolder in subfolders:
            folder_path = os.path.join(foldername, subfolder)
            if not os.listdir(folder_path):
                os.rmdir(folder_path)
                print(f"Removed empty folder: {folder_path}")

def calculate_file_hash(file_path, hash_func='sha256'):
    h = hashlib.new(hash_func)
    with open(file_path, 'rb') as file:
        chunk = file.read(8192)
        while chunk:
            h.update(chunk)
            chunk = file.read(8192)
    return h.hexdigest()

def get_media_type(filename):
    extensions = {
        '.jpg': 'image', '.jpeg': 'image', '.webp': 'image', '.png': 'image', '.gif': 'image',
        '.mp4': 'video', '.mov': 'video'
    }
    for ext, media_type in extensions.items():
        if filename.lower().endswith(ext):
            return media_type
    return None

def move_files(source_root, destination_root):
    for root, dirs, files in os.walk(source_root):
        for file in files:
            if "~" in file or 'FB_IMG' in file or 's instagram' in file:
                username = file.split("'")[0]
                source_path = os.path.join(root, file)
                rel_path = os.path.relpath(root, source_root)
                destination_path = os.path.join(destination_root, username, rel_path)

                if not os.path.exists(destination_path):
                    os.makedirs(destination_path)

                shutil.move(source_path, os.path.join(destination_path, file))
                print(f"Moved {file} to {destination_path}")

if __name__ == '__main__':
    print('Starting processing...')
    source_directory = 'StorySave_Sort/Sort/StorySave'
    destination_directory = 'StorySave_Sort/Final/Stories'
    move_files(source_directory, destination_directory)
    clean_empty_folders(source_directory)
    print("Processing completed.")
