"""
Models for django_ai_admin_chat app.

This file is ready for future implementation of models related to chat functionality.
"""

import uuid

from django.contrib.auth import get_user_model
from django.db import models

User = get_user_model()


class ChatHistory(models.Model):
    """Model storing historical chat data."""

    SEARCH_TYPE_SQL_DATABASE_CHAIN = "sql_database_chain"
    SEARCH_TYPE_NONE = "none"
    SEARCH_TYPE_CHOICES = [
        (SEARCH_TYPE_SQL_DATABASE_CHAIN, "SQLDatabaseChain Search"),
        (SEARCH_TYPE_NONE, "No Database Search"),
    ]

    session_id = models.UUIDField(
        default=uuid.uuid4,
        editable=False,
        db_index=True,
        help_text="Unique chat session identifier",
    )
    user = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name="chat_histories",
        help_text="User who executed the query",
    )
    query = models.TextField(help_text="User question")
    search_type = models.CharField(
        max_length=20,
        choices=SEARCH_TYPE_CHOICES,
        default=SEARCH_TYPE_NONE,
        help_text="Search type used to find data",
    )
    search_results = models.JSONField(
        default=list,
        help_text="Search results (list of SearchMatch as JSON)",
    )
    context = models.TextField(
        help_text="Built context from search results",
    )
    response = models.TextField(
        help_text="Assistant response",
    )
    tokens_prompt = models.IntegerField(
        null=True,
        blank=True,
        help_text="Number of tokens used in prompt",
    )
    tokens_completion = models.IntegerField(
        null=True,
        blank=True,
        help_text="Number of tokens used in response",
    )
    tokens_total = models.IntegerField(
        null=True,
        blank=True,
        help_text="Total number of tokens (prompt + completion)",
    )
    chat_history = models.JSONField(
        default=list,
        help_text="Chat history before this query (list of messages)",
    )
    sql_query = models.TextField(
        null=True,
        blank=True,
        help_text="SQL query generated by AI model",
    )
    raw_sql_results = models.JSONField(
        null=True,
        blank=True,
        help_text="Raw results from SQL query execution",
    )
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ["-created_at"]
        verbose_name = "Chat History"
        verbose_name_plural = "Chat Histories"
        indexes = [
            models.Index(fields=["-created_at"]),
            models.Index(fields=["user", "-created_at"]),
            models.Index(fields=["session_id", "-created_at"]),
        ]

    def __str__(self):
        query_preview = self.query[:50] + "..." if len(self.query) > 50 else self.query
        return f"ChatHistory: {query_preview} ({self.created_at})"
