"""Unit tests for ContextCompressor.check_context_size."""

import pytest

from navi.config import Settings
from navi.core.compressor import ContextCompressor
from navi.exceptions import ContextTooLargeError
from navi.llm.base import Message


class TestCheckContextSize:
    @pytest.fixture(autouse=True)
    def _patch_settings(self, monkeypatch):
        """Use a small context window so tests don't need huge strings."""
        monkeypatch.setattr(
            "navi.config.settings",
            Settings(
                _env_file=None,
                ollama_num_ctx=128,
                output_reserve_tokens=8,
                navi_persona_file="",
            ),
        )

    def test_empty_context_ok(self):
        compressor = ContextCompressor()
        compressor.check_context_size([])

    def test_small_context_ok(self):
        compressor = ContextCompressor()
        msgs = [Message(role="user", content="hi")]
        compressor.check_context_size(msgs)

    def test_exceeds_window_raises(self):
        compressor = ContextCompressor()
        # 128 ctx - 8 reserve = 120 available; each char ~0.33 tokens
        # Need > 120 * 3 = 360 chars to exceed
        msgs = [Message(role="user", content="x" * 600)]
        with pytest.raises(ContextTooLargeError) as exc_info:
            compressor.check_context_size(msgs)
        assert "Context too large" in str(exc_info.value)

    def test_images_count_toward_limit(self):
        compressor = ContextCompressor()
        # 500 tokens per image; with 128 ctx we exceed immediately
        msgs = [Message(role="user", content="look", images=["b64"])]
        with pytest.raises(ContextTooLargeError):
            compressor.check_context_size(msgs)
