"""Tests for WebUI discovery and registration."""

from __future__ import annotations

from pathlib import Path
import textwrap

from agentbyte.webui.discovery import AgentbyteScanner
from agentbyte.webui.registry import EntityRegistry

from .helpers import DummyAgent, DummyOrchestrator


def test_registry_register_entity_extracts_agent_metadata() -> None:
    registry = EntityRegistry()
    info = registry.register_entity("dummy-agent", DummyAgent())

    assert info.type == "agent"
    assert info.name == "dummy-agent"
    assert info.model == "dummy-model"
    assert info.tools == []


def test_registry_register_entity_extracts_orchestrator_metadata() -> None:
    registry = EntityRegistry()
    orchestrator = DummyOrchestrator(DummyAgent())
    orchestrator.example_tasks = [
        "Review a short article about solar energy benefits.",
        "Review a note about remote work productivity.",
    ]
    info = registry.register_entity("dummy-orchestrator", orchestrator)

    assert info.type == "orchestrator"
    assert info.orchestrator_type == "DummyOrchestrator"
    assert info.agents == ["dummy-agent"]
    assert info.termination_conditions == ["MaxMessageTermination"]
    assert info.example_tasks == [
        "Review a short article about solar energy benefits.",
        "Review a note about remote work productivity.",
    ]


def test_scanner_discovers_agent_from_directory(tmp_path: Path) -> None:
    module_path = tmp_path / "demo_agent.py"
    module_path.write_text(
        textwrap.dedent(
            """
            from agentbyte.agents.base import BaseAgent
            from agentbyte.agents.types import AgentResponse
            from agentbyte.context import AgentContext
            from agentbyte.messages import AssistantMessage, Usage


            class _Model:
                model = "demo-model"


            class DemoAgent(BaseAgent):
                def __init__(self):
                    super().__init__(
                        name="demo-agent",
                        description="Discovered demo agent",
                        instructions="Be helpful",
                        model_client=_Model(),
                    )

                async def run(self, task=None, context=None, cancellation_token=None):
                    ctx = context or AgentContext()
                    msg = AssistantMessage(content="ok", source=self.name)
                    ctx.add_message(msg)
                    return AgentResponse(context=ctx, source=self.name, finish_reason="stop", usage=Usage())

                async def run_stream(self, task=None, context=None, cancellation_token=None, verbose=False, stream_tokens=False):
                    response = await self.run(task=task, context=context, cancellation_token=cancellation_token)
                    yield response


            agent = DemoAgent()
            """
        )
    )

    scanner = AgentbyteScanner(str(tmp_path))
    entities = scanner.discover_entities()

    assert len(entities) == 1
    assert entities[0].type == "agent"
    assert entities[0].name == "demo-agent"
