"""
_____________________________________________________________________.

:PROJECT: LARAsuite

*lara_django_sequence semantics metadata handler *

:details: lara_django_sequence semantics metadata handler.
:authors: mark doerr <mark.doerr@uni-greifswald.de>

________________________________________________________________________
"""

from __future__ import annotations

import logging
from typing import TYPE_CHECKING, Any

from lara_django_base.tasks import semantic_data_to_triplestore

if TYPE_CHECKING:
    from django.db import models

logger = logging.getLogger("lara_semantics")


data_model_map = {
    "Data": "Data",
}


def get_semantic_data_map(instance: models.Model) -> dict[str, Any]:
    """
    Return dictionary with semantic mapping of the data.

    TODO: add more semantic mapping
    """
    return {
        "data_id": str(instance.data_id),  # hasLaraID
        "name_full": instance.name_full,
        "hasNamespace": instance.namespace.uri,
        "datetime_created": instance.datetime_created,
        "datetime_last_modified": instance.datetime_last_modified,
        "version": instance.version,
        "description": instance.description,
    }


def insert_semantic_data(sender: type[models.Model], instance: models.Model, **kwargs: Any) -> None:
    """
    Insert semantics data handler function.

    This function is called when a new data instance is created.
    It extracts the semantic data from the instance and sends it to the
    semantic_data_to_triplestore celery task for processing.
    """
    graph_urn = "urn:sparql:lara:data"

    try:
        data_model = data_model_map[instance.name]
    except KeyError:
        logger.exception("Error retrieving semantic data model")
        data_model = instance.name
    else:
        semantic_data_to_triplestore.delay(
            instance_name=instance.name,
            data_model=data_model,
            attributes=get_semantic_data_map(instance),
            graph_urn=graph_urn,
        )
