"""Tests for ToolCall.to_dict() JSON-string fix and BaileysWhatsAppAdapter."""

import json

import pytest

from neuralclaw.providers.router import ToolCall
from neuralclaw.channels.whatsapp_baileys import BaileysWhatsAppAdapter


# ---------------------------------------------------------------------------
# ToolCall.to_dict() — arguments must be a JSON string
# ---------------------------------------------------------------------------


class TestToolCallToDict:
    def test_arguments_is_json_string(self):
        tc = ToolCall(id="call_1", name="get_weather", arguments={"city": "Karachi"})
        result = tc.to_dict()
        args = result["function"]["arguments"]
        assert isinstance(args, str), f"Expected str, got {type(args)}"
        assert json.loads(args) == {"city": "Karachi"}

    def test_empty_arguments(self):
        tc = ToolCall(id="call_2", name="noop", arguments={})
        result = tc.to_dict()
        assert result["function"]["arguments"] == "{}"

    def test_nested_arguments_serialized(self):
        nested = {"filters": {"status": "active", "tags": ["a", "b"]}}
        tc = ToolCall(id="call_3", name="search", arguments=nested)
        result = tc.to_dict()
        assert json.loads(result["function"]["arguments"]) == nested

    def test_dict_structure(self):
        tc = ToolCall(id="call_4", name="fn", arguments={"x": 1})
        d = tc.to_dict()
        assert d["id"] == "call_4"
        assert d["type"] == "function"
        assert d["function"]["name"] == "fn"


# ---------------------------------------------------------------------------
# BaileysWhatsAppAdapter — basic unit tests (no subprocess)
# ---------------------------------------------------------------------------


class TestBaileysWhatsAppAdapter:
    def test_name(self):
        adapter = BaileysWhatsAppAdapter()
        assert adapter.name == "whatsapp-baileys"

    def test_custom_auth_dir(self):
        adapter = BaileysWhatsAppAdapter(auth_dir="/tmp/my_auth")
        assert adapter._auth_dir == "/tmp/my_auth"

    def test_bridge_script_contains_baileys(self):
        adapter = BaileysWhatsAppAdapter()
        script = adapter._get_bridge_script()
        assert "@whiskeysockets/baileys" in script
        assert "puppeteer" not in script.lower()

    def test_bridge_script_uses_auth_dir(self):
        adapter = BaileysWhatsAppAdapter(auth_dir="my_custom_auth")
        script = adapter._get_bridge_script()
        assert "my_custom_auth" in script

    def test_on_qr_callback_stored(self):
        cb = lambda qr: None
        adapter = BaileysWhatsAppAdapter(on_qr=cb)
        assert adapter._on_qr is cb

    @pytest.mark.asyncio
    async def test_send_raises_when_not_running(self):
        adapter = BaileysWhatsAppAdapter()
        with pytest.raises(RuntimeError, match="not running"):
            await adapter.send("123@s.whatsapp.net", "hello")

    def test_callbacks_inherited(self):
        adapter = BaileysWhatsAppAdapter()
        assert hasattr(adapter, "_callbacks")
        assert adapter._callbacks == []
