import os
import config
import cv2
from funcs import generate_phash
from BunnyCDN.Storage import Storage

db, cursor = config.gen_connection()
obj_storage = Storage('345697f9-d9aa-4a6b-a5ec8bffc16d-ceaf-453e', 'storysave')

cursor.execute("SELECT id, media_id, media_url FROM media WHERE media_type = 'video' 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]
    media_id = result[1]
    
    if not media_id:
        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
    
    thumbPath = f'temp/{media_id}.jpg'
    cap = cv2.VideoCapture(localFilePath)
    ret, frame = cap.read()
    cv2.imwrite(thumbPath, frame)
    cap.release()
    phash = generate_phash(thumbPath)
    os.remove(thumbPath)
    
    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)}: {media_id} with pHash {phash}")