from typing import Optional
from typing import Dict


def parse_encryption(bucket: str, encryption: Optional[Dict]) -> Optional[Dict]:
    """ Parses the S3 default encryption object and returns a dict of the relevant data """
    # Encryption object JSON looks like:
    # {
    #     'ServerSideEncryptionConfiguration': {
    #         'Rules': [
    #             {
    #                 'ApplyServerSideEncryptionByDefault': {
    #                     'SSEAlgorithm': 'AES256'|'aws:kms',
    #                     'KMSMasterKeyID': 'string'
    #                 },
    #                 'BucketKeyEnabled': True|False
    #             },
    #         ]
    #     }
    # }
    if encryption is None:
        return None
    _ssec = encryption.get('ServerSideEncryptionConfiguration', {})
    # Rules is a list, but only one rule ever exists
    try:
        rule = _ssec.get('Rules', []).pop()
    except IndexError:
        return None
    algorithm = rule.get('ApplyServerSideEncryptionByDefault', {}).get('SSEAlgorithm')
    if not algorithm:
        return None
    return {
        "bucket": bucket,
        "default_encryption": True,
        "encryption_algorithm": algorithm,
        "encryption_key_id": rule.get("ApplyServerSideEncryptionByDefault", {}).get('KMSMasterKeyID'),
        "bucket_key_enabled": rule.get('BucketKeyEnabled'),
    }