import json
import sqlite3

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 now
from layercake.dynamodb import DynamoDBPersistenceLayer
from sqlite_utils import Database

from boto3clients import dynamodb_client
from config import (
    ENROLLMENT_TABLE,
    SQLITE_DATABASE,
    SQLITE_TABLE,
)

sqlite3.register_converter('json', json.loads)

logger = Logger(__name__)
enrollment_layer = DynamoDBPersistenceLayer(ENROLLMENT_TABLE, dynamodb_client)


class DeduplicationConflictError(Exception):
    def __init__(self, *args):
        super().__init__('Enrollment already exists')


@event_source(data_class=EventBridgeEvent)
@logger.inject_lambda_context
def lambda_handler(event: EventBridgeEvent, context: LambdaContext) -> bool:
    new_image = event.detail['new_image']
    now_ = now()
    course = _get_course(new_image['course']['id'])

    with enrollment_layer.transact_writer() as transact:
        transact.put(
            item={
                'id': new_image['id'],
                'sk': 'metadata#deduplication_window',
                'offset_days': 90,
                'created_at': now_,
            }
        )
        transact.put(
            item={
                'id': new_image['id'],
                'sk': 'metadata#course',
                'created_at': now_,
                'access_period': int(course['access_period']),
                'cert': course['cert'],
            }
        )

    return True


class CourseNotFoundError(Exception):
    def __init__(self, *args):
        super().__init__('Course not found')


def _get_course(course_id: str) -> dict:
    with sqlite3.connect(
        database=SQLITE_DATABASE, detect_types=sqlite3.PARSE_DECLTYPES
    ) as conn:
        db = Database(conn)
        rows = db[SQLITE_TABLE].rows_where(
            "json->>'$.metadata__betaeducacao_id' = ?", [course_id]
        )

        for row in rows:
            return row['json']

    raise CourseNotFoundError
