import httpx
import respx

from whatsrb_cloud import WhatsrbCloud
from whatsrb_cloud.objects.agent import Agent
from whatsrb_cloud.objects.list_response import ListResponse

BASE_URL = "https://whatsrb.com/api/v1"

AGENT_DATA = {
    "id": "agt_1",
    "name": "Support Bot",
    "description": "Handles support",
    "system_prompt": "You are a support agent",
    "model": "gpt-4",
    "temperature": 0.7,
    "max_tokens": 1024,
    "active": True,
    "auto_run_inbound": False,
    "allowed_actions": ["support.ticket.create"],
    "created_at": "2025-01-01T00:00:00Z",
    "updated_at": "2025-01-01T00:00:00Z",
}


class TestAgentsResource:
    @respx.mock
    def test_list(self):
        respx.get(f"{BASE_URL}/agents").mock(
            return_value=httpx.Response(200, json={"data": [AGENT_DATA], "meta": {"total": 1}})
        )
        client = WhatsrbCloud("wrb_test")
        result = client.agents.list()
        assert isinstance(result, ListResponse)
        assert len(result) == 1
        assert result[0].name == "Support Bot"

    @respx.mock
    def test_create(self):
        respx.post(f"{BASE_URL}/agents").mock(
            return_value=httpx.Response(201, json={"data": AGENT_DATA})
        )
        client = WhatsrbCloud("wrb_test")
        agent = client.agents.create(name="Support Bot", system_prompt="You are a support agent")
        assert isinstance(agent, Agent)
        assert agent.id == "agt_1"
        assert agent.name == "Support Bot"

    @respx.mock
    def test_retrieve(self):
        respx.get(f"{BASE_URL}/agents/agt_1").mock(
            return_value=httpx.Response(200, json={"data": AGENT_DATA})
        )
        client = WhatsrbCloud("wrb_test")
        agent = client.agents.retrieve("agt_1")
        assert agent.id == "agt_1"
        assert agent.is_active is True
        assert agent.is_auto_run is False

    @respx.mock
    def test_update(self):
        updated = {**AGENT_DATA, "name": "Updated Bot"}
        respx.patch(f"{BASE_URL}/agents/agt_1").mock(
            return_value=httpx.Response(200, json={"data": updated})
        )
        client = WhatsrbCloud("wrb_test")
        agent = client.agents.update("agt_1", name="Updated Bot")
        assert agent.name == "Updated Bot"

    @respx.mock
    def test_delete(self):
        respx.delete(f"{BASE_URL}/agents/agt_1").mock(
            return_value=httpx.Response(204, text="")
        )
        client = WhatsrbCloud("wrb_test")
        assert client.agents.delete("agt_1") is True

    @respx.mock
    def test_agent_to_dict(self):
        respx.get(f"{BASE_URL}/agents/agt_1").mock(
            return_value=httpx.Response(200, json={"data": AGENT_DATA})
        )
        client = WhatsrbCloud("wrb_test")
        agent = client.agents.retrieve("agt_1")
        assert agent.to_dict() == AGENT_DATA
