"""Router Agent — 基于 claude_agent_sdk 的智能路由代理

负责：
1. 理解用户需求，撰写任务书
2. 调度 CodingAgent 创建工具
3. 搜索和调用已有工具
4. 提供命令行交互界面
"""

from __future__ import annotations

import asyncio
import json
import logging
from typing import TYPE_CHECKING

from claude_agent_sdk import (
    AssistantMessage, UserMessage, ResultMessage,
    TextBlock, ClaudeAgentOptions, tool,
    create_sdk_mcp_server, ClaudeSDKClient, ThinkingBlock, ToolUseBlock,
)

if TYPE_CHECKING:
    from tool_agent.router.agent import Router

logger = logging.getLogger(__name__)


# ===========================================================================
#  Router Agent 工具定义
# ===========================================================================

@tool(name="search_tools", description="""
搜索已注册的工具列表。

Args:
    keyword: 搜索关键词（可选），匹配工具名称或描述
    category: 工具分类（可选），如 "cv", "nlp", "devtools"

Returns:
    工具列表，包含 tool_id、名称、描述、参数、运行状态等
""", input_schema={
    "type": "object",
    "properties": {
        "keyword": {"type": "string", "description": "搜索关键词"},
        "category": {"type": "string", "description": "工具分类"},
    },
})
async def search_tools_fn(args):
    """搜索工具"""
    if not _router_instance:
        return _text_result({"status": "error", "error": "Router not initialized"})

    all_tools = _router_instance.registry.list_all()
    matched = all_tools

    if args.get("category"):
        matched = [t for t in matched if t.category == args["category"]]
    if args.get("keyword"):
        kw = args["keyword"].lower()
        matched = [t for t in matched if kw in t.name.lower() or kw in t.description.lower()]

    tools_info = []
    for tool in matched:
        status = _router_instance.status_manager.get_status(tool.tool_id)

        # 解析参数列表
        params = []
        if tool.input_schema and "properties" in tool.input_schema:
            required_fields = tool.input_schema.get("required", [])
            for param_name, param_def in tool.input_schema["properties"].items():
                params.append({
                    "name": param_name,
                    "type": param_def.get("type", "string"),
                    "required": param_name in required_fields,
                    "description": param_def.get("description", ""),
                })

        tools_info.append({
            "tool_id": tool.tool_id,
            "name": tool.name,
            "description": tool.description,
            "category": tool.category,
            "backend_runtime": tool.backend_runtime.value if tool.backend_runtime else "unknown",
            "group_ids": tool.group_ids,
            "state": status.state.value if status else "unknown",
            "params": params,
        })

    return _text_result({
        "status": "success",
        "total": len(tools_info),
        "tools": tools_info,
    })


@tool(name="call_tool", description="""
调用已注册的工具。如果工具未启动，会自动启动。

Args:
    tool_id: 工具 ID
    params: 工具参数（JSON 对象）

Returns:
    工具执行结果
""", input_schema={
    "type": "object",
    "properties": {
        "tool_id": {"type": "string", "description": "工具 ID"},
        "params": {"type": "object", "description": "工具参数"},
    },
    "required": ["tool_id", "params"],
})
async def call_tool_fn(args):
    """调用工具"""
    if not _router_instance:
        return _text_result({"status": "error", "error": "Router not initialized"})

    tool_id = args["tool_id"]
    params = args.get("params", {})

    try:
        result = await _router_instance.dispatcher.dispatch(tool_id, params)
        return _text_result({"status": "success", "result": result})
    except Exception as e:
        return _text_result({"status": "error", "error": str(e)})


@tool(name="create_tool", description="""
创建新工具。根据用户需求撰写详细任务书，提交给 CodingAgent 异步执行。

**重要**：你需要先理解用户需求，然后撰写一个详细的任务书（task_spec）。

任务书必须包含：
1. 功能描述
2. 输入输出的 JSON Schema
3. 实现要求（使用 uv 还是 Docker）
4. tool_id（小写字母+下划线）
5. 明确要求"必须注册到 Router"

Args:
    tool_id: 工具 ID（小写字母+下划线），如 "image_compressor"
    description: 简短功能描述
    task_spec: 详细任务书（包含功能需求、接口定义、实现要求）
    reference_files: 参考文件路径列表（可选）

Returns:
    task_id 和状态
""", input_schema={
    "type": "object",
    "properties": {
        "tool_id": {"type": "string", "description": "工具 ID"},
        "description": {"type": "string", "description": "简短功能描述"},
        "task_spec": {"type": "string", "description": "详细任务书"},
        "reference_files": {"type": "array", "items": {"type": "string"}, "description": "参考文件路径"},
    },
    "required": ["tool_id", "description", "task_spec"],
})
async def create_tool_fn(args):
    """创建工具"""
    import uuid

    if not _router_instance:
        return _text_result({"status": "error", "error": "Router not initialized"})

    task_id = f"create_{uuid.uuid4().hex[:8]}"
    task_spec = args.get("task_spec") or args["description"]
    reference_files = args.get("reference_files", [])

    _router_instance.submit_create_task(task_id, task_spec, reference_files)

    return _text_result({
        "status": "success",
        "task_id": task_id,
        "message": "Task submitted, use check_task_status to monitor progress",
    })


@tool(name="check_task_status", description="""
查询异步任务状态。

Args:
    task_id: 任务 ID

Returns:
    任务状态（pending/running/completed/failed）和结果
""", input_schema={
    "type": "object",
    "properties": {
        "task_id": {"type": "string", "description": "任务 ID"},
    },
    "required": ["task_id"],
})
async def check_task_status_fn(args):
    """查询任务状态"""
    if not _router_instance:
        return _text_result({"status": "error", "error": "Router not initialized"})

    task = _router_instance.get_task_status(args["task_id"])
    if not task:
        return _text_result({"status": "error", "error": "Task not found"})

    return _text_result(task)


@tool(name="list_all_tools", description="""
列出所有已注册的工具，包含详细信息。

Returns:
    所有工具的列表，包含 tool_id、名称、描述、状态、参数等
""", input_schema={
    "type": "object",
    "properties": {},
})
async def list_all_tools_fn(args):
    """列出所有工具"""
    if not _router_instance:
        return _text_result({"status": "error", "error": "Router not initialized"})

    all_tools = _router_instance.registry.list_all()
    tools_info = []

    for tool in all_tools:
        status = _router_instance.status_manager.get_status(tool.tool_id)
        tools_info.append({
            "tool_id": tool.tool_id,
            "name": tool.name,
            "description": tool.description,
            "category": tool.category,
            "backend_runtime": tool.backend_runtime.value if tool.backend_runtime else "unknown",
            "group_ids": tool.group_ids,
            "state": status.state.value if status else "unknown",
            "port": status.port if status else None,
        })

    return _text_result({
        "status": "success",
        "total": len(tools_info),
        "tools": tools_info,
    })


@tool(name="get_tool_details", description="""
获取指定工具的详细信息，包括参数定义、输出格式、运行状态等。

Args:
    tool_id: 工具 ID

Returns:
    工具的完整信息
""", input_schema={
    "type": "object",
    "properties": {
        "tool_id": {"type": "string", "description": "工具 ID"},
    },
    "required": ["tool_id"],
})
async def get_tool_details_fn(args):
    """获取工具详细信息"""
    if not _router_instance:
        return _text_result({"status": "error", "error": "Router not initialized"})

    tool = _router_instance.registry.get(args["tool_id"])
    if not tool:
        return _text_result({"status": "error", "error": f"Tool '{args['tool_id']}' not found"})

    status = _router_instance.status_manager.get_status(args["tool_id"])

    return _text_result({
        "status": "success",
        "tool": {
            "tool_id": tool.tool_id,
            "name": tool.name,
            "description": tool.description,
            "category": tool.category,
            "backend_runtime": tool.backend_runtime.value if tool.backend_runtime else "unknown",
            "group_ids": tool.group_ids,
            "input_schema": tool.input_schema,
            "output_schema": tool.output_schema,
            "stream_support": tool.stream_support,
            "state": status.state.value if status else "unknown",
            "port": status.port if status else None,
            "pid": status.pid if status else None,
        }
    })


@tool(name="get_tools_status", description="""
获取所有工具的运行状态。

Returns:
    所有工具的状态信息（运行中/已停止/错误等）
""", input_schema={
    "type": "object",
    "properties": {},
})
async def get_tools_status_fn(args):
    """获取工具状态"""
    if not _router_instance:
        return _text_result({"status": "error", "error": "Router not initialized"})

    statuses = _router_instance.status_manager.list_status()
    status_info = []

    for status in statuses:
        status_info.append({
            "tool_id": status.tool_id,
            "state": status.state,
            "port": status.port,
            "pid": status.pid,
            "last_error": status.last_error,
        })

    return _text_result({
        "status": "success",
        "total": len(status_info),
        "tools": status_info,
    })


