"""Message is the boundary every stored text passes through."""

from datetime import datetime, timezone

from navi.llm.base import Message, ToolCallRequest


class TestNulBytes:
    """PostgreSQL text cannot hold a NUL byte, and one arriving in a tool result
    made the whole session_messages INSERT fail with CharacterNotInRepertoireError
    — the turn died and the user lost it (three times on prod, 2026-10-07). The
    strip lives on Message so it covers every writer downstream of it.
    """

    def test_content_loses_nul_bytes(self):
        assert Message(role="tool", content="bi\x00nary").content == "binary"

    def test_thinking_loses_nul_bytes_too(self):
        assert Message(role="assistant", thinking="th\x00ink").thinking == "think"

    def test_clean_text_is_untouched(self):
        text = "привет, мир — 100% ok"
        assert Message(role="user", content=text).content == text

    def test_absent_content_stays_none(self):
        assert Message(role="assistant").content is None


class TestCreatedAt:
    """created_at used to default to None, and since only some construction sites
    filled it, 85% of prod rows stored no timestamp — every tool message
    (14 168/14 168), so no query could slice history by time or measure a pause.
    """

    def test_new_messages_are_stamped(self):
        before = datetime.now(timezone.utc)
        message = Message(role="tool", content="output")
        assert message.created_at is not None
        assert before <= message.created_at <= datetime.now(timezone.utc)

    def test_tool_call_only_messages_are_stamped_too(self):
        message = Message(
            role="assistant",
            tool_calls=[ToolCallRequest(id="1", name="terminal", arguments={"command": "ls"})],
        )
        assert message.created_at is not None

    def test_an_explicit_value_is_kept(self):
        stamp = datetime(2026, 10, 7, 12, 0, tzinfo=timezone.utc)
        assert Message(role="user", content="hi", created_at=stamp).created_at == stamp

    def test_loading_a_row_without_a_timestamp_does_not_invent_one(self):
        """PgSessionStore passes the column through explicitly, so a NULL row
        stays NULL instead of being restamped with the time of the read."""
        assert Message(role="tool", content="old", created_at=None).created_at is None
