from BunnyCDN.Storage import Storage
import os, config, requests
from moviepy.editor import VideoFileClip

def get_media_type(filename):
    image_extensions = {".jpg", ".jpeg", ".png", ".gif", ".webp"}
    video_extensions = {".mp4", ".mov"}
    extension = os.path.splitext(filename.lower())[1]
    if extension in image_extensions:
        return 'image'
    elif extension in video_extensions:
        return 'video'
    else:
        return 'unknown'

def determine_post_type(media_type):
    # Assuming the post type is directly based on media type.
    return media_type

def get_video_dimensions(filepath):
    with VideoFileClip(filepath) as clip:
        width, height = clip.size
    return width, height

def download_file(url):
    local_filename = url.split('/')[-1]
    # Note: Stream=True to avoid loading the whole file into memory
    with requests.get(url, stream=True) as r:
        r.raise_for_status()
        with open(local_filename, 'wb') as f:
            for chunk in r.iter_content(chunk_size=8192):
                f.write(chunk)
    return local_filename

if __name__ == '__main__':
    newDB, newCursor = config.gen_connection()
    obj_storage = Storage('345697f9-d9aa-4a6b-a5ec8bffc16d-ceaf-453e', 'storysave')
    
    posts = open('fucked', 'r')
    
    for item in posts:
        username, url = item.strip().split('~')
        media_id = url.split('/')[-1].split('.')[0]
        media_type = get_media_type(url)

        query = "INSERT IGNORE INTO media (username, media_type, platform, media_url) VALUES (%s, %s, %s, %s)"
        values = (username, media_type, 'facebook', url)

        try:
            newCursor.execute(query, values)
            newDB.commit()
            print(f'[{newCursor.rowcount}] records updated.{url}')
        except Exception as e:
            print(f"Database error: {e}")

    posts.close()
