import json
import boto3
import os
import requests


def lambda_handler(event, context):
    """
    Send an alert of the AWS Macie findings to Discord
    """

    # Grab the findings that have been generated by Macie 
    client = boto3.client('macie2')
    finding_ids = client.list_findings()
    
    # Creating strings to store the different classifications of findings
    high_str = "High: \n"
    medium_str = "Medium: \n" 
    low_str = "Low: \n"
    other_str = "Other: \n"

    # Count to keep track of the findings limited to 10 (arbitrary) based on max limit of Discord
    count=0
    
    # Goes through the findings and classfies findings based on severity
    for finding in finding_ids['findingIds']:
        macie_finding = client.get_findings(findingIds=['finding'])

        # Exit the for loop if we have ten findings, responders will be encouraged to check the console
        if count==10:
            other_str=other_str+"... see the console for more findings\n"
            break
        
        # Classifying the findings and creating strings
        if (macie_finding['findings'] == []):
            other_str=other_str+"\tId: "+finding+"\n"
        elif (macie_finding['severity']['description'] == "High"):
            high_str=high_str+"\tId: "+finding+"\n"
            high_str=high_str+"\tLocation: "+(macie_finding['resourceAffected']['s3Bucket.arn'])+"\n"
        elif (macie_finding['severity']['description'] == "Medium"):
            medium_medium=high_str+"\tId: "+finding+"\n"
            medium_medium=high_str+"\tLocation: "+(macie_finding['resourceAffected']['s3Bucket.arn'])+"\n"
        elif (macie_finding['severity']['description'] == "Low"):
            low_str=low_str+"\tId: "+finding+"\n"
            low_str=low_str+"\tLocation: "+(macie_finding['resourceAffected']['s3Bucket.arn'])+"\n"
        count += 1
    
    # Determines the environment and sends to the appropriate discord channel
    is_dev=os.environ["IS_DEV"]
    if is_dev == "1":
        webhook_url = os.environ["DISCORD_ALERTS_CHANNEL_WEBHOOK"]
    else:
        webhook_url = os.environ["DISCORD_DEV_ALERTS_CHANNEL_WEBHOOK"]

    # Added all the different finding types together
    macie_response=high_str+medium_str+low_str+other_str

    # Below is the response that will be sent to Discord
    content=f"I am the Macie Poller bot. :robot:\n```{macie_response}```\nFor more information check Macie in the console."

    # Send the response to the right Discord webhook
    response = requests.post(webhook_url, data={"content": content})
    return response
