import unittest
from slack_bot.llm.gemini import GeminiLLM
from unittest.mock import MagicMock

class TestGeminiJSON(unittest.TestCase):
    def setUp(self):
        # Mock env vars to avoid init failing
        import os
        os.environ["GEMINI_API_KEY"] = "fake_key"
        self.llm = GeminiLLM()

    def test_clean_json(self):
        """Test parsing valid clean JSON."""
        data = '{"name": "test", "value": 123}'
        result = self.llm._safe_parse_json(data)
        self.assertEqual(result, {"name": "test", "value": 123})

    def test_extra_data_suffix(self):
        """Test parsing JSON with trailing text (common Gemini issue)."""
        data = '{"name": "tool"} Here is some explanation text'
        result = self.llm._safe_parse_json(data)
        self.assertEqual(result, {"name": "tool"})

    def test_extra_data_prefix(self):
        """Test parsing JSON with leading text."""
        data = 'Sure, here is the tool call: {"name": "tool"}'
        result = self.llm._safe_parse_json(data)
        self.assertEqual(result, {"name": "tool"})
        
    def test_nested_structure(self):
        """Test parsing nested JSON structure."""
        data = '{"args": {"date": "2023-01-01", "list": [1, 2, 3]}}'
        result = self.llm._safe_parse_json(data)
        self.assertEqual(result["args"]["list"], [1, 2, 3])

    def test_invalid_json(self):
        """Test completely invalid JSON returns empty dict."""
        data = 'Not a json string at all'
        result = self.llm._safe_parse_json(data)
        self.assertEqual(result, {})

if __name__ == '__main__':
    unittest.main()
