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

from apps.core.models import uuid7


class ChatSession(models.Model):
    """One AI assistant conversation thread owned by a user in one organization."""
    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="chatbot_sessions")
    organization = models.ForeignKey(
        "companies.Organization",
        on_delete=models.CASCADE,
        related_name="chatbot_sessions",
        null=True,
        blank=True,
        db_index=True,
    )
    title = models.CharField(max_length=255, blank=True)
    is_archived = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        db_table = "chatbot_sessions"
        ordering = ["-updated_at"]
        indexes = [models.Index(fields=["user", "-updated_at"])]

    def __str__(self):
        return self.title or f"Session {self.id}"


class ChatMessage(models.Model):
    """One turn in a ChatSession. `tool_calls`/`tool_results` record any RBAC-scoped
    lookups the assistant made while answering, for transparency/audit."""
    ROLE_CHOICES = [
        ("user", "User"),
        ("assistant", "Assistant"),
    ]

    id = models.UUIDField(primary_key=True, default=uuid7, editable=False)
    session = models.ForeignKey(ChatSession, on_delete=models.CASCADE, related_name="messages")
    role = models.CharField(max_length=10, choices=ROLE_CHOICES)
    content = models.TextField(blank=True)
    tool_calls = models.JSONField(default=list, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        db_table = "chatbot_messages"
        ordering = ["created_at"]
        indexes = [models.Index(fields=["session", "created_at"])]

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