import pytest
import json
from slack_bot.llm.gemini import GeminiLLM

class TestGeminiResilience:
    def setup_method(self):
        # We need to mock os.environ inside the test or rely on mock_env fixture if passed
        pass

    def test_safe_parse_json_valid(self, mock_env):
        llm = GeminiLLM()
        data = '{"foo": "bar"}'
        assert llm._safe_parse_json(data) == {"foo": "bar"}

    def test_safe_parse_json_with_comments(self, mock_env):
        llm = GeminiLLM()
        # Common local LLM behavior: adding comments
        data = '{"foo": "bar"} // This is a comment'
        res = llm._safe_parse_json(data)
        assert res == {"foo": "bar"}
    
    def test_safe_parse_json_with_prefix(self, mock_env):
        llm = GeminiLLM()
        # Common verbose LLM behavior
        data = 'Here is the JSON: {"foo": "bar"}'
        res = llm._safe_parse_json(data)
        assert res == {"foo": "bar"}

    def test_format_response_truncation(self, mock_env):
        """Test that _format_response truncates very long tool outputs."""
        from slack_bot.dispatcher import MessageDispatcher
        # We can't easily instantiate Dispatcher without real Slack client unless we mock it
        # But for this logic test, we can just check the helper logic if we extract it,
        # or use a partial mock.
        
        # Let's mock the Slack Client in init
        with pytest.MonkeyPatch.context() as m:
            m.setattr("slack_sdk.WebClient.__init__", lambda self, token: None)
            dispatcher = MessageDispatcher()
            
            long_tool_result = "A" * 10000
            tool_results = [{
                "tool": "test",
                "args": {},
                "result": long_tool_result
            }]
            
            response = dispatcher._format_response("Main text", tool_results, max_length=4000)
            
            assert len(response) <= 4000
            # The final safety truncation message should be present
            assert "⚠️ (Response truncated" in response
