"""Test MCP client helpers: headers, exception unwrapping, error mapping."""

import pytest
from mcpbundles.mcp_client import (
    _build_headers,
    _unwrap_exception,
    ConnectionError,
    ToolCallError,
    extract_text,
    extract_json,
)
from mcp.types import CallToolResult, TextContent, ImageContent


class TestBuildHeaders:
    def test_api_key(self):
        h = _build_headers("mb_test_key_123")
        assert h == {"X-API-Key": "mb_test_key_123"}
        assert "Authorization" not in h

    def test_bearer_token(self):
        h = _build_headers("eyJtoken.stuff.here")
        assert h == {"Authorization": "Bearer eyJtoken.stuff.here"}
        assert "X-API-Key" not in h

    def test_session_id(self):
        h = _build_headers("mb_key", session_id="sess-abc")
        assert h["Mcp-Session-Id"] == "sess-abc"
        assert h["X-API-Key"] == "mb_key"

    def test_no_session_id(self):
        h = _build_headers("mb_key")
        assert "Mcp-Session-Id" not in h

    def test_empty_session_id_excluded(self):
        h = _build_headers("mb_key", session_id="")
        assert "Mcp-Session-Id" not in h


class TestUnwrapException:
    def test_plain_exception(self):
        exc = ValueError("test")
        assert _unwrap_exception(exc) is exc

    def test_single_level_group(self):
        inner = ValueError("inner")
        group = BaseExceptionGroup("group", [inner])
        assert _unwrap_exception(group) is inner

    def test_nested_groups(self):
        inner = RuntimeError("deep")
        level1 = BaseExceptionGroup("l1", [inner])
        level2 = BaseExceptionGroup("l2", [level1])
        assert _unwrap_exception(level2) is inner

    def test_empty_group_returns_group(self):
        group = BaseExceptionGroup("empty", [ValueError("x")])
        result = _unwrap_exception(group)
        assert isinstance(result, ValueError)


class TestToolCallError:
    def test_message(self):
        exc = ToolCallError("tool failed")
        assert str(exc) == "tool failed"

    def test_content_preserved(self):
        content = [TextContent(type="text", text="details")]
        exc = ToolCallError("fail", content=content)
        assert exc.content == content


class TestExtractText:
    def test_single_text(self):
        result = CallToolResult(
            content=[TextContent(type="text", text="hello")],
            isError=False,
        )
        assert extract_text(result) == "hello"

    def test_multiple_text(self):
        result = CallToolResult(
            content=[
                TextContent(type="text", text="line1"),
                TextContent(type="text", text="line2"),
            ],
            isError=False,
        )
        assert extract_text(result) == "line1\nline2"

    def test_mixed_content_skips_images(self):
        result = CallToolResult(
            content=[
                TextContent(type="text", text="text"),
                ImageContent(type="image", data="abc", mimeType="image/png"),
            ],
            isError=False,
        )
        assert extract_text(result) == "text"

    def test_empty_content(self):
        result = CallToolResult(content=[], isError=False)
        assert extract_text(result) == ""


class TestExtractJson:
    def test_valid_json(self):
        result = CallToolResult(
            content=[TextContent(type="text", text='{"key": "value"}')],
            isError=False,
        )
        assert extract_json(result) == {"key": "value"}

    def test_invalid_json_returns_text(self):
        result = CallToolResult(
            content=[TextContent(type="text", text="plain text")],
            isError=False,
        )
        assert extract_json(result) == "plain text"
