import sys
import unittest
from pathlib import Path
from unittest.mock import MagicMock

ROOT = Path(__file__).resolve().parents[1] / "src"
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))

from hieromem_client import HieromemClient


class TestHieromemClient(unittest.TestCase):
    def setUp(self):
        self.session = MagicMock()
        self.client = HieromemClient(
            base_url="http://test-api.com",
            api_key="secret",
            session=self.session,
        )

    def _stub_response(self, payload):
        response = MagicMock()
        response.json.return_value = payload
        response.status_code = 200
        response.headers = {"content-type": "application/json"}
        self.session.request.return_value = response
        return response

    def test_remember(self):
        self._stub_response({"id": "ep-123"})

        result = self.client.remember("Hello world", namespace="ns1")

        self.assertEqual(result["id"], "ep-123")
        self.session.request.assert_called_once()
        args, kwargs = self.session.request.call_args
        self.assertEqual(args[0], "POST")
        self.assertEqual(args[1], "http://test-api.com/memory/remember")
        self.assertEqual(kwargs["json"]["namespace"], "ns1")
        self.assertIn("X-API-Key", kwargs["headers"])
        self.assertEqual(kwargs["headers"]["X-API-Key"], "secret")

    def test_dual_recall(self):
        self._stub_response({"results": [{"id": "ep-1", "score": 0.9}]})

        result = self.client.dual_recall("query", k=5)

        self.assertEqual(len(result["results"]), 1)
        self.assertEqual(result["results"][0]["id"], "ep-1")
        self.session.request.assert_called_once()
        args, kwargs = self.session.request.call_args
        self.assertEqual(kwargs["json"]["k"], 5)

    def test_health_uses_get(self):
        self._stub_response({"status": "ok"})

        result = self.client.health()

        self.assertEqual(result["status"], "ok")
        args, _ = self.session.request.call_args
        self.assertEqual(args[0], "GET")


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