@tool(name="list_backend_runtimes", description="""
列出所有后端执行环境类型（local/docker/remote）及其说明。

注意：所有工具对外都是统一的本地 Python/FastAPI 调用层，backend_runtime 表示工具内部的执行目标。

Returns:
    后端运行时列表，包含名称、描述、工具数量
""", input_schema={
    "type": "object",
    "properties": {},
})
async def list_backend_runtimes_fn(args):
    """列出后端执行环境"""
    if not _router_instance:
        return _text_result({"status": "error", "error": "Router not initialized"})

    runtimes = [
        {
            "backend_runtime": "local",
            "name": "本地 Python 运行时",
            "description": "使用 uv 管理的本地 Python 进程，启动快、资源占用少，适合纯 Python 任务",
            "tool_count": len(_router_instance.registry.find_by_backend_runtime("local")),
        },
        {
            "backend_runtime": "docker",
            "name": "Docker 容器运行时",
            "description": "运行在 Docker 容器中，适合需要系统库、GPU 或隔离环境的场景",
            "tool_count": len(_router_instance.registry.find_by_backend_runtime("docker")),
        },
        {
            "backend_runtime": "remote",
            "name": "远程 API / 云端服务",
            "description": "调用外部 API 或云端服务，如 RunComfy、LiblibAI 等第三方平台",
            "tool_count": len(_router_instance.registry.find_by_backend_runtime("remote")),
        },
    ]

    return _text_result({
        "status": "success",
        "total": len(runtimes),
        "backend_runtimes": runtimes,
    })


@tool(name="list_groups", description="""
列出所有工具组。

Returns:
    所有工具组的列表，包含组名、描述、工具列表和使用顺序
""", input_schema={
    "type": "object",
    "properties": {},
})
async def list_groups_fn(args):
    """列出工具组"""
    if not _router_instance:
        return _text_result({"status": "error", "error": "Router not initialized"})

    groups = _router_instance.registry.group_manager.list_all()
    group_info = []

    for group in groups:
        group_info.append({
            "group_id": group.group_id,
            "name": group.name,
            "description": group.description,
            "category": group.category.value,
            "tool_ids": group.tool_ids,
            "usage_order": group.usage_order,
            "usage_example": group.usage_example,
        })

    return _text_result({
        "status": "success",
        "total": len(group_info),
        "groups": group_info,
    })


@tool(name="get_group_details", description="""
获取指定工具组的详细信息。

Args:
    group_id: 工具组 ID

Returns:
    工具组的完整信息
""", input_schema={
    "type": "object",
    "properties": {
        "group_id": {"type": "string", "description": "工具组 ID"},
    },
    "required": ["group_id"],
})
async def get_group_details_fn(args):
    """获取工具组详细信息"""
    if not _router_instance:
        return _text_result({"status": "error", "error": "Router not initialized"})

    group = _router_instance.registry.group_manager.get_group(args["group_id"])
    if not group:
        return _text_result({"status": "error", "error": f"Group '{args['group_id']}' not found"})

    tools = _router_instance.registry.get_tools_in_group(args["group_id"])

    return _text_result({
        "status": "success",
        "group": {
            "group_id": group.group_id,
            "name": group.name,
            "description": group.description,
            "category": group.category.value,
            "tool_ids": group.tool_ids,
            "usage_order": group.usage_order,
            "usage_example": group.usage_example,
            "tools": [
                {
                    "tool_id": t.tool_id,
                    "name": t.name,
                    "description": t.description,
                }
                for t in tools
            ],
        }
    })


@tool(name="list_tasks", description="""
列出所有异步任务及其状态。

Returns:
    所有任务的列表
""", input_schema={
    "type": "object",
    "properties": {},
})
async def list_tasks_fn(args):
    """列出所有任务"""
    if not _router_instance:
        return _text_result({"status": "error", "error": "Router not initialized"})

    tasks = []
    for task_id, task_data in _router_instance._tasks.items():
        tasks.append({
            "task_id": task_id,
            "status": task_data.get("status"),
            "task_spec": task_data.get("task_spec", "")[:100],  # 只显示前100字符
        })

    return _text_result({
        "status": "success",
        "total": len(tasks),
        "tasks": tasks,
    })


