from moviepy.editor import VideoFileClip
import json

def is_valid_video(file_path):
    try:
        with VideoFileClip(file_path) as video:
            return True
    except Exception as e:
        print(f"Invalid video {file_path}: {str(e)}")
        return False

def load_hashes(file_path):
    try:
        with open(file_path, 'r') as file:
            return json.load(file)
    except FileNotFoundError:
        return {}

def save_hashes(hashes, file_path):
    with open(file_path, 'w') as file:
        json.dump(hashes, file, indent=4)

def find_duplicates(video_hashes):
    hash_map = {}
    for video, v_hash in video_hashes:
        if v_hash in hash_map:
            hash_map[v_hash].append(video)
        else:
            hash_map[v_hash] = [video]

    duplicates = {h: vids for h, vids in hash_map.items() if len(vids) > 1}
    return duplicates

hashes = load_hashes('video_hashes.json')
for username, user_hashes in hashes.items():
    print(f"Checking for duplicates in '{username}' videos:")
    duplicates = find_duplicates(user_hashes)
    if duplicates:
        for dup_hash, dup_videos in duplicates.items():
            print(f"Duplicate hash: {dup_hash}")
            for vid in dup_videos:
                print(f" - {vid}")
    else:
        print("No duplicates found.")
