from django.db import models
from calls.models import Call


class Conversation(models.Model):
    """Model representing a conversation that occurred during a call"""
    
    # Relationship
    call = models.OneToOneField(
        Call,
        on_delete=models.CASCADE,
        related_name='conversation',
        help_text="The call this conversation belongs to"
    )
    
    # Conversation Content
    transcript = models.TextField(
        blank=True,
        help_text="Full transcript of the conversation"
    )
    summary = models.TextField(
        blank=True,
        help_text="AI-generated summary of the conversation"
    )
    
    # Key Topics and Memories
    topics_discussed = models.JSONField(
        default=list,
        help_text="List of topics discussed during the conversation"
    )
    key_memories = models.JSONField(
        default=list,
        help_text="Key memories or stories shared during the conversation"
    )
    emotions_detected = models.JSONField(
        default=list,
        help_text="Emotions detected during the conversation"
    )
    
    # Conversation Analysis
    sentiment_score = models.FloatField(
        null=True,
        blank=True,
        help_text="Overall sentiment score (-1 to 1)"
    )
    engagement_level = models.CharField(
        max_length=20,
        choices=[
            ('low', 'Low'),
            ('medium', 'Medium'),
            ('high', 'High'),
        ],
        null=True,
        blank=True,
        help_text="Level of engagement during the conversation"
    )
    
    # Follow-up Information
    follow_up_topics = models.JSONField(
        default=list,
        help_text="Topics to discuss in future calls"
    )
    follow_up_questions = models.JSONField(
        default=list,
        help_text="Questions to ask in future calls"
    )
    
    # Metadata
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        ordering = ['-created_at']
    
    def __str__(self):
        return f"Conversation with {self.call.senior.name} - {self.created_at.strftime('%Y-%m-%d %H:%M')}"
    
    @property
    def senior(self):
        """Return the senior from the associated call"""
        return self.call.senior
    
    @property
    def duration(self):
        """Return the duration of the call"""
        return self.call.duration
    
    @property
    def is_meaningful(self):
        """Return True if the conversation was meaningful (has summary and topics)"""
        return bool(self.summary and self.topics_discussed)


class Memory(models.Model):
    """Model for storing important memories extracted from conversations"""
    
    MEMORY_TYPES = [
        ('story', 'Story'),
        ('fact', 'Fact'),
        ('preference', 'Preference'),
        ('relationship', 'Relationship'),
        ('experience', 'Experience'),
        ('achievement', 'Achievement'),
    ]
    
    # Relationship
    senior = models.ForeignKey(
        'seniors.Senior',
        on_delete=models.CASCADE,
        related_name='memories',
        help_text="The senior this memory belongs to"
    )
    conversation = models.ForeignKey(
        Conversation,
        on_delete=models.CASCADE,
        related_name='memories',
        help_text="The conversation this memory was extracted from"
    )
    
    # Memory Content
    memory_type = models.CharField(
        max_length=20,
        choices=MEMORY_TYPES,
        help_text="Type of memory"
    )
    title = models.CharField(
        max_length=200,
        help_text="Short title for the memory"
    )
    content = models.TextField(help_text="The memory content")
    
    # Memory Metadata
    importance_score = models.FloatField(
        default=0.5,
        help_text="Importance score (0-1) for prioritizing memories"
    )
    tags = models.JSONField(
        default=list,
        help_text="Tags for categorizing the memory"
    )
    
    # Usage Tracking
    times_referenced = models.PositiveIntegerField(
        default=0,
        help_text="Number of times this memory has been referenced in conversations"
    )
    last_referenced = models.DateTimeField(
        null=True,
        blank=True,
        help_text="When this memory was last referenced"
    )
    
    # Metadata
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        ordering = ['-importance_score', '-created_at']
        unique_together = ['senior', 'title']
    
    def __str__(self):
        return f"{self.title} ({self.memory_type})"
    
    def mark_referenced(self):
        """Mark this memory as referenced in a conversation"""
        self.times_referenced += 1
        from django.utils import timezone
        self.last_referenced = timezone.now()
        self.save()


class ConversationInsight(models.Model):
    """Model for storing insights derived from conversation analysis"""
    
    INSIGHT_TYPES = [
        ('mood_trend', 'Mood Trend'),
        ('interest_change', 'Interest Change'),
        ('health_concern', 'Health Concern'),
        ('social_pattern', 'Social Pattern'),
        ('memory_pattern', 'Memory Pattern'),
        ('communication_style', 'Communication Style'),
    ]
    
    # Relationship
    senior = models.ForeignKey(
        'seniors.Senior',
        on_delete=models.CASCADE,
        related_name='insights',
        help_text="The senior this insight belongs to"
    )
    
    # Insight Content
    insight_type = models.CharField(
        max_length=20,
        choices=INSIGHT_TYPES,
        help_text="Type of insight"
    )
    title = models.CharField(
        max_length=200,
        help_text="Title of the insight"
    )
    description = models.TextField(help_text="Description of the insight")
    
    # Insight Data
    data = models.JSONField(
        default=dict,
        help_text="Supporting data for the insight"
    )
    confidence_score = models.FloatField(
        default=0.5,
        help_text="Confidence score (0-1) for the insight"
    )
    
    # Metadata
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        ordering = ['-confidence_score', '-created_at']
    
    def __str__(self):
        return f"{self.title} ({self.insight_type})"