import urllib.parse as urllib_parse
from email.utils import parseaddr

from aws_lambda_powertools import Logger
from aws_lambda_powertools.utilities.data_classes import SESEvent, event_source
from aws_lambda_powertools.utilities.typing import LambdaContext
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair, SortKey

from boto3clients import dynamodb_client
from config import USER_TABLE
from ses_utils import get_header_value

logger = Logger(__name__)
user_layer = DynamoDBPersistenceLayer(USER_TABLE, dynamodb_client)


@logger.inject_lambda_context
@event_source(data_class=SESEvent)
def lambda_handler(event: SESEvent, context: LambdaContext) -> dict:
    ses = event.record.ses
    to = urllib_parse.unquote(ses.receipt.recipients[0]).lower()
    name, email_from = parseaddr(get_header_value(ses.mail.headers, 'from'))

    org_id = user_layer.collection.get_item(
        KeyPair('email', SortKey(to, path_spec='user_id')),
        raise_on_error=False,
        default={},
    )

    if not org_id:
        return {'disposition': 'STOP_RULE_SET'}

    print(
        {
            'id': f'mailbox#org#{org_id}',
            'sk': ses.mail.message_id,
        }
    )

    return {'disposition': 'CONTINUE'}
