"""Tests for v0.36.0: from_anthropic_tool_use, from_anthropic_messages."""
import pytest
from llm_guard.agent_guard import AgentGuard


class _FakeBlock:
    def __init__(self, type, **kwargs):
        self.type = type
        for k, v in kwargs.items():
            setattr(self, k, v)


class _FakeResponse:
    def __init__(self, blocks):
        self.content = blocks


class TestFromAnthropicToolUse:

    def test_single_tool_use_block(self):
        block = _FakeBlock("tool_use", name="search", input={"query": "Paris capital"}, id="c1")
        resp = _FakeResponse([block])
        steps = AgentGuard.from_anthropic_tool_use(resp)
        assert len(steps) == 1
        assert steps[0]["action_type"] == "search"
        assert steps[0]["action_arg"] == "Paris capital"
        assert steps[0]["observation"] == ""

    def test_ignores_non_tool_use_blocks(self):
        blocks = [
            _FakeBlock("text", text="Let me search..."),
            _FakeBlock("tool_use", name="search", input={"query": "test"}, id="c1"),
        ]
        resp = _FakeResponse(blocks)
        steps = AgentGuard.from_anthropic_tool_use(resp)
        assert len(steps) == 1

    def test_empty_response(self):
        resp = _FakeResponse([])
        steps = AgentGuard.from_anthropic_tool_use(resp)
        assert steps == []

    def test_dict_blocks(self):
        """Also works with dict-style content blocks."""
        resp = _FakeResponse([{"type": "tool_use", "name": "search", "input": {"query": "test"}, "id": "c1"}])
        steps = AgentGuard.from_anthropic_tool_use(resp)
        assert len(steps) == 1
        assert steps[0]["action_type"] == "search"


class TestFromAnthropicMessages:

    def _make_messages(self):
        return [
            {"role": "user", "content": "What is the capital of France?"},
            {"role": "assistant", "content": [
                {"type": "text", "text": "Let me search."},
                {"type": "tool_use", "id": "tu1", "name": "search", "input": {"query": "capital France"}},
            ]},
            {"role": "user", "content": [
                {"type": "tool_result", "tool_use_id": "tu1", "content": "Paris is the capital."},
            ]},
            {"role": "assistant", "content": [
                {"type": "text", "text": "The capital is Paris."},
            ]},
        ]

    def test_basic_conversion(self):
        msgs = self._make_messages()
        steps = AgentGuard.from_anthropic_messages(msgs)
        assert len(steps) == 1
        assert steps[0]["action_type"] == "search"
        assert steps[0]["action_arg"] == "capital France"
        assert steps[0]["observation"] == "Paris is the capital."
        assert steps[0]["thought"] == "Let me search."

    def test_empty_messages(self):
        steps = AgentGuard.from_anthropic_messages([])
        assert steps == []

    def test_no_tool_calls(self):
        msgs = [
            {"role": "user", "content": "Hello"},
            {"role": "assistant", "content": "Hi there."},
        ]
        steps = AgentGuard.from_anthropic_messages(msgs)
        assert steps == []


class TestFromOpenaiMessages:

    def _make_messages(self):
        import json
        return [
            {"role": "user", "content": "What is the capital of France?"},
            {"role": "assistant", "content": "Let me search.",
             "tool_calls": [{"id": "c1", "type": "function",
                             "function": {"name": "search",
                                          "arguments": json.dumps({"query": "capital France"})}}]},
            {"role": "tool", "tool_call_id": "c1", "content": "Paris is the capital of France."},
            {"role": "assistant", "content": "The capital is Paris.", "tool_calls": None},
        ]

    def test_basic_conversion(self):
        msgs = self._make_messages()
        steps = AgentGuard.from_openai_messages(msgs)
        assert len(steps) == 1
        assert steps[0]["action_type"] == "search"
        assert steps[0]["action_arg"] == "capital France"
        assert steps[0]["observation"] == "Paris is the capital of France."
        assert steps[0]["thought"] == "Let me search."

    def test_empty_messages(self):
        steps = AgentGuard.from_openai_messages([])
        assert steps == []

    def test_no_tool_calls(self):
        msgs = [
            {"role": "user", "content": "Hello"},
            {"role": "assistant", "content": "Hi there."},
        ]
        steps = AgentGuard.from_openai_messages(msgs)
        assert steps == []

    def test_multiple_tool_calls(self):
        import json
        msgs = [
            {"role": "user", "content": "Multi step"},
            {"role": "assistant", "content": "",
             "tool_calls": [
                 {"id": "c1", "type": "function", "function": {"name": "search", "arguments": json.dumps({"query": "q1"})}},
                 {"id": "c2", "type": "function", "function": {"name": "lookup", "arguments": json.dumps({"query": "q2"})}},
             ]},
            {"role": "tool", "tool_call_id": "c1", "content": "result1"},
            {"role": "tool", "tool_call_id": "c2", "content": "result2"},
        ]
        steps = AgentGuard.from_openai_messages(msgs)
        assert len(steps) == 2
        assert steps[0]["observation"] == "result1"
        assert steps[1]["observation"] == "result2"
        assert steps[1]["action_type"] == "lookup"
