// retoor <retoor@molodetz.nl>
export default class ToolRegistry {
  constructor(context) {
    this.context = context;
    this.tools = new Map();
  }

  register(tool) {
    this.tools.set(tool.name, tool);
    return this;
  }

  registerAll(tools) {
    for (const tool of tools) this.register(tool);
    return this;
  }

  has(name) {
    return this.tools.has(name);
  }

  schemas() {
    return [...this.tools.values()].map((tool) => ({
      type: "function",
      function: {
        name: tool.name,
        description: tool.description,
        parameters: tool.parameters || { type: "object", properties: {} },
      },
    }));
  }

  async execute(name, args) {
    const tool = this.tools.get(name);
    if (!tool) return "Error: unknown tool '" + name + "'";
    try {
      const result = await tool.handler(args || {}, this.context);
      return typeof result === "string" ? result : JSON.stringify(result);
    } catch (error) {
      return "Error: " + (error && error.message ? error.message : String(error));
    }
  }
}
