/**
 * Tool plugin registry.
 * Aggregates all VoiceTool instances, exposes TOOL_SCHEMAS array
 * and executeTool dispatcher.
 */

import type { AgentId, VoiceTool } from './_types'
import { ToolHttpError } from './_http'

import { tool as weather } from './weather'
import { tool as transport } from './transport'
import { tools as calendarTools } from './calendar'
import { tools as timerTools } from './timers'
import { tool as notes } from './notes'
import { tools as smartHomeTools } from './smart-home'
import { tools as spotifyTools } from './spotify'
import { tools as lightTools } from './lights'

const ALL_TOOLS: VoiceTool[] = [
  weather,
  transport,
  ...calendarTools,
  ...timerTools,
  notes,
  ...smartHomeTools,
  ...spotifyTools,
  ...lightTools,
]

export const TOOL_SCHEMAS = ALL_TOOLS.map((t) => t.schema)

export async function executeTool(
  name: string,
  args: Record<string, any>,
  agent: AgentId,
): Promise<Record<string, any> | { error: string }> {
  const t = ALL_TOOLS.find((t) => t.schema.function.name === name)
  if (!t) return { error: `unknown tool: ${name}` }
  try {
    return await t.execute(args || {}, agent)
  } catch (e) {
    if (e instanceof ToolHttpError) {
      return { error: `tool_http_${e.status}` }
    }
    if (e instanceof TypeError && /fetch/i.test(e.message)) {
      return { error: 'tool_network_error' }
    }
    return { error: `tool_exception: ${(e as Error).message}` }
  }
}
