from BunnyCDN.Storage import Storage
from datetime import datetime
import os, config, funcs
from PIL import Image

def dump_instagram(folder_path):
    for filename in os.listdir(folder_path):
        parts = filename.split('_')
        
        try:
            username = '_'.join(parts[:-2])  # Join all except last two
            timestamp = int(parts[-2])  # Second last is timestamp
            user_id = int(parts[-1].split('.')[0])  # Last part before extension is user_id
        except Exception as e:
            print(f"Invalid filename: {filename}. Error: {e}")
            continue
        
        filepath = os.path.join(folder_path, filename)

        mediatype = funcs.get_media_type(filename)
        post_type = funcs.determine_post_type(filepath, mediatype)

        UploadMedia(username=username, media_type=mediatype, filepath=filepath, post_type=post_type, timestamp=timestamp, user_id=user_id)


def UploadMedia(filepath, username, media_type='image', post_type='story', timestamp=None, user_id=None):
    if 'tero' in username:
        pass
    
    filename = os.path.basename(filepath)
    file_extension = os.path.splitext(filename)[1].lower()

    file_hash = funcs.calculate_file_hash(filepath)

    duration = funcs.get_video_duration(filepath) if media_type == 'video' else 0

    post_date = datetime.fromtimestamp(int(timestamp)) if timestamp else datetime.now()

    dirtype = funcs.determine_post_type(filepath, media_type)

    server_path = f'media/{dirtype}/{username}/{file_hash}{file_extension}'

    file_url = f"https://storysave.b-cdn.net/{server_path}"

    if file_hash in existing_files:
        print('Duplicate file detected. Removing...')
        os.remove(filepath)
        return True

    obj_storage.PutFile(filepath, server_path)

    if media_type == 'image':
        with Image.open(filepath) as img:
            width, height = img.size
    else:
        width, height = funcs.get_video_dimensions(filepath)

    query = "INSERT IGNORE INTO media (username, media_type, media_url, width, height, post_type, date, user_id, hash, filename, duration) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
    values = (username, media_type, file_url, width, height, post_type, post_date, user_id, file_hash, filename, duration)

    newCursor.execute(query, values)
    newDB.commit()
    print(f'[{newCursor.rowcount}] records updated. File {filename} uploaded to {file_url}')

    os.remove(filepath)

    return True
 

if __name__ == '__main__':
    print('Starting processing...')

    newDB, newCursor = config.gen_connection()

    obj_storage = Storage('345697f9-d9aa-4a6b-a5ec8bffc16d-ceaf-453e', 'storysave')

    newCursor.execute("SELECT hash FROM media WHERE platform='instagram' AND hash IS NOT NULL")
    existing_files = [image[0] for image in newCursor.fetchall()]

    dump_instagram('storysaver/missingdata/')

    print("Processing completed.")