import config
from funcs import generate_phash

count = 0

storage = config.get_storage()

db, cursor = config.gen_connection()

generate_for = 'media_url'
media_type = 'image'

cursor.execute(f"SELECT id, {generate_for} FROM media WHERE media_type = %s AND phash IS NULL;", [media_type])
medias = cursor.fetchall()

for item in medias:
    count += 1
    
    itemID = item[0]
    media_url = item[1]

    server_path = media_url.replace('https://storysave.b-cdn.net/', '').replace('\\', '/')
    filepath = storage.DownloadFile(server_path, 'temp')
    if not filepath:
        print(f"Error downloading {server_path}")
        continue
    
    phash = generate_phash(filepath)
    if not phash:
        print(f"Error generating pHash for {filepath}")
        continue

    cursor.execute("UPDATE media SET phash = %s WHERE id = %s", [phash, itemID])
    db.commit()
    
    print(f"[{cursor.rowcount}] Processed {count}/{len(medias)}: with pHash {phash}")