from uuid import uuid4

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.dynamodb import DynamoDBPersistenceLayer, SortKey, TransactKey

from boto3clients import dynamodb_client
from config import ENROLLMENT_TABLE
from enrollment import Course, Enrollment, Kind, LinkedEntity, User, enroll

logger = Logger(__name__)
dyn = DynamoDBPersistenceLayer(ENROLLMENT_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']
    metadata = dyn.collection.get_items(
        TransactKey(new_image['id'])
        + SortKey(
            sk='METADATA#SUBSCRIPTION_COVERED',
            rename_key='subscription',
        )
        + SortKey(
            sk='METADATA#DEDUPLICATION_WINDOW',
            path_spec='offset_days',
            rename_key='dedup_window_offset_days',
        )
        + SortKey(
            sk='ORG',
            rename_key='org',
        ),
        flatten_top=False,
    )
    user = User.model_validate(new_image['user'])
    course = Course.model_validate(new_image['course'])
    subscription = metadata['subscription'] if 'subscription' in metadata else None
    offset_days = metadata.get('dedup_window_offset_days', None)
    enrollment = Enrollment(
        id=uuid4(),
        course=course,
        user=user,
    )

    return enroll(
        enrollment,
        org=metadata.get('org', None),
        subscription=subscription,
        # Transfer the deduplication window if it exists
        deduplication_window={'offset_days': offset_days} if offset_days else None,
        linked_entities=frozenset(
            {
                LinkedEntity(
                    id=new_image['id'],
                    kind=Kind.ENROLLMENT,
                ),
            },
        ),
        persistence_layer=dyn,
    )
