"""远程传输层 - Phase 10.2"""

import asyncio
import json
from typing import Any
from dataclasses import dataclass


@dataclass
class StructuredMessage:
    """结构化消息"""

    type: str  # response, event, tool_call, error
    data: dict[str, Any]
    session_id: str | None = None


class RemoteTransport:
    """远程传输层

    处理与远程 Agent 的通信。
    """

    def __init__(self):
        self._connections: dict[str, Any] = {}
        self._handlers: dict[str, Any] = {}

    async def send_response(self, session_id: str, response: dict[str, Any]) -> bool:
        """发送响应

        Args:
            session_id: 会话 ID
            response: 响应数据

        Returns:
            是否发送成功
        """
        message = StructuredMessage(
            type="response",
            data=response,
            session_id=session_id,
        )
        return await self._send(session_id, message)

    async def send_event(self, session_id: str, event: dict[str, Any]) -> bool:
        """发送事件

        Args:
            session_id: 会话 ID
            event: 事件数据

        Returns:
            是否发送成功
        """
        message = StructuredMessage(
            type="event",
            data=event,
            session_id=session_id,
        )
        return await self._send(session_id, message)

    async def send_tool_call(self, session_id: str, tool_call: dict[str, Any]) -> bool:
        """发送工具调用

        Args:
            session_id: 会话 ID
            tool_call: 工具调用数据

        Returns:
            是否发送成功
        """
        message = StructuredMessage(
            type="tool_call",
            data=tool_call,
            session_id=session_id,
        )
        return await self._send(session_id, message)

    async def _send(self, session_id: str, message: StructuredMessage) -> bool:
        """内部发送方法"""
        if session_id not in self._connections:
            return False

        try:
            connection = self._connections[session_id]
            if hasattr(connection, "send"):
                await connection.send(json.dumps(message.__dict__))
                return True
        except Exception:
            pass

        return False

    def register_handler(self, event_type: str, handler: Any) -> None:
        """注册消息处理器

        Args:
            event_type: 事件类型
            handler: 处理函数
        """
        self._handlers[event_type] = handler

    async def handle_message(self, session_id: str, message: dict[str, Any]) -> None:
        """处理收到的消息

        Args:
            session_id: 会话 ID
            message: 消息数据
        """
        msg_type = message.get("type")
        handler = self._handlers.get(msg_type)
        if handler:
            await handler(session_id, message.get("data"))
