/**
 * Tool Registry
 * Central registry for all agent tools.
 * Tools self-register on import via side-effect in index.ts.
 */

import { tool } from 'ai'
import { z } from 'zod'

export interface ToolContext {
  userId: string
  agentId: string
  actionId: string
  config: Record<string, string>
}

export interface RegisteredTool {
  name: string
  description: string
  buildTool: (ctx: ToolContext) => any  // Returns an AI SDK tool() synchronously
  isInternal: boolean  // true = no API key needed
}

class ToolRegistry {
  private tools: Map<string, RegisteredTool> = new Map()

  register(tool: RegisteredTool): void {
    this.tools.set(tool.name, tool)
  }

  get(name: string): RegisteredTool | undefined {
    return this.tools.get(name)
  }

  buildToolsForAgent(toolNames: string[], ctx: ToolContext): Record<string, any> {
    const built: Record<string, any> = {}
    for (const name of toolNames) {
      const registered = this.tools.get(name)
      if (registered) {
        built[name] = registered.buildTool(ctx)
      }
    }
    return built
  }

  getAvailableTools(): Array<{ name: string; description: string; isInternal: boolean }> {
    return Array.from(this.tools.values()).map(t => ({
      name: t.name,
      description: t.description,
      isInternal: t.isInternal,
    }))
  }
}

// Singleton
export const toolRegistry = new ToolRegistry()
