from email.mime.application import MIMEApplication
from urllib.parse import urlparse

from aws_lambda_powertools import Logger
from aws_lambda_powertools.utilities.data_classes import EventBridgeEvent, event_source
from aws_lambda_powertools.utilities.typing import LambdaContext
from layercake.dateutils import fromisoformat
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair
from layercake.email_ import Message

from boto3clients import dynamodb_client, s3_client, sesv2_client
from config import EMAIL_SENDER, USER_TABLE

SUBJECT = (
    'Relatório de matrículas realizadas entre {start_period} e {end_period} na EDUSEG®'
)
REPLY_TO = ('Carolina Brand', 'carolina@somosbeta.com.br')
BCC = [
    'sergio@somosbeta.com.br',
    'carolina@somosbeta.com.br',
    'tiago@somosbeta.com.br',
]
MESSAGE = """
Oi, tudo bem?<br/><br/>

Em anexo você encontra o relatório das matrículas realizadas no período de
<strong>{start_period}</strong> a <strong>{end_period}</strong>.<br/><br/>

<a href="https://admin.saladeaula.digital/{org_id}/billing?start={start_query}&end={end_query}">
    📈 Clique aqui para ver mais detalhes do relatório
</a><br/><br/>

Qualquer dúvida, estamos à disposição.
"""

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


@event_source(data_class=EventBridgeEvent)
@logger.inject_lambda_context
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
    new_image = event.detail['new_image']
    # Key pattern `BILLING#ORG#{org_id}`
    *_, org_id = new_image['id'].split('#')
    # Key pattern `START#{start_period}#END#{v}
    _, start_period, _, end_period, *_ = new_image['sk'].split('#')

    emailmsg = Message(
        from_=EMAIL_SENDER,
        to=_get_admin_emails(org_id),
        reply_to=REPLY_TO,
        bcc=BCC,
        subject=SUBJECT.format(
            start_period=_locale_dateformat(start_period),
            end_period=_locale_dateformat(end_period),
        ),
    )
    emailmsg.add_alternative(
        MESSAGE.format(
            org_id=org_id,
            start_period=_locale_dateformat(start_period),
            end_period=_locale_dateformat(end_period),
            start_query=start_period,
            end_query=end_period,
        )
    )
    attachment = MIMEApplication(_get_file_bytes(new_image['s3_uri']))
    attachment.add_header(
        'Content-Disposition',
        'attachment',
        filename=f'{start_period}_{end_period}.pdf',
    )
    emailmsg.attach(attachment)

    try:
        sesv2_client.send_email(
            Content={
                'Raw': {
                    'Data': emailmsg.as_bytes(),
                },
            }
        )
        logger.info('Email sent')
    except Exception as exc:
        logger.exception(exc)
        return False
    else:
        return True


def _get_admin_emails(org_id: str) -> list[tuple[str, str]]:
    # Post-migration: rename `admins` to `ADMIN`
    r = user_layer.collection.query(KeyPair(org_id, 'admins'))
    return [(x['name'], x['email']) for x in r['items']]


def _get_file_bytes(s3_uri: str) -> bytes:
    parsed = urlparse(s3_uri)
    bucket = parsed.netloc
    key = parsed.path.lstrip('/')

    r = s3_client.get_object(Bucket=bucket, Key=key)
    return r['Body'].read()


def _locale_dateformat(s: str) -> str:
    dt = fromisoformat(s)
    if not dt:
        raise ValueError('Invalid date')
    return dt.strftime('%d/%m/%Y')
