import { ToolContext } from './context';

export interface ToolDefinition {
    name: string;
    description: string;
    parameters: Record<string, unknown>;
    /** Implementation — called by executeTool(). Not sent to the LLM. */
    handler: (args: Record<string, unknown>, ctx: ToolContext) => Promise<unknown>;
}

/** Live registry — grows as domain files are imported. */
const _registry = new Map<string, ToolDefinition>();

/**
 * Mutable array kept in sync with the registry.
 * Used by agents.ts to pick tool subsets by name (backwards-compatible with ALL_TOOLS).
 */
export const ALL_TOOLS: ToolDefinition[] = [];

export function registerTool(tool: ToolDefinition): void {
    _registry.set(tool.name, tool);
    ALL_TOOLS.push(tool);
}

/** Dispatch a tool call by name — O(1) map lookup, no switch needed. */
export async function executeTool(
    name: string,
    args: Record<string, unknown>,
    ctx: ToolContext
): Promise<unknown> {
    const tool = _registry.get(name);
    if (!tool) return { error: `Unknown tool: ${name}` };
    return tool.handler(args, ctx);
}
