from __future__ import annotations

import unittest
from unittest.mock import patch

from src.langfuse_client import LangfuseHTTPClient, build_langfuse_client


class LangfuseClientTests(unittest.TestCase):
    def test_build_langfuse_client_falls_back_to_http(self) -> None:
        with patch("src.langfuse_client._build_sdk_client", side_effect=RuntimeError("sdk import failed")):
            client, backend, error = build_langfuse_client(
                public_key="pk-test",
                secret_key="sk-test",
                host="https://example.langfuse.com",
                environment="prod",
            )
        self.assertIsNone(error)
        self.assertEqual(backend, "http-fallback")
        self.assertIsNotNone(client)
        self.assertTrue(hasattr(client, "api"))

    def test_http_prompt_get_encodes_path(self) -> None:
        client = LangfuseHTTPClient(
            public_key="pk-test",
            secret_key="sk-test",
            host="https://example.langfuse.com",
        )
        with patch.object(client._transport, "request_json", return_value={"prompt": "hello"}) as mocked:
            response = client.get_prompt("folder/name", label="latest")
        self.assertEqual(response.prompt, "hello")
        _, kwargs = mocked.call_args
        self.assertEqual(kwargs["path"], "api/public/v2/prompts/folder%2Fname")

    def test_http_trace_list_maps_params(self) -> None:
        client = LangfuseHTTPClient(
            public_key="pk-test",
            secret_key="sk-test",
            host="https://example.langfuse.com",
            environment="prod",
        )
        with patch.object(client._transport, "request_json", return_value={"data": []}) as mocked:
            response = client.api.trace.list(limit=3, user_id="u-1")
        self.assertEqual(response.data, [])
        _, kwargs = mocked.call_args
        self.assertEqual(kwargs["path"], "api/public/traces")
        self.assertEqual(kwargs["params"]["limit"], 3)
        self.assertEqual(kwargs["params"]["userId"], "u-1")
        self.assertEqual(kwargs["params"]["environment"], "prod")


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