from uuid import uuid4
import uuid
import os

def is_valid_uuid(uuid_to_test, version=4):
    try:
        uuid_obj = uuid.UUID(uuid_to_test, version=version)
    except ValueError:
        return False

    return str(uuid_obj) == uuid_to_test

source_dir = 'tiktoks/'
processed_dir = 'processed_tiktoks'

os.makedirs(processed_dir, exist_ok=True)

users = os.listdir(source_dir)

for user in users:
    user_dir = os.path.join(source_dir, user)
    if not os.path.isdir(user_dir):
        print(f"Skipping {user}")
        continue

    for file in os.listdir(user_dir):
        filename = os.path.splitext(file)[0]
        filepath = os.path.join(user_dir, file)
        file_ext = os.path.splitext(file)[1]

        tiktok_id = str(uuid4())
        username = user

        if is_valid_uuid(filename):
            title = ''
            tiktok_id = filename
        elif 'masstik' in file or 'masstiktok' in file:
            data = file.split('_')
            title = filename.split('_')[-1]
        else:
            title = filename
        
        
        print("="*100)
        title = title.encode('utf-8', 'ignore').decode('utf-8')
        print(f"Username: {username}\nTitle: {title}")
        
        new_filename = f"{username}~{title}~{tiktok_id}{file_ext}"
        new_filepath = os.path.join(processed_dir, username, new_filename)
        
        os.makedirs(os.path.dirname(new_filepath), exist_ok=True)
        if not os.path.exists(new_filepath):
            os.rename(filepath, new_filepath)
            print(f"Renamed {file} to {new_filepath}")
        else:
            print("File with the same name already exists. Renaming aborted.")

        print("="*100)