"""
Call Center models - Call center interaction tracking and ratings

This module implements call center tracking that:
- Records call center interactions
- Tracks agent performance
- Monitors wait times and satisfaction
- Creates PX actions for low ratings
"""
from django.db import models

from apps.core.models import TimeStampedModel, UUIDModel


class CallCenterInteraction(UUIDModel, TimeStampedModel):
    """
    Call center interaction - tracks calls with patients.
    
    Low ratings trigger PX action creation.
    """
    # Patient information
    patient = models.ForeignKey(
        'organizations.Patient',
        on_delete=models.CASCADE,
        null=True,
        blank=True,
        related_name='call_center_interactions'
    )
    
    # Caller information (if not a patient)
    caller_name = models.CharField(max_length=200, blank=True)
    caller_phone = models.CharField(max_length=20, blank=True)
    caller_relationship = models.CharField(
        max_length=50,
        choices=[
            ('patient', 'Patient'),
            ('family', 'Family Member'),
            ('other', 'Other'),
        ],
        default='patient'
    )
    
    # Organization
    hospital = models.ForeignKey(
        'organizations.Hospital',
        on_delete=models.CASCADE,
        related_name='call_center_interactions'
    )
    department = models.ForeignKey(
        'organizations.Department',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='call_center_interactions'
    )
    
    # Agent information
    agent = models.ForeignKey(
        'accounts.User',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='call_center_interactions'
    )
    
    # Call details
    call_type = models.CharField(
        max_length=50,
        choices=[
            ('inquiry', 'Inquiry'),
            ('complaint', 'Complaint'),
            ('appointment', 'Appointment'),
            ('follow_up', 'Follow-up'),
            ('feedback', 'Feedback'),
            ('other', 'Other'),
        ],
        db_index=True
    )
    
    subject = models.CharField(max_length=500)
    notes = models.TextField(blank=True)
    
    # Metrics
    wait_time_seconds = models.IntegerField(
        null=True,
        blank=True,
        help_text="Time caller waited before agent answered"
    )
    call_duration_seconds = models.IntegerField(
        null=True,
        blank=True,
        help_text="Total call duration"
    )
    
    # Rating (1-5 scale)
    satisfaction_rating = models.IntegerField(
        null=True,
        blank=True,
        help_text="Caller satisfaction rating (1-5)"
    )
    is_low_rating = models.BooleanField(
        default=False,
        db_index=True,
        help_text="True if rating below threshold (< 3)"
    )
    
    # Resolution
    resolved = models.BooleanField(default=False)
    resolution_notes = models.TextField(blank=True)
    
    # Timestamps
    call_started_at = models.DateTimeField(auto_now_add=True)
    call_ended_at = models.DateTimeField(null=True, blank=True)
    
    # Metadata
    metadata = models.JSONField(default=dict, blank=True)
    
    class Meta:
        ordering = ['-call_started_at']
        indexes = [
            models.Index(fields=['hospital', '-call_started_at']),
            models.Index(fields=['agent', '-call_started_at']),
            models.Index(fields=['is_low_rating', '-call_started_at']),
        ]
    
    def __str__(self):
        caller = self.patient.get_full_name() if self.patient else self.caller_name
        return f"{caller} - {self.call_type} ({self.call_started_at.strftime('%Y-%m-%d %H:%M')})"
    
    def save(self, *args, **kwargs):
        """Check if rating is low"""
        if self.satisfaction_rating and self.satisfaction_rating < 3:
            self.is_low_rating = True
        super().save(*args, **kwargs)
