"""Tests for StreamState buffer efficiency and correctness."""

from terminaluse.lib.utils.dev_tools.async_messages import StreamState


class TestStreamState:
    """Tests for StreamState output buffer operations."""

    def test_append_output_efficiency(self) -> None:
        """Verify O(n) total time for n appends (list-based, not string concat)."""
        state = StreamState()

        # Simulate 10000 character deltas (like streaming a long response)
        for _ in range(10000):
            state.append_output("x")

        output = state.get_output()
        assert len(output) == 10000
        assert output == "x" * 10000

    def test_output_preserves_order(self) -> None:
        """Output maintains insertion order."""
        state = StreamState()
        state.append_output("Hello")
        state.append_output(" ")
        state.append_output("World")

        assert state.get_output() == "Hello World"

    def test_empty_append_ignored(self) -> None:
        """Empty strings are not appended (optimization)."""
        state = StreamState()
        state.append_output("")
        state.append_output("text")
        state.append_output("")

        assert state.get_output() == "text"
        # Verify internal list doesn't contain empty strings
        assert len(state._output_parts) == 1

    def test_empty_state_returns_empty_string(self) -> None:
        """Empty state returns empty string, not None."""
        state = StreamState()
        assert state.get_output() == ""

    def test_multiple_get_output_calls_consistent(self) -> None:
        """Multiple calls to get_output() return same result."""
        state = StreamState()
        state.append_output("test")

        result1 = state.get_output()
        result2 = state.get_output()

        assert result1 == result2 == "test"

    def test_rich_markup_preserved(self) -> None:
        """Rich markup is preserved in output."""
        state = StreamState()
        state.append_output("[bold]Hello[/bold]")
        state.append_output(" ")
        state.append_output("[red]World[/red]")

        assert state.get_output() == "[bold]Hello[/bold] [red]World[/red]"

    def test_multiline_content(self) -> None:
        """Multiline content is handled correctly."""
        state = StreamState()
        state.append_output("Line 1\n")
        state.append_output("Line 2\n")
        state.append_output("Line 3")

        assert state.get_output() == "Line 1\nLine 2\nLine 3"
