import os
import cloudinary
from cloudinary import uploader, api

# Configure Cloudinary with your credentials
cloudinary.config(

    #cloud_name='your_cloud_name',
    cloud_name='df667rfp2',
    #api_key='your_api_key',
    api_key='843839891244491',
    #api_secret='your_api_secret'
    api_secret='GUjP1I7lpjrig5Z7IXOF0WDzOyo'
)

local_folder_path = 'public/uploads'
cloudinary_folder_path = 'public/uploads'  # Change this to your Cloudinary folder path

def upload_folder(local_folder, cloudinary_folder):
    # Get the list of local files and folders
    local_items = os.listdir(local_folder)

    # Get the list of Cloudinary files and folders

    #cloudinary_items = api.sub_folders(cloudinary_folder)['folders']
    cloudinary_items = api.subfolders(cloudinary_folder)['folders']

    # Upload missing files and create missing folders on Cloudinary
    for item in local_items:
        item_path = os.path.join(local_folder, item)

        if os.path.isfile(item_path):
            # Check if the file exists on Cloudinary
            cloudinary_file_path = os.path.join(cloudinary_folder, item)
            if cloudinary_file_path not in cloudinary_items:
                upload_file(item_path, cloudinary_file_path)
        elif os.path.isdir(item_path):
            # Check if the folder exists on Cloudinary
            cloudinary_sub_folder_path = os.path.join(cloudinary_folder, item)
            if cloudinary_sub_folder_path not in cloudinary_items:
                create_folder(cloudinary_sub_folder_path)
                upload_folder(item_path, cloudinary_sub_folder_path)

def upload_file(local_path, cloudinary_path):
    #print(f'Uploading {local_path} to {cloudinary_path}')
    #uploader.upload(local_path, folder=cloudinary_path)
    # Use os.path.basename to get the filename without the path
    public_id = os.path.basename(local_path)

    

    # Combine the cloudinary_path and public_id to create the full public_id
   
    #full_public_id = os.path.join(cloudinary_path, public_id)
    full_public_id = os.path.join(cloudinary_path)

    print(f'Uploading {local_path} to {full_public_id}')
    
    try:

        uploader.upload(local_path, public_id=full_public_id)
        #uploader.upload(local_path)
    except cloudinary.exceptions.Error as e:
        print(f'Error uploading file: {e}')


def create_folder(cloudinary_path):
    print(f'Creating folder {cloudinary_path} on Cloudinary')
    api.create_folder(cloudinary_path)

# Start the recursive upload process
upload_folder(local_folder_path, cloudinary_folder_path)

