import config, os, json
from PIL import Image
import imagehash

def find_file(filename, directory):
    filename = filename.lower().split('.')[0]
    for root, dirs, files in os.walk(directory):
        for file in files:
            if filename in file:
                return os.path.join(root, file)
    return None

def generate_phash(image_path):
    image = Image.open(image_path)
    return str(imagehash.phash(image))

count = 0

cacheDir = 'sorted'
dataPath = 'pins.json'

os.makedirs(cacheDir, exist_ok=True)

medias = json.load(open(dataPath))

for item in medias:
    count += 1

    filepath = item['filepath']
    if os.path.exists(filepath):
        continue
    
    newfilepath = find_file(os.path.basename(filepath), cacheDir)
    if newfilepath:
        print(f"Found file {newfilepath} for {filepath}")
        item['filepath'] = newfilepath
        
        
with open(dataPath, 'w') as f:
    json.dump(medias, f)