import unittest
import json
from unittest.mock import patch, MagicMock
from src.gemini_cli_adapter import GeminiCliAdapter

class TestGeminiCliAdapterParity(unittest.TestCase):
 def setUp(self) -> None:
  self.adapter = GeminiCliAdapter(binary_path="gemini")

 def tearDown(self) -> None:
  pass

 def test_count_tokens_fallback(self) -> None:
  contents = ["Hello", "world!"]
  estimated = self.adapter.count_tokens(contents)
  self.assertEqual(estimated, 3)

 @patch('src.gemini_cli_adapter.subprocess.Popen')
 def test_send_starts_subprocess_with_model(self, mock_popen: MagicMock) -> None:
  mock_process = MagicMock()
  mock_process.communicate.return_value = ('{"type": "message", "content": "hi"}', '')
  mock_process.returncode = 0
  mock_popen.return_value = mock_process
  self.adapter.send("test", model="gemini-2.0-flash")
  args, _ = mock_popen.call_args
  cmd_list = args[0]
  self.assertIn("-m", cmd_list)
  self.assertIn("gemini-2.0-flash", cmd_list)

 @patch('src.gemini_cli_adapter.subprocess.Popen')
 def test_send_parses_tool_calls_from_streaming_json(self, mock_popen: MagicMock) -> None:
  tool_call_json = {
   "type": "tool_use",
   "tool_name": "list_directory",
   "parameters": {"path": "."},
   "tool_id": "call_abc"
  }
  mock_process = MagicMock()
  stdout_output = (
   json.dumps(tool_call_json) + "\n" +
   '{"type": "message", "content": "I listed the files."}'
  )
  mock_process.communicate.return_value = (stdout_output, '')
  mock_process.returncode = 0
  mock_popen.return_value = mock_process
  result = self.adapter.send("msg")
  self.assertEqual(len(result["tool_calls"]), 1)
  self.assertEqual(result["tool_calls"][0]["name"], "list_directory")
  self.assertEqual(result["text"], "I listed the files.")