# ===========================================================================
#  辅助函数
# ===========================================================================

def _text_result(data: dict) -> dict:
    """将 dict 包装为 claude_agent_sdk 的 tool 返回格式"""
    return {"content": [{"type": "text", "text": json.dumps(data, ensure_ascii=False, indent=2)}]}


def _build_dynamic_context(router: "Router") -> str:
    """构造 Router Agent 的动态系统上下文"""
    runtimes = [
        {
            "backend_runtime": "local",
            "name": "本地 Python 运行时",
            "description": "使用 uv 管理的本地 Python 进程，启动快、资源占用少，适合纯 Python 任务",
            "tool_count": len(router.registry.find_by_backend_runtime("local")),
        },
        {
            "backend_runtime": "docker",
            "name": "Docker 容器运行时",
            "description": "运行在 Docker 容器中，适合需要系统库、GPU 或隔离环境的场景",
            "tool_count": len(router.registry.find_by_backend_runtime("docker")),
        },
        {
            "backend_runtime": "remote",
            "name": "远程 API / 云端服务",
            "description": "调用外部 API 或云端服务，如 RunComfy、LiblibAI 等第三方平台",
            "tool_count": len(router.registry.find_by_backend_runtime("remote")),
        },
    ]

    groups = []
    for g in router.registry.group_manager.list_all():
        groups.append({
            "group_id": g.group_id,
            "name": g.name,
            "description": g.description,
            "category": g.category.value,
            "tool_ids": g.tool_ids,
            "usage_order": g.usage_order,
        })

    tools = []
    for tool in router.registry.list_all():
        route = router.status_manager.get_status(tool.tool_id)
        state = route.state.value if route else "stopped"
        tools.append({
            "tool_id": tool.tool_id,
            "name": tool.name,
            "description": tool.description,
            "category": tool.category,
            "backend_runtime": tool.backend_runtime.value if tool.backend_runtime else "unknown",
            "group_ids": tool.group_ids,
            "state": state,
            "port": route.port if route else None,
        })

    coding_status = router.get_coding_agent_status()
    tasks = [
        {"task_id": tid, "status": data.get("status"), "task_spec": data.get("task_spec", "")[:120]}
        for tid, data in list(router._tasks.items())[-10:]
    ]

    return json.dumps({
        "backend_runtimes": runtimes,
        "groups": groups,
        "tools": tools,
        "coding_agent": coding_status,
        "recent_tasks": tasks,
    }, ensure_ascii=False, indent=2)


# ===========================================================================
#  Router Agent System Prompt
# ===========================================================================

