from __future__ import annotations


from django_anyllm.models import Chat, Message, MessageFile


class TestChatModel:
    """Tests for the Chat model."""

    def test_create(self, db):
        chat = Chat.objects.create(title="Test Chat", model="gpt-4")
        assert str(chat) == "Test Chat"
        assert chat.model == "gpt-4"

    def test_default_title(self, db):
        chat = Chat.objects.create()
        assert str(chat) == f"Chat {chat.pk}"

    def test_ordering(self, db):
        Chat.objects.create(title="Old")
        c2 = Chat.objects.create(title="New")
        chats = list(Chat.objects.all())
        assert chats[0] == c2

    def test_default_model(self, db):
        chat = Chat.objects.create()
        assert chat.model == "gpt-4"

    def test_default_provider(self, db):
        chat = Chat.objects.create()
        assert chat.provider == "openai"

    def test_custom_default_model(self, db, settings):
        settings.DJANGO_ANYLLM = {"DEFAULT_MODEL": "claude-3-opus"}
        chat = Chat.objects.create()
        assert chat.model == "claude-3-opus"

    def test_custom_default_provider(self, db, settings):
        settings.DJANGO_ANYLLM = {"DEFAULT_PROVIDER": "anthropic"}
        chat = Chat.objects.create()
        assert chat.provider == "anthropic"


class TestMessageModel:
    """Tests for the Message model."""

    def test_create(self, db):
        chat = Chat.objects.create()
        msg = chat.messages.create(role=Message.Role.USER, content="Hello")
        assert msg.role == "user"
        assert "Hello" in str(msg)

    def test_ordering(self, db):
        chat = Chat.objects.create()
        m1 = chat.messages.create(role=Message.Role.USER, content="First")
        m2 = chat.messages.create(role=Message.Role.USER, content="Second")
        msgs = list(chat.messages.all())
        assert msgs[0] == m1
        assert msgs[1] == m2


class TestMessageFileModel:
    """Tests for the MessageFile model."""

    def test_create(self, db):
        chat = Chat.objects.create()
        msg = chat.messages.create(role=Message.Role.USER, content="Hi")
        mf = MessageFile.objects.create(
            message=msg,
            mime_type="image/png",
        )
        assert mf.mime_type == "image/png"

    def test_to_image_content_non_image(self, db):
        chat = Chat.objects.create()
        msg = chat.messages.create(role=Message.Role.USER, content="Hi")
        mf = MessageFile.objects.create(message=msg, mime_type="text/plain")
        assert mf.to_image_content() is None
