from PIL import Image
import imagehash
import config
import cv2
import os

def generate_thumbnail_phash(filepath, hash_size=8):  # Set hash_size to 8
    cap = cv2.VideoCapture(filepath)
    ret, frame = cap.read()
    cap.release()

    if not ret:
        print(f"Error reading frame from {filepath}")
        return None

    # Resize frame to a standard size
    standard_size = (320, 240)
    resized_frame = cv2.resize(frame, standard_size, interpolation=cv2.INTER_AREA)

    # Convert OpenCV image (BGR) to PIL Image (RGB)
    image_rgb = cv2.cvtColor(resized_frame, cv2.COLOR_BGR2RGB)
    pil_image = Image.fromarray(image_rgb)

    # Compute pHash
    phash = imagehash.phash(pil_image, hash_size=hash_size)

    return phash

def are_phashes_duplicates(phash1, phash2, threshold=5):
    # Compute Hamming distance between the pHashes
    try:
        distance = phash1 - phash2
    except TypeError as e:
        print(f"Error comparing pHashes: {e}")
        return False

    return distance <= threshold

def get_media_by_phash(phash, username, existing_medias, threshold=5):
    for media in existing_medias:
        existing_phash_str = media[1]
        existing_username = media[2]
        if existing_username != username:
            continue

        # Convert stored phash string to ImageHash object
        existing_phash = imagehash.hex_to_hash(existing_phash_str)

        if are_phashes_duplicates(phash, existing_phash, threshold=threshold):
            return media
    return None

# Database connection
db, cursor = config.gen_connection()

# Directory containing user videos
directory = 'check_if_exists'

# Fetch existing videos with pHashes
cursor.execute("SELECT id, phash, username FROM media WHERE media_type = %s AND phash IS NOT NULL", ['video'])
existing_medias = cursor.fetchall()

users = os.listdir(directory)  # Assuming 'check_if_exists' contains user videos
for username in users:
    user_videos_path = os.path.join(directory, username)
    if not os.path.isdir(user_videos_path):
        continue

    videos = [video for video in os.listdir(user_videos_path) if video.endswith(('.mp4', '.avi', '.mov'))]
    for video in videos:
        print(f'Processing {video}...')
        filepath = os.path.join(user_videos_path, video)

        phash = generate_thumbnail_phash(filepath, hash_size=8)  # Use hash_size=8
        if phash is None:
            continue

        phash_str = str(phash)

        duplicate_media = get_media_by_phash(phash, username, existing_medias, threshold=5)
        if duplicate_media:
            print(f'Duplicate url found: https://altpins.com/pin/{duplicate_media[0]}')
            print(f'Duplicate video path: {filepath}')
            newpath = filepath.replace(directory, 'duplicates')
            os.makedirs(os.path.dirname(newpath), exist_ok=True)
            os.rename(filepath, newpath)
            print(f'Moved {video} to duplicates/')