#!/usr/bin/env python3
"""
MindfulLens Watermark Verifier.
Extracts the 32-bit hash from an image and compares it with known buyer IDs.
"""
import argparse
import hashlib
import numpy as np
from PIL import Image

def extract_hash(image_path: str) -> int:
    with Image.open(image_path) as im:
        arr = np.array(im)
    
    h = 0
    for i in range(32):
        y = (i // 8) + 2
        x = (i % 8) + 2
        
        # Extract LSB from Green channel
        bit = arr[y, x, 1] & 1
        h |= (bit << i)
        
    return h

def verify(image_path: str, buyer_emails: list):
    found_hash = extract_hash(image_path)
    print(f"Extracted Hash: {found_hash:08X}")
    
    for email in buyer_emails:
        target_hash = int(hashlib.md5(email.encode()).hexdigest()[:8], 16)
        if target_hash == found_hash:
            print(f"MATCH FOUND: {email}")
            return email
            
    print("NO MATCH FOUND in the provided list.")
    return None

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("image", help="Path to the image to verify")
    parser.add_argument("--emails", nargs="+", help="List of emails to check against")
    args = parser.parse_args()
    
    if args.emails:
        verify(args.image, args.emails)
    else:
        print(f"Extracted Hash: {extract_hash(args.image):08X}")
        print("Provide --emails to find a match.")
