import base64
import gzip
import json
import os
from io import BytesIO

import boto3

sns_client = boto3.client('sns')

def lambda_handler(event, context):
    awslogs_dict = event.get('awslogs') 
    base64_data = awslogs_dict.get('data')
    try:
        decoded_gzip_data = base64.b64decode(base64_data)
    except Exception as e:
        raise e
    log_event_str = gzip.GzipFile(fileobj=BytesIO(decoded_gzip_data)).read()
    log_event = json.loads(log_event_str)

    publish_message = {
        'Subject': f'Detect Error(or Warning) in {log_event.get("logGroup")}',
        'Message': '\n'.join([log.get('message') for log in log_event.get('logEvents')]),
        'TopicArn': os.environ.get('SNS_TOPIC_ARN')
    }
    
    print(publish_message)
    
    sns_client.publish(**publish_message)
