from beaver.engine import AgentLoop, EngineLoader
from beaver.foundation.events import InboundMessage, MessageBus, OutboundMessage
from beaver.interfaces.channels import ChannelManager, MemoryChannelAdapter
from beaver.interfaces.gateway.main import run_gateway
from beaver.interfaces.web.app import create_app
from beaver.interfaces.web.schemas import WebChatRequest, WebChatResponse


def test_platform_channel_modules_import_without_live_clients() -> None:
    from beaver.interfaces.channels.platforms.feishu import FeishuAdapter
    from beaver.interfaces.channels.platforms.qqbot import QQBotAdapter
    from beaver.interfaces.channels.platforms.telegram import TelegramAdapter
    from beaver.interfaces.channels.platforms.weixin import WeixinAdapter

    assert FeishuAdapter.KIND == "feishu"
    assert QQBotAdapter.KIND == "qqbot"
    assert TelegramAdapter.KIND == "telegram"
    assert WeixinAdapter.KIND == "weixin"


def test_platform_channel_optional_extras_are_declared() -> None:
    import tomllib
    from pathlib import Path

    pyproject = Path(__file__).resolve().parents[2] / "pyproject.toml"
    data = tomllib.loads(pyproject.read_text(encoding="utf-8"))
    extras = data["project"]["optional-dependencies"]

    assert "python-telegram-bot>=22.0,<23.0" in extras["telegram"]
    assert "lark-oapi>=1.4.22,<2.0.0" in extras["feishu"]
    assert "aiohttp>=3.9.0,<4.0.0" in extras["qqbot"]
    assert "aiohttp>=3.9.0,<4.0.0" in extras["weixin"]
    assert "python-telegram-bot>=22.0,<23.0" in extras["channels"]
    assert "lark-oapi>=1.4.22,<2.0.0" in extras["channels"]


def test_agent_loop_boots(tmp_path) -> None:
    loop = AgentLoop(loader=EngineLoader(workspace=tmp_path))
    loaded = loop.boot()
    assert "echo" in loaded.tools
    assert "memory" in loaded.tools
    assert "session_search" in loaded.tools


def test_web_app_factory() -> None:
    app = create_app()
    assert app.title == "Beaver Backend"


def test_gateway_entry_imports() -> None:
    assert callable(run_gateway)


def test_message_bus_imports() -> None:
    bus = MessageBus()
    assert isinstance(bus, MessageBus)
    assert InboundMessage(channel="test", content="hello").channel == "test"
    assert OutboundMessage(channel="test", content="ok", session_id=None, finish_reason="stop").content == "ok"


def test_channel_imports() -> None:
    bus = MessageBus()
    class Sink:
        async def accept_inbound(self, message):
            await bus.publish_inbound(message)

    channel = MemoryChannelAdapter(Sink())
    manager = ChannelManager(bus)
    manager.register(channel)
    assert manager.channels["memory-dev"] is channel


def test_web_schema_imports() -> None:
    assert WebChatRequest(message="hello").message == "hello"
    assert WebChatResponse(
        session_id="s",
        run_id="r",
        output_text="ok",
        finish_reason="stop",
        tool_iterations=0,
    ).output_text == "ok"
