from django.db import models


class ScheduledReply(models.Model):
    """A human-like auto-reply queued to send a few minutes after the email
    arrived (so it doesn't look robotically instant). A periodic sweep sends
    any whose ``send_at`` has passed."""
    PENDING = 'pending'
    SENT = 'sent'
    FAILED = 'failed'
    CANCELLED = 'cancelled'
    STATUS_CHOICES = [
        (PENDING, 'Pending'),
        (SENT, 'Sent'),
        (FAILED, 'Failed'),
        (CANCELLED, 'Cancelled'),
    ]

    ticket = models.ForeignKey('tickets.Ticket', on_delete=models.CASCADE, related_name='scheduled_replies')
    agent = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True, blank=True)
    subject = models.CharField(max_length=500, blank=True, default='')
    body = models.TextField()
    send_at = models.DateTimeField(db_index=True)
    status = models.CharField(max_length=12, choices=STATUS_CHOICES, default=PENDING)
    error = models.TextField(blank=True, default='')
    created_at = models.DateTimeField(auto_now_add=True)
    sent_at = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return f'ScheduledReply<{self.ticket_id} {self.status} @ {self.send_at:%H:%M}>'


class AIReplyArchive(models.Model):
    """Every reply the AI has written — both the ones actually emailed to a
    customer and the drafts an agent asked for.

    The point is reuse without spend: once a reply exists here, an agent can
    search it and paste it into a new ticket instead of paying for a fresh
    generation. Searching this table never calls the AI, so it keeps working
    with the AI Assistant switched off (or the API key removed).
    """
    SENT = 'sent'
    DRAFT = 'draft'
    KIND_CHOICES = [
        (SENT, 'Sent to customer'),
        (DRAFT, 'Draft (not sent)'),
    ]

    # Denormalised client FK: the source ticket may be deleted, but the archive
    # entry stays useful — and tenant isolation must not depend on the ticket.
    client   = models.ForeignKey('clients.Client', on_delete=models.CASCADE,
                                 related_name='ai_reply_archive')
    ticket   = models.ForeignKey('tickets.Ticket', on_delete=models.SET_NULL,
                                 null=True, blank=True, related_name='ai_archive')
    kind     = models.CharField(max_length=8, choices=KIND_CHOICES, default=DRAFT, db_index=True)
    subject  = models.CharField(max_length=500, blank=True, default='')
    body     = models.TextField()
    # What the AI decided the customer wanted — the most useful search key.
    concern  = models.CharField(max_length=500, blank=True, default='')
    category = models.CharField(max_length=100, blank=True, default='', db_index=True)
    tone     = models.CharField(max_length=40, blank=True, default='')
    agent    = models.ForeignKey('core.User', on_delete=models.SET_NULL, null=True, blank=True,
                                 related_name='ai_replies_authored')
    used_count = models.PositiveIntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True, db_index=True)

    class Meta:
        ordering = ['-created_at']
        indexes = [models.Index(fields=['client', 'kind', '-created_at'])]

    def __str__(self):
        return f'AIReplyArchive<{self.kind} {self.subject[:40]}>'
