from django.db import models
from django.utils import timezone


class Ticket(models.Model):
    # Status choices
    NEW = 'new'
    OPEN = 'open'
    ASSIGNED = 'assigned'
    IN_PROGRESS = 'in_progress'
    WAITING_CUSTOMER = 'waiting_customer'
    WAITING_CLIENT = 'waiting_client'
    WAITING_APPROVAL = 'waiting_approval'
    # Blocked on someone outside both us and the customer — a courier, a bank, a
    # supplier. Previously these were parked in "waiting_customer", which made
    # response-time reporting blame the customer for a third party's delay.
    WAITING_THIRD_PARTY = 'waiting_third_party'
    ESCALATED = 'escalated'
    RESOLVED = 'resolved'
    REOPENED = 'reopened'
    CLOSED = 'closed'
    CANCELLED = 'cancelled'

    STATUS_CHOICES = [
        (NEW, 'New'),
        (OPEN, 'Open'),
        (ASSIGNED, 'Assigned'),
        (IN_PROGRESS, 'In Progress'),
        (WAITING_CUSTOMER, 'Waiting for Customer'),
        (WAITING_CLIENT, 'Waiting for Client'),
        (WAITING_APPROVAL, 'Waiting for Approval'),
        (WAITING_THIRD_PARTY, 'Waiting on Third Party'),
        (ESCALATED, 'Escalated'),
        (RESOLVED, 'Resolved'),
        (REOPENED, 'Reopened'),
        (CLOSED, 'Closed'),
        (CANCELLED, 'Cancelled'),
    ]

    # Priority choices
    CRITICAL = 'critical'
    HIGH = 'high'
    MEDIUM = 'medium'
    LOW = 'low'

    PRIORITY_CHOICES = [
        (CRITICAL, 'Critical'),
        (HIGH, 'High'),
        (MEDIUM, 'Medium'),
        (LOW, 'Low'),
    ]

    # Channel choices
    CHANNEL_CHOICES = [
        ('phone', 'Phone'),
        ('email', 'Email'),
        ('chat', 'Chat'),
        ('web_form', 'Web Form'),
        ('social_media', 'Social Media'),
        ('whatsapp', 'WhatsApp'),
        ('walk_in', 'Walk-in'),
        ('api', 'API'),
        ('vicidial', 'VICIdial'),
    ]

    TYPE_CHOICES = [
        ('billing',    'Billing'),
        ('technical',  'Technical'),
        ('complaint',  'Complaint'),
        ('inquiry',    'Inquiry'),
        ('escalation', 'Escalation'),
        ('network',    'Network'),
        ('social',     'Social Media'),
        ('hr',         'HR'),
        ('general',    'General'),
    ]

    SEVERITY_CHOICES = [
        ('s1', 'S1 - Critical'),
        ('s2', 'S2 - High'),
        ('s3', 'S3 - Medium'),
        ('s4', 'S4 - Low'),
    ]

    ticket_number = models.CharField(max_length=20, unique=True)
    client = models.ForeignKey('clients.Client', on_delete=models.CASCADE, related_name='tickets')
    department = models.ForeignKey('clients.ClientDepartment', on_delete=models.SET_NULL, null=True, blank=True)
    category = models.ForeignKey('clients.TicketCategory', on_delete=models.SET_NULL, null=True, blank=True)
    sub_category = models.ForeignKey('clients.TicketSubCategory', on_delete=models.SET_NULL, null=True, blank=True)

    # Customer info
    customer_name = models.CharField(max_length=200)
    customer_email = models.EmailField(blank=True)
    customer_phone = models.CharField(max_length=20, blank=True)
    customer_account = models.CharField(max_length=100, blank=True)

    # Ticket details
    ticket_type = models.CharField(max_length=20, choices=TYPE_CHOICES, default='general')
    subject = models.CharField(max_length=500)
    description = models.TextField()
    channel = models.CharField(max_length=20, choices=CHANNEL_CHOICES, default='phone')
    channel_source = models.CharField(max_length=100, blank=True, default='')  # e.g. email account name
    priority = models.CharField(max_length=10, choices=PRIORITY_CHOICES, default=MEDIUM)
    severity = models.CharField(max_length=5, choices=SEVERITY_CHOICES, default='s3')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default=NEW)

    # Assignment
    assigned_agent = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True, blank=True,
                                       related_name='assigned_tickets')
    assigned_team_leader = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True, blank=True,
                                             related_name='supervised_tickets')
    created_by = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True,
                                   related_name='created_tickets')

    # SLA
    sla_policy = models.ForeignKey('sla.SLAPolicy', on_delete=models.SET_NULL, null=True, blank=True)
    first_response_due = models.DateTimeField(null=True, blank=True)
    resolution_due = models.DateTimeField(null=True, blank=True)
    first_responded_at = models.DateTimeField(null=True, blank=True)
    resolved_at = models.DateTimeField(null=True, blank=True)
    closed_at = models.DateTimeField(null=True, blank=True)
    sla_paused = models.BooleanField(default=False)
    sla_paused_at = models.DateTimeField(null=True, blank=True)
    sla_paused_minutes = models.IntegerField(default=0)

    # Resolution
    resolution_notes = models.TextField(blank=True)
    closure_reason = models.CharField(max_length=200, blank=True)
    customer_satisfaction = models.IntegerField(null=True, blank=True)  # 1-5
    qa_score = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True)

    # VICIdial integration
    vicidial_call_id = models.CharField(max_length=100, blank=True)
    vicidial_recording_url = models.URLField(blank=True)

    # AI fields
    ai_summary = models.TextField(blank=True)
    ai_sentiment = models.CharField(max_length=20, blank=True)
    ai_suggested_category = models.CharField(max_length=100, blank=True)

    # Sub-ticket hierarchy
    parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='sub_tickets')

    # Email ingestion: Message-ID of the email that opened this ticket
    # (Freshdesk-style threading + idempotent dedup).
    source_message_id = models.CharField(max_length=500, blank=True, default='', db_index=True)

    # Free-form labels, comma-separated (e.g. "vip, chargeback-risk").
    # Deliberately NOT used to record the handling agent — that is assigned_agent,
    # which is filterable and reportable. Duplicating it here would create two
    # sources of truth that drift the moment a ticket is reassigned.
    tags = models.CharField(max_length=300, blank=True, default='', db_index=True)

    # Reopen tracking
    reopen_count = models.IntegerField(default=0)

    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['status', 'client']),
            models.Index(fields=['assigned_agent', 'status']),
            models.Index(fields=['ticket_number']),
            models.Index(fields=['resolution_due']),
        ]

    def __str__(self):
        return f"{self.ticket_number} - {self.subject[:50]}"

    # Tier × Type → suggested priority
    _PRIORITY_MATRIX = {
        'platinum': {'billing':'critical','technical':'critical','complaint':'critical','escalation':'critical','network':'critical','inquiry':'high',   'social':'high',  'hr':'high',   'general':'high'},
        'gold':     {'billing':'high',    'technical':'high',    'complaint':'high',    'escalation':'critical','network':'high',    'inquiry':'medium', 'social':'medium','hr':'medium', 'general':'medium'},
        'silver':   {'billing':'medium',  'technical':'medium',  'complaint':'high',    'escalation':'high',    'network':'medium',  'inquiry':'low',    'social':'low',   'hr':'medium', 'general':'low'},
        'bronze':   {'billing':'medium',  'technical':'low',     'complaint':'medium',  'escalation':'high',    'network':'medium',  'inquiry':'low',    'social':'low',   'hr':'low',    'general':'low'},
    }

    def auto_priority(self):
        tier = getattr(self.client, 'tier', 'bronze') if self.client_id else 'bronze'
        return self._PRIORITY_MATRIX.get(tier, {}).get(self.ticket_type, 'low')

    def save(self, *args, **kwargs):
        if not self.ticket_number:
            self.ticket_number = self._generate_ticket_number()
        super().save(*args, **kwargs)

    def _generate_ticket_number(self):
        from django.utils import timezone
        prefix = f"TKT{timezone.now().strftime('%Y%m%d')}"
        last = Ticket.objects.filter(ticket_number__startswith=prefix).order_by('-ticket_number').first()
        if last:
            seq = int(last.ticket_number[-4:]) + 1
        else:
            seq = 1
        return f"{prefix}{seq:04d}"


class TicketComment(models.Model):
    INTERNAL = 'internal'
    PUBLIC = 'public'
    CUSTOMER_REPLY = 'customer_reply'
    CLIENT_REPLY = 'client_reply'
    SYSTEM = 'system'

    TYPE_CHOICES = [
        (INTERNAL, 'Internal Note'),
        (PUBLIC, 'Public Reply'),
        (CUSTOMER_REPLY, 'Customer Reply'),
        (CLIENT_REPLY, 'Client Reply'),
        (SYSTEM, 'System'),
    ]

    ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, related_name='comments')
    author = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True, blank=True)
    comment_type = models.CharField(max_length=20, choices=TYPE_CHOICES, default=PUBLIC)
    body = models.TextField()
    is_ai_generated = models.BooleanField(default=False)
    ai_edited = models.BooleanField(default=False)
    # Message-ID of the reply email that produced this comment (dedup/threading).
    source_message_id = models.CharField(max_length=500, blank=True, default='', db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['created_at']


class TicketAttachment(models.Model):
    ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, related_name='attachments')
    uploaded_by = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True, blank=True)
    file = models.FileField(upload_to='ticket_attachments/%Y/%m/')
    filename = models.CharField(max_length=255)
    file_size = models.IntegerField(default=0)
    file_type = models.CharField(max_length=50, blank=True)
    tags = models.CharField(max_length=200, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.filename


class TicketHistory(models.Model):
    ticket = models.ForeignKey(Ticket, on_delete=models.CASCADE, related_name='history')
    user = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True, blank=True)
    field_changed = models.CharField(max_length=50)
    old_value = models.TextField(blank=True)
    new_value = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created_at']
