import config, os
from funcs import generate_phash

db, cursor = config.gen_connection()

cursor.execute("SELECT id, media_id, media_url FROM media WHERE media_type = 'image' AND phash = 0;")
results = cursor.fetchall()

count = 0
cacheDir = 'cache'
os.makedirs(cacheDir, exist_ok=True)
print(f"Found {len(results)} files to process.")


for result in results:
    count += 1
    itemID = result[0]
    mediaID = result[1]
    if not mediaID:
        print(f"Media ID is null, skipping.")
        continue
    mediaURL = result[2]
    
    serverPath = mediaURL.replace("https://storysave.b-cdn.net/", '').replace('//', '/').replace('\\', '/')
    localFilePath = os.path.join(cacheDir, os.path.basename(serverPath))
    
    if not os.path.exists(localFilePath):
        print(f"File {localFilePath} does not exist, skipping.")
        continue
    
    phash = generate_phash(localFilePath)
    if not phash:
        print(f"Error generating pHash for {localFilePath}, skipping.")
        continue
    
    cursor.execute("UPDATE media SET phash = %s WHERE id = %s", (phash, itemID))
    db.commit()
    
    print(f"Processed {count}/{len(results)}: {mediaID} with pHash {phash}")