"""_____________________________________________________________________

:PROJECT: LARAsuite

*lara_django_processes signals handler *

:details: lara_django_processes signals handler.
         -
         - 
:authors: mark doerr <mark.doerr@uni-greifswald.de>

.. note:: -
.. todo:: -
________________________________________________________________________
"""

# get settings from django.conf
import logging
from django.conf import settings
from django.apps import apps
from .rmq_producer import ProducerProcessesCreated

from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver

#from .proc_deploy import deploy_prefect_process

from prefect import flow
from prefect_aws.s3 import S3Bucket

# logger

logger = logging.getLogger(__name__)

# rabbitmq = ProducerProcessesCreated()

def post_init_handler(sender, instance, **kwargs):
    """
    handler for post_init signal of all models
    """
    logger.debug(f"post_init_handler: {sender}, {instance}, {kwargs}")
    #rabbitmq.publish("post_init", instance)
    

@receiver(post_save, sender='lara_django_processes.ProcessInstance') #apps.get_model('lara_django_processes', 'ProcessInstance'))
def post_save_handler(sender, instance,  **kwargs):  #created,
    """
    handler for post_save signal of all models
    """
    logger.debug(f"post_save_handler processes: {sender}, {instance}, ") #{created}

    # if created use mapping to write semantic data to triple store
    if  instance.__class__.__name__ == "ProcessInstance": # and created:
       print(f"!!!  creating - post_save_handler: {sender}, {instance}, {kwargs}")
       
       deploy_prefect_process_loc(sender, instance, **kwargs)

        
    
def post_delete_handler(sender, instance, using, origin, **kwargs):
    """
    handler for post_delete signal of all models
    """
    print(f"!!!  deleting - post_delete_handler: {sender}, {instance}, {using}, {origin}, {kwargs}")
    #waiting_task.delay()


def deploy_prefect_process_loc(sender, instance, **kwargs):
    """
    deploy prefect process
    """

    instance_id = str(instance.processinstance_id)[:8]
    print(f"******* - --- deploying prefect process {instance.name} - {instance_id} ")
    
    prefect_workpool = "local-process-worker-1" # settings.DEFAULT_PREFCT_WORKPOOL

    # if instance has a workpool set as parameters, use it !

    # s3_bucket_block = S3Bucket.load("minio-prefect-flows-lara")

    print(f"******* - --- deploying prefect process {instance.name} - {prefect_workpool} ")

    # flow.from_source(
    #     source=s3_bucket_block,
    #     entrypoint="robot_workflow_sila.py:science_robotic_process"
    # ).deploy(
    #     name=f"minio-s3-deployment-lara-{instance.name}-{instance_id}",
    #     work_pool_name="local-process-worker-1", #prefect_workpool,
    #     job_variables={"env": {"EXTRA_PIP_PACKAGES": "prefect-aws"} },
    #     tags=["lara", "sila"],
    #     description="Deployment of a SiLA workflow.",
    #     version="v0.0.1",
    # )

from django.dispatch import receiver
from django.db.models.signals import post_save
from lara_django_base.decorators import postgres_only

from .semantics import insert_semantic_data

logger = logging.getLogger('lara_signals')


# @receiver(post_save, sender=Evaluation)
# def semantics_data_handler(sender, instance, created, **kwargs):
#     """Semantic data post_save signal handler.

#        This function is triggered after an instance of the Evaluation model is saved.
#        It calls the insert_semantics function to handle the semantic data insertion
#        into the triplestore, running asynchronously as celery task.
#     """
#     logger.debug("post_save_handler1: %s, %s ", sender, instance)

#     insert_semantic_data(sender, instance, **kwargs)


# @receiver(post_save, sender=Evaluation)
# @postgres_only
# def update_search_vector(sender, instance, **kwargs):
#     sender.objects.filter(pk=instance.pk).update(
#         search_vector=(
#             SearchVector('name', weight='A') +
#             SearchVector('name_display', weight='B') +
#             SearchVector('description', weight='C') +
#             SearchVector('caption', weight='D')
#         )
#     )