import json, os
from videohash import VideoHash
from moviepy.editor import VideoFileClip

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)

hashes = load_hashes('video_hashes.json')
video_directory = 'STORAGE'

for username in os.listdir(video_directory):
    user_dir = os.path.join(video_directory, username)
    if not os.path.isdir(user_dir):
        continue

    for video_file in os.listdir(user_dir):
        video_path = os.path.join(user_dir, video_file)
        if not video_file.endswith(('.mp4', '.mkv', '.avi')) or not is_valid_video(video_path):
            continue

        if username in hashes and any(v[0] == video_file for v in hashes[username]):
            continue

        try:
            video_hash = VideoHash(path=video_path)
            if username in hashes:
                hashes[username].append((video_file, video_hash.hash))
            else:
                hashes[username] = [(video_file, video_hash.hash)]
        except Exception as e:
            print(f"Error processing {video_file}: {str(e)}")

save_hashes(hashes, 'video_hashes.json')
