"""
工具装饰器与自动注册
"""

from typing import Callable, Dict, Any
from functools import wraps

class ToolSpec:
    def __init__(self, name: str, metadata: Dict[str, Any]):
        self.name = name
        self.metadata = metadata
        self.handler = None

def tool(name: str, **metadata):
    """
    装饰器：将函数注册为 ACT 工具
    """
    def decorator(func: Callable):
        spec = ToolSpec(name, metadata)
        spec.handler = func

        @wraps(func)
        def wrapper(*args, **kwargs):
            return func(*args, **kwargs)

        wrapper._act_tool = spec
        return wrapper
    return decorator

def register_tools_from_module(kernel, module):
    """
    自动扫描模块中所有带 _act_tool 属性的函数并注册到内核，
    同时根据工具名自动添加路由（格式为 tool.action）。
    """
    import inspect
    for name, obj in inspect.getmembers(module):
        if hasattr(obj, "_act_tool"):
            spec = obj._act_tool
            if "." not in spec.name:
                raise ValueError("Tool name must be in format 'tool.action'")
            tool_name, action_name = spec.name.split(".", 1)
            kernel.register_tool(tool_name, action_name, obj, metadata=spec.metadata)
            # 自动添加路由，匹配完整的 "tool.action" 作为意图
            kernel.add_route(spec.name, tool_name, action_name)
