from django.db import models
from django.conf import settings


class ChatSession(models.Model):
    """Represents a single chat conversation."""

    user = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="chat_sessions"
    )
    # A title for the chat, can be auto-generated or set by the user later
    title = models.CharField(max_length=255, default="New Chat")
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    state = models.CharField(
        max_length=20,
        choices=[("bot", "Bot"), ("waiting", "Waiting for Agent"), ("agent", "Agent")],
        default="bot",
    )
    assigned_agent = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="assigned_sessions",
    )

    class Meta:
        # Order by most recent chats first
        ordering = ["-updated_at"]

    def __str__(self):
        return f"Chat {self.id} for {self.user.username}: {self.title}"


class ChatMessage(models.Model):
    """Represents a single message within a chat session."""

    session = models.ForeignKey(
        ChatSession, on_delete=models.CASCADE, related_name="messages"
    )
    role = models.CharField(
        max_length=10, choices=[("user", "User"), ("bot", "Bot")]
    )  # 'user' or 'bot'
    content = models.TextField()
    language = models.CharField(max_length=50)  # e.g., 'eng', 'lug', 'nyn'
    timestamp = models.DateTimeField(auto_now_add=True)

    class Meta:
        # Order messages within a session chronologically
        ordering = ["timestamp"]

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


class KnowledgeBase(models.Model):
    """
    Stores documents, videos, and audio files as a knowledge base for the chatbot.
    """

    title = models.CharField(
        max_length=255, help_text="A brief title for the knowledge base item."
    )
    document = models.FileField(
        upload_to="knowledge_base/documents/",
        blank=True,
        null=True,
        help_text="Upload a document (e.g., PDF, DOCX).",
    )
    # images
    image = models.ImageField(
        upload_to="knowledge_base/images/",
        blank=True,
        null=True,
        help_text="Upload an image file.",
    )
    video = models.FileField(
        upload_to="knowledge_base/videos/",
        blank=True,
        null=True,
        help_text="Upload a video file.",
    )
    audio = models.FileField(
        upload_to="knowledge_base/audio/",
        blank=True,
        null=True,
        help_text="Upload an audio file.",
    )
    uploaded_at = models.DateTimeField(auto_now_add=True)

    is_published = models.BooleanField(default=False)  # track publish state

    class Meta:
        verbose_name_plural = "Knowledge Base"

    def __str__(self):
        return self.title
