"""Unit tests for Agent._check_context_size."""

import pytest

from navi.config import Settings
from navi.core.agent import Agent
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."""
        import navi.core.agent as _agent_mod

        monkeypatch.setattr(
            _agent_mod,
            "settings",
            Settings(
                _env_file=None,
                ollama_num_ctx=128,
                output_reserve_tokens=8,
                navi_persona_file="",
            ),
        )

    def test_empty_context_ok(self):
        agent = Agent(None, None, None, None)
        agent._check_context_size([])

    def test_small_context_ok(self):
        agent = Agent(None, None, None, None)
        msgs = [Message(role="user", content="hi")]
        agent._check_context_size(msgs)

    def test_exceeds_window_raises(self):
        agent = Agent(None, None, None, None)
        # 128 ctx - 8 reserve = 120 available; each char ~0.25 tokens
        # Need > 120 * 4 = 480 chars to exceed
        msgs = [Message(role="user", content="x" * 600)]
        with pytest.raises(ContextTooLargeError) as exc_info:
            agent._check_context_size(msgs)
        assert "Context too large" in str(exc_info.value)

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