import boto3
import os
import uuid


def s3_upload(bytes_or_file_like, filename=None, file_extension=None):
    '''
    @bytes_or_file_like: bytes(), open('filepath') or io.StringIO('')
    '''
    if filename is None:
        filename = uuid.uuid4().hex
        if file_extension:
            filename += file_extension

    s3 = boto3.resource('s3',
        aws_access_key_id=os.getenv('AWS_ACCESS_KEY_ID'),
        aws_secret_access_key=os.getenv('AWS_SECRET_ACCESS_KEY'))

    # Default: test environment
    bucket_name = os.getenv('AWS_S3_BUCKET', 'sunpower-test-dgplatform-spectrum')

    # Assuming bucket already exists
    s3.Bucket(bucket_name).put_object(Key=filename, Body=bytes_or_file_like.read(), ACL='public-read')
    file_url = 'https://s3.amazonaws.com/{}/{}'.format(bucket_name, filename)
    print('Uploaded filename {} to S3: {}'.format(filename, file_url))
    return file_url
