class ToolDefinitionFactory:
    """
    Type-safe base class for tool definition factories.
    """

    def __init__(
        self,
        retry_handler: ToolRetryHandler | None = None,
        behaviour_manager: BehaviourManager | None = None,
    ):
        self.retry_handler = retry_handler or DefaultRetryHandler()
        self.behaviour_manager = behaviour_manager or BehaviourManager()

    def create_tool_definition[T: CommonRequiredDependencies, K: ToolMetadata](
        self,
        dependencies: T,
        tool_definition_input: ToolDefinitionInput[T, K],
        override_retry_input: OverrideRetryInput | None = None,
    ) -> ToolDefinition[K]:
        """Create the tool definition with provided dependencies."""
        tool_func_with_dependencies = tool_definition_input.tool_callable(dependencies)
        metadata = tool_definition_input.metadata

        retry_config = override_retry_input.retry_config if override_retry_input else RetryConfig()
        retry_handler = override_retry_input.retry_handler if override_retry_input else self.retry_handler

        original_func = tool_func_with_dependencies
        original_sig = inspect.signature(original_func)

        @wraps(original_func)
        async def wrapped_callback(*args: Any, **kwargs: Any) -> Any:
            tool_input = BehaviourToolDefinitionInput(name=tool_definition_input.name, metadata=metadata)
            context = ToolResponseContext()

            async with self.behaviour_manager.manage_behaviours(
                tool_input, dependencies, context
            ) as early_end_message:
                if early_end_message is not None:
                    return early_end_message
                else:
                    try:
                        result = await retry_handler.execute_with_retry(
                            original_func,
                            retry_config,
                            *args,
                            **kwargs,
                        )

                        return result
                    except Exception as e:
                        context.error = e
                        caller_agent: BaseAgent = dependencies["caller_agent"]
                        error_message = (
                            f"Tool execution error: The tool '{tool_definition_input.name}' had "
                            "a system error."
                        )

                        logger.error(error_message, exc_info=True)

                        return communicate_system_data(caller_agent.session, error_message)

        # Make sure tooling that introspects the function sees the original signature
        # (otherwise the tool parameters are args/kwargs instead of the tool parameters).
        wrapped_callback.__signature__ = original_sig  # type: ignore[attr-defined]

        if is_function_tool(original_func):
            function_tool_attr = getattr(original_func, "__livekit_tool_info")
            setattr(wrapped_callback, "__livekit_tool_info", function_tool_attr)
        elif is_raw_function_tool(original_func):
            function_tool_attr = getattr(original_func, "__livekit_raw_tool_info")
            setattr(wrapped_callback, "__livekit_raw_tool_info", function_tool_attr)
        else:
            raise ValueError(f"Tool function {original_func} is not a function tool or raw function tool")

        return ToolDefinition(
            name=tool_definition_input.name,
            function_tool=wrapped_callback,
            add_instructions=tool_definition_input.add_instructions,
            metadata=metadata,
        )


tool_definition_factory = ToolDefinitionFactory()