ROUTER_AGENT_SYSTEM_PROMPT = """你是 Router Agent，Tool Agent 系统的智能客服和工具管理员。

**重要：你不是 Claude，你是 Router Agent。请始终以 Router Agent 的身份回答问题。**

## 你的角色定位

你是一个**友好、专业的客服**，负责：
1. **帮助用户使用工具**：解答工具使用问题、调用工具、处理错误
2. **管理工具库**：搜索、推荐、调用已有工具
3. **创建新工具**：理解需求、撰写任务书、调度 CodingAgent
4. **提供技术支持**：解决接口问题、参数错误、调用失败等

## 你拥有的工具

**工具管理：**
- `search_tools`: 搜索工具（支持关键词和分类）
- `list_all_tools`: 列出所有工具
- `get_tool_details`: 获取工具详细信息（参数、输出格式等）
- `get_tools_status`: 获取所有工具的运行状态
- `list_backend_runtimes`: 列出后端执行环境类型及说明
- `list_groups`: 列出固定配合使用的工具组
- `get_group_details`: 获取工具组详细信息和推荐使用顺序

**工具操作：**
- `call_tool`: 调用已注册的工具
- `create_tool`: 创建新工具（提交任务书给 CodingAgent）

**任务管理：**
- `list_tasks`: 列出所有异步任务
- `check_task_status`: 查询任务状态

## 工作流程

### 1. 用户咨询工具使用
**场景**：用户询问"如何使用 XXX 工具"、"XXX 工具的参数是什么"
**处理**：
- 使用 `search_tools` 查找工具
- 详细说明工具的功能、参数、使用方法
- 提供示例调用

### 2. 用户请求调用工具
**场景**：用户说"帮我压缩这张图片"、"用 XXX 工具处理"
**处理**：
- 确认工具 ID 和参数
- 使用 `call_tool` 调用工具
- 返回结果或错误信息
- 如果失败，提供解决方案

### 3. 用户请求创建工具
**场景**：用户说"我需要一个 XXX 工具"、"能不能做 XXX"
**处理**：
1. 先使用 `search_tools` 搜索是否已有类似工具
2. 如果没有，询问详细需求：
   - 输入是什么？（文件、文本、URL？）
   - 输出是什么？（文件、JSON、图片？）
   - 有什么特殊要求？
3. **撰写详细任务书**（这是最重要的步骤）：
   ```
   ## 目标
   创建一个 HTTP API 工具并注册到 Router，用于 [功能描述]

   ## 核心功能
   [详细功能说明]

   ## HTTP API 接口（必须实现）
   实现 POST /[endpoint] 接口：

   ### 输入 JSON Schema
   {
     "type": "object",
     "properties": {
       "param1": {"type": "string", "description": "参数说明"},
       ...
     },
     "required": ["param1"]
   }

   ### 输出 JSON Schema
   {
     "type": "object",
     "properties": {
       "result": {"type": "string", "description": "结果说明"},
       ...
     }
   }

   ## 实现要求
   1. 使用 uv 创建项目，项目名：[tool_id]
   2. 使用 FastAPI 实现 HTTP 接口
   3. 添加必要的依赖包
   4. 编写测试脚本验证功能
   5. **必须调用 register_tool 注册到 Router**，tool_id 为 "[tool_id]"
   ```
4. 使用 `create_tool` 提交任务
5. 告知用户 task_id，可以用 `check_task_status` 查询进度

### 4. 用户遇到问题
**场景**：用户说"调用失败"、"参数错误"、"工具不工作"
**处理**：
- 询问具体错误信息
- 检查工具状态
- 提供解决方案（修正参数、重启工具、重新创建）
- 如果是工具 bug，记录并提交修复任务

## 撰写任务书的要点

当需要创建新工具时，任务书必须包含：

```json
{
  "description": "简短描述（一句话）",
  "task_spec": "详细任务书，包含：
    1. 功能需求：明确输入输出
    2. 接口定义：JSON Schema 格式
    3. 实现要求：
       - 使用 uv 项目（纯 Python）或 Docker（需要系统库/GPU）
       - 项目名称和 tool_id
       - 依赖包列表
    4. 交付要求：
       - 创建 uv 项目
       - 编写核心业务逻辑
       - 编写 FastAPI HTTP 接口
       - 调用 register_tool 注册到 Router
       - 验证工具可用性
  ",
  "reference_files": ["相关参考文件路径"]
}
```

## 重要规则

1. **优先使用已有工具**：避免重复创建
2. **优先使用工具组视角回答**：当多个工具固定配合使用时，优先介绍工具组、步骤顺序和参数传递关系
3. **回答时基于实时状态**：如果动态上下文里有工具状态、任务状态、Coding Agent 状态，优先基于这些实时信息回答
4. **友好沟通**：用自然语言，不要太技术化
5. **主动询问**：需求不明确时主动询问细节
6. **提供帮助**：遇到错误时提供解决方案，不要只说"失败了"
7. **记录问题**：如果是系统 bug，记录并提交修复任务
8. **耐心解答**：用户可能不熟悉技术细节，耐心解释

## 对话风格

- 友好、专业、耐心
- 用简单的语言解释技术概念
- 提供具体的示例和步骤
- 遇到问题时提供解决方案，不要只说"不行"
- 适当使用 emoji 让对话更友好（但不要过度）
"""


# ===========================================================================
#  Router Agent 类
# ===========================================================================

ALL_ROUTER_TOOLS = [
    search_tools_fn,
    call_tool_fn,
    create_tool_fn,
    check_task_status_fn,
    list_all_tools_fn,
    get_tool_details_fn,
    get_tools_status_fn,
    list_backend_runtimes_fn,
    list_groups_fn,
    get_group_details_fn,
    list_tasks_fn,
]

MCP_SERVER_NAME = "router_tools"


class RouterAgent:
    """Router Agent：智能路由代理，负责理解需求、调度工具"""

    def __init__(self, router: Router, model: str = "claude-sonnet-4-5") -> None:
        self.router = router
        self.model = model

        # 设置全局 router 实例供工具函数使用
        global _router_instance
        _router_instance = router

    async def chat(self, user_message: str) -> str:
        """单轮对话"""
        mcp_server = create_sdk_mcp_server(
            name=MCP_SERVER_NAME,
            version="1.0.0",
            tools=ALL_ROUTER_TOOLS,
        )

        dynamic_context = _build_dynamic_context(self.router)
        enhanced_message = f"""[系统提示：你是 Router Agent，Tool Agent 系统的智能客服]

[实时系统上下文]
{dynamic_context}

用户消息：{user_message}"""

        options = ClaudeAgentOptions(
            system_prompt=ROUTER_AGENT_SYSTEM_PROMPT,
            mcp_servers={MCP_SERVER_NAME: mcp_server},
            model=self.model,
            setting_sources=["project"],
            allowed_tools=[
                f"mcp__{MCP_SERVER_NAME}__{t.name}"
                for t in ALL_ROUTER_TOOLS
            ]
        )

        result_text = ""

        async with ClaudeSDKClient(options=options) as client:
            await client.query(enhanced_message)

            async for message in client.receive_response():
                if isinstance(message, AssistantMessage):
                    for block in message.content:
                        if isinstance(block, TextBlock):
                            logger.info(f"[ROUTER] {block.text}")
                            result_text = block.text
                        elif isinstance(block, ThinkingBlock):
                            logger.debug(f"[THINKING] {block.thinking[:200]}...")
                        elif isinstance(block, ToolUseBlock):
                            logger.info(f"[TOOL_USE] {block.name}")

                elif isinstance(message, ResultMessage):
                    logger.info(f"[DONE] duration={message.duration_ms}ms")
                    if message.result:
                        result_text = message.result

        return result_text

    async def interactive_loop(self):
        """交互式命令行循环"""
        print("=" * 60)
        print("Router Agent - Interactive Mode")
        print("=" * 60)
        print("Commands:")
        print("  - Type your request to interact with tools")
        print("  - Type 'exit' or 'quit' to stop")
        print("  - Type 'help' for available commands")
        print("-" * 60)

        while True:
            try:
                user_input = await asyncio.to_thread(input, "\n[You] > ")
                user_input = user_input.strip()

                if not user_input:
                    continue

                if user_input.lower() in ("exit", "quit"):
                    print("Goodbye!")
                    break

                if user_input.lower() == "help":
                    print("\nAvailable commands:")
                    print("  search <keyword>  - Search for tools")
                    print("  list              - List all tools")
                    print("  status            - Show tools status")
                    print("  runtimes          - List backend runtimes")
                    print("  groups            - List tool groups")
                    print("  exit/quit         - Exit interactive mode")
                    continue

                # 处理简单命令
                if user_input.lower() == "list":
                    tools = self.router.registry.list_all()
                    print(f"\nTotal tools: {len(tools)}")
                    for t in tools:
                        print(f"  - {t.tool_id}: {t.name}")
                    continue

                if user_input.lower() == "status":
                    tools = self.router.registry.list_all()
                    print(f"\nTools status:")
                    for t in tools:
                        status = self.router.status_manager.get_status(t.tool_id)
                        state = status.state.value if status else "unknown"
                        print(f"  - {t.tool_id}: {state}")
                    continue

                if user_input.lower() == "runtimes":
                    print("\nBackend runtimes:")
                    ctx = json.loads(_build_dynamic_context(self.router))
                    for item in ctx["backend_runtimes"]:
                        print(f"  - {item['category']}: {item['name']} ({item['tool_count']})")
                        print(f"    {item['description']}")
                    continue

                if user_input.lower() == "groups":
                    print("\nTool groups:")
                    for item in json.loads(_build_dynamic_context(self.router))["groups"]:
                        print(f"  - {item['group_id']}: {item['name']}")
                        print(f"    tools={item['tool_ids']}")
                    continue

                # 使用 Claude 处理复杂请求
                print("\n[Router Agent] Processing...")
                response = await self.chat(user_input)
                print(f"\n[Router Agent] {response}")

            except KeyboardInterrupt:
                print("\n\nInterrupted. Type 'exit' to quit.")
            except EOFError:
                print("\nGoodbye!")
                break
            except Exception as e:
                logger.error(f"Error in interactive loop: {e}")
                print(f"\nError: {e}")


# 全局 router 实例（供工具函数使用）
_router_instance: Router | None = None
