import os
import json
import config

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

# Fetch rows with file_size = 0
cursor.execute("SELECT id, media_id, media_url FROM media WHERE file_size = 0;")
results = cursor.fetchall()

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

update_data = []
for result in results:
    itemID = result[0]
    media_id = result[1]

    if not media_id:
        print(f"Media ID is null for ID {itemID}, 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 for ID {itemID}, skipping.")
        continue

    file_size = os.path.getsize(localFilePath)
    update_data.append({"id": itemID, "file_size": file_size})

# Save the results to a JSON file
output_file = "update_data.json"
with open(output_file, 'w') as f:
    json.dump(update_data, f, indent=4)

print(f"Saved {len(update_data)} updates to {output_file}.")
cursor.close()
db.close()