"""Assistant conversation persistence.

Stored under the `core` app label (sibling of `core.audit`). Three small
models: a `Conversation` per user, a `Message` per turn, and a `ToolCall`
per tool invocation inside an assistant message — the last is what makes
audit-style "did the bot leak doc X?" forensics possible.
"""
from __future__ import annotations

import uuid

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


class Conversation(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    user = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name="assistant_conversations",
    )
    title = models.CharField(max_length=200, blank=True)
    summary = models.TextField(blank=True)
    summary_until_message_id = models.UUIDField(null=True, 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:
        app_label = "core"
        ordering = ["-updated_at"]
        indexes = [models.Index(fields=["user", "-updated_at"])]

    def __str__(self) -> str:
        return self.title or f"Conversation {self.id}"

    def derive_title(self, first_user_text: str) -> None:
        """Set the title from the first user message if not set yet."""
        if self.title:
            return
        text = (first_user_text or "").strip().splitlines()[0] if first_user_text else ""
        self.title = (text[:60] + "…") if len(text) > 60 else text or "Untitled chat"


class Message(models.Model):
    class Role(models.TextChoices):
        USER = "user", "User"
        ASSISTANT = "assistant", "Assistant"
        TOOL = "tool", "Tool"
        SYSTEM = "system", "System"

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    conversation = models.ForeignKey(
        Conversation,
        on_delete=models.CASCADE,
        related_name="messages",
    )
    role = models.CharField(max_length=16, choices=Role.choices)
    content = models.TextField()
    citations = models.JSONField(default=list, blank=True)
    metadata = models.JSONField(default=dict, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        app_label = "core"
        ordering = ["created_at"]
        indexes = [models.Index(fields=["conversation", "created_at"])]


class ToolCall(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    message = models.ForeignKey(
        Message,
        on_delete=models.CASCADE,
        related_name="tool_calls",
    )
    name = models.CharField(max_length=64)
    arguments = models.JSONField(default=dict, blank=True)
    result_preview = models.TextField(blank=True)
    surfaced_object_ids = models.JSONField(default=list, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        app_label = "core"
        ordering = ["created_at"]
