import config, os, threading, queue
from funcs import generate_phash

# Initialize database connection
db, cursor = config.gen_connection()

# Query the media table for unprocessed images
cursor.execute("SELECT id, media_id, media_url FROM media WHERE media_type = 'image' AND phash = '0';")
results = cursor.fetchall()

# Setup cache directory
cacheDir = 'cache'
os.makedirs(cacheDir, exist_ok=True)

print(f"Found {len(results)} files to process.")

# Thread-safe queue for processed media
processed_media_queue = queue.Queue()

def process_media():
    """Thread function to update database with processed pHash values."""
    while True:
        try:
            item = processed_media_queue.get(timeout=10)  # Timeout prevents infinite blocking
            if item is None:  # Sentinel value to exit the loop
                break
            
            itemID, phash = item
            cursor.execute("UPDATE media SET phash = %s WHERE id = %s", (phash, itemID))
            db.commit()
            print(f"Updated database for ID {itemID} with pHash {phash}.")
        except queue.Empty:
            continue

# Start the database update thread
update_thread = threading.Thread(target=process_media, daemon=True)
update_thread.start()

# Main processing loop for generating pHash
count = 0

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

    # Add the processed media to the queue
    processed_media_queue.put((itemID, phash))
    print(f"Processed {count}/{len(results)}: {mediaID} with pHash {phash}")

# Signal the update thread to stop
processed_media_queue.put(None)

# Wait for the update thread to finish
update_thread.join()

print("Processing completed.")
