import uuid
from django.db import models
from django.conf import settings
from accounts.models import VendorProfile


class VendorAIConfig(models.Model):
    vendor = models.OneToOneField(
        VendorProfile,
        on_delete=models.CASCADE,
        related_name='ai_config'
    )
    business_description = models.TextField(blank=True, default='')
    policies = models.TextField(blank=True, default='')
    custom_instructions = models.TextField(blank=True, default='')
    suggested_questions = models.JSONField(default=list, blank=True)
    is_active = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'vendor_ai_configs'

    def __str__(self):
        return f"AI Config for {self.vendor.shop_name}"


class VendorFAQ(models.Model):
    ai_config = models.ForeignKey(
        VendorAIConfig,
        on_delete=models.CASCADE,
        related_name='faqs'
    )
    question = models.CharField(max_length=500)
    answer = models.TextField()
    order = models.PositiveIntegerField(default=0)
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = 'vendor_faqs'
        ordering = ['order', 'created_at']

    def __str__(self):
        return f"FAQ: {self.question[:50]}"


class AIChat(models.Model):
    vendor = models.ForeignKey(
        VendorProfile,
        on_delete=models.CASCADE,
        related_name='ai_chats'
    )
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='ai_chats'
    )
    session_id = models.UUIDField(default=uuid.uuid4, unique=True, editable=False)
    started_at = models.DateTimeField(auto_now_add=True)
    ended_at = models.DateTimeField(null=True, blank=True)
    was_handed_off = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)

    class Meta:
        db_table = 'ai_chats'
        ordering = ['-started_at']

    def __str__(self):
        return f"Chat {self.session_id} - {self.vendor.shop_name}"


class AIChatMessage(models.Model):
    ROLE_CHOICES = [
        ('customer', 'Customer'),
        ('assistant', 'Assistant'),
        ('system', 'System'),
    ]

    chat = models.ForeignKey(
        AIChat,
        on_delete=models.CASCADE,
        related_name='messages'
    )
    role = models.CharField(max_length=10, choices=ROLE_CHOICES)
    content = models.TextField()
    was_helpful = models.BooleanField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = 'ai_chat_messages'
        ordering = ['created_at']

    def __str__(self):
        return f"{self.role}: {self.content[:50]}"
