"""
AI Engine signals - Auto-analyze text content from various apps

This module automatically triggers sentiment analysis when text content is created
or updated in various apps throughout the system.
"""
from django.db.models.signals import post_save
from django.dispatch import receiver

from .services import AIEngineService


@receiver(post_save, sender='complaints.Complaint')
def analyze_complaint_sentiment(sender, instance, created, **kwargs):
    """
    Analyze sentiment when a complaint is created or updated.
    
    Analyzes the complaint description for sentiment.
    """
    if instance.description:
        try:
            AIEngineService.sentiment.analyze_and_save(
                text=instance.description,
                content_object=instance
            )
        except Exception as e:
            # Log error but don't fail the complaint creation
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Failed to analyze complaint sentiment: {e}")


@receiver(post_save, sender='feedback.Feedback')
def analyze_feedback_sentiment(sender, instance, created, **kwargs):
    """
    Analyze sentiment when feedback is created or updated.
    
    Analyzes the feedback message for sentiment.
    """
    if instance.message:
        try:
            AIEngineService.sentiment.analyze_and_save(
                text=instance.message,
                content_object=instance
            )
        except Exception as e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Failed to analyze feedback sentiment: {e}")


@receiver(post_save, sender='surveys.SurveyResponse')
def analyze_survey_response_sentiment(sender, instance, created, **kwargs):
    """
    Analyze sentiment for text survey responses.
    
    Only analyzes responses with text_value (text/textarea questions).
    """
    if instance.text_value and len(instance.text_value.strip()) > 10:
        try:
            AIEngineService.sentiment.analyze_and_save(
                text=instance.text_value,
                content_object=instance
            )
        except Exception as e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Failed to analyze survey response sentiment: {e}")




@receiver(post_save, sender='callcenter.CallCenterInteraction')
def analyze_callcenter_notes_sentiment(sender, instance, created, **kwargs):
    """
    Analyze sentiment for call center interaction notes.
    
    Analyzes both notes and resolution_notes for sentiment.
    """
    # Combine notes and resolution notes
    text_to_analyze = []
    if instance.notes:
        text_to_analyze.append(instance.notes)
    if instance.resolution_notes:
        text_to_analyze.append(instance.resolution_notes)
    
    if text_to_analyze:
        combined_text = " ".join(text_to_analyze)
        try:
            AIEngineService.sentiment.analyze_and_save(
                text=combined_text,
                content_object=instance
            )
        except Exception as e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Failed to analyze call center interaction sentiment: {e}")


@receiver(post_save, sender='complaints.ComplaintUpdate')
def analyze_complaint_update_sentiment(sender, instance, created, **kwargs):
    """
    Analyze sentiment for complaint updates/notes.
    
    Analyzes the message in complaint updates.
    """
    if instance.message and len(instance.message.strip()) > 10:
        try:
            AIEngineService.sentiment.analyze_and_save(
                text=instance.message,
                content_object=instance
            )
        except Exception as e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Failed to analyze complaint update sentiment: {e}")


@receiver(post_save, sender='feedback.FeedbackResponse')
def analyze_feedback_response_sentiment(sender, instance, created, **kwargs):
    """
    Analyze sentiment for feedback responses.
    
    Analyzes the message in feedback responses.
    """
    if instance.message and len(instance.message.strip()) > 10:
        try:
            AIEngineService.sentiment.analyze_and_save(
                text=instance.message,
                content_object=instance
            )
        except Exception as e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Failed to analyze feedback response sentiment: {e}")


@receiver(post_save, sender='complaints.Inquiry')
def analyze_inquiry_sentiment(sender, instance, created, **kwargs):
    """
    Analyze sentiment for inquiries.
    
    Analyzes the inquiry message and response.
    """
    # Analyze the inquiry message
    if instance.message:
        try:
            AIEngineService.sentiment.analyze_and_save(
                text=instance.message,
                content_object=instance
            )
        except Exception as e:
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f"Failed to analyze inquiry sentiment: {e}")
