from decimal import Decimal
from http import HTTPStatus
from typing import Any

from aws_lambda_powertools import Logger, Tracer
from aws_lambda_powertools.event_handler.api_gateway import (
    APIGatewayHttpResolver,
    Response,
)
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.utilities.typing import LambdaContext
from layercake.dynamodb import DynamoDBPersistenceLayer, KeyPair, SortKey

from boto3clients import dynamodb_client
from config import ENROLLMENT_TABLE
from enrollment import EnrollmentNotFoundError, set_score, update_progress

logger = Logger(__name__)
tracer = Tracer()
app = APIGatewayHttpResolver(enable_validation=True)
dyn = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)


@app.post('/')
@tracer.capture_method
def postback():
    json_body = app.current_event.json_body

    event_name = json_body['event_name']
    score = round(Decimal(json_body['APROVEITAMENTO']), 2)
    progress = round(Decimal(json_body['ANDAMENTO']), 2)
    enrollment_id = dyn.collection.get_item(
        KeyPair(
            # Post-migration: uncomment the following line
            # pk='KONVIVA',
            pk='konviva',
            sk=SortKey(
                json_body['ID_MATRICULA'],
                path_spec='enrollment_id',
            ),
        ),
        exc_cls=EnrollmentNotFoundError,
    )

    # Make sure webhooks send the correct event names
    match event_name:
        case 'UPDATING':
            update_progress(
                enrollment_id,
                progress,
                dynamodb_persistence_layer=dyn,
            )
        case 'COMPLETED':
            set_score(
                enrollment_id,
                score,
                progress,
                dynamodb_persistence_layer=dyn,
            )

    return Response(status_code=HTTPStatus.NO_CONTENT)


@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_HTTP)
@tracer.capture_lambda_handler
def lambda_handler(
    event: dict[str, Any],
    context: LambdaContext,
) -> dict[str, Any]:
    return app.resolve(event, context)
