"""
Complaints signals

Handles automatic actions triggered by complaint and survey events.
"""
import logging

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

from apps.complaints.models import Complaint
from apps.surveys.models import SurveyInstance

logger = logging.getLogger(__name__)


@receiver(post_save, sender=Complaint)
def handle_complaint_created(sender, instance, created, **kwargs):
    """
    Handle complaint creation.

    Triggers:
    - AI-powered severity and priority analysis
    - Create PX Action if hospital config requires it
    - Send notification to assigned user/department
    """
    if created:
        # Import here to avoid circular imports
        from apps.complaints.tasks import (
            analyze_complaint_with_ai,
            create_action_from_complaint,
            send_complaint_notification,
        )

        # Try to trigger async tasks, but don't fail if Redis/Celery is unavailable
        try:
            # Trigger AI analysis (determines severity and priority)
            analyze_complaint_with_ai.delay(str(instance.id))

            # Trigger PX Action creation (if configured)
            create_action_from_complaint.delay(str(instance.id))

            # Send notification
            send_complaint_notification.delay(
                complaint_id=str(instance.id),
                event_type='created'
            )

            logger.info(f"Complaint created: {instance.id} - {instance.title} - Async tasks queued")    
        except Exception as e:
            # Log the error but don't prevent complaint creation
            logger.warning(
                f"Complaint created: {instance.id} - {instance.title} - "
                f"Async tasks could not be queued (Celery/Redis unavailable): {e}"
            )


@receiver(post_save, sender=SurveyInstance)
def handle_survey_completed(sender, instance, created, **kwargs):
    """
    Handle survey completion.

    Checks if this is a complaint resolution survey and if score is below threshold.
    If so, creates a PX Action automatically.
    """
    if not created and instance.status == 'completed' and instance.total_score is not None:
        # Check if this is a complaint resolution survey
        if instance.metadata.get('complaint_id'):
            from apps.complaints.tasks import check_resolution_survey_threshold

            try:
                check_resolution_survey_threshold.delay(
                    survey_instance_id=str(instance.id),
                    complaint_id=instance.metadata['complaint_id']
                )

                logger.info(
                    f"Resolution survey completed for complaint {instance.metadata['complaint_id']}: "
                    f"Score = {instance.total_score} - Async task queued"
                )
            except Exception as e:
                # Log the error but don't prevent survey completion
                logger.warning(
                    f"Resolution survey completed for complaint {instance.metadata['complaint_id']}: "
                    f"Score = {instance.total_score} - Async task could not be queued (Celery/Redis unavailable): {e}"
                )
