"""Message tool for subagents to communicate with the main agent."""

from typing import Any, TYPE_CHECKING

from nanobot.agent.tools.base import Tool
from nanobot.bus.events import InboundMessage

if TYPE_CHECKING:
    from nanobot.bus.queue import MessageBus


class SubagentMessageTool(Tool):
    """
    Tool for subagents to send messages to the main agent.

    Messages are sent via the bus and preserve metadata (e.g. suppress_output)
    from the originating message that spawned the subagent.
    """

    def __init__(
        self,
        bus: "MessageBus",
        origin_channel: str,
        origin_chat_id: str,
        origin_metadata: dict[str, Any] | None = None,
    ):
        self._bus = bus
        self._origin_channel = origin_channel
        self._origin_chat_id = origin_chat_id
        self._origin_metadata = origin_metadata or {}

    @property
    def name(self) -> str:
        return "message"

    @property
    def description(self) -> str:
        return (
            "Send a message to the main agent. "
            "Use this to communicate findings, request clarification, or provide updates. "
            "The main agent will process your message and decide how to respond."
        )

    @property
    def parameters(self) -> dict[str, Any]:
        return {
            "type": "object",
            "properties": {
                "content": {
                    "type": "string",
                    "description": "The message content to send to the main agent"
                },
            },
            "required": ["content"]
        }

    async def execute(self, content: str, **kwargs: Any) -> str:
        """Send a message to the main agent via the bus."""
        # Create InboundMessage to trigger main agent
        msg = InboundMessage(
            channel="system",
            sender_id="subagent",
            chat_id=f"{self._origin_channel}:{self._origin_chat_id}",
            content=f"[Subagent message]\n\n{content}",
            metadata=self._origin_metadata,
        )

        try:
            await self._bus.publish_inbound(msg)
            return "Message sent to main agent"
        except Exception as e:
            return f"Error sending message: {str(e)}"
