import { ToolContext } from './context';
import { VIBN_TOOL_DEFINITIONS } from './vibn-tools';

export const ALL_TOOLS = VIBN_TOOL_DEFINITIONS;

export async function executeTool(
    name: string,
    args: Record<string, unknown>,
    ctx: ToolContext
): Promise<unknown> {
    // Some tools might just be executed locally by the Runner in the future, 
    // but right now we forward all non-github/http tools to the frontend MCP.
    
    // Convert underscore to dot format as expected by MCP
    const action = name.replace(/_/g, ".");
    
    try {
        const response = await fetch(`${ctx.vibnApiUrl}/api/mcp`, {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                "Authorization": `Bearer ${ctx.mcpToken}`,
                ...(ctx.projectId ? { "X-Vibn-Project-Id": ctx.projectId } : {})
            },
            body: JSON.stringify({ action, params: args }),
        });
        
        const data: any = await response.json();
        
        if (!response.ok) {
            return { error: data.error || `HTTP ${response.status}: ${response.statusText}` };
        }
        
        return data.result || data;
    } catch (e) {
        return { error: `Failed to execute tool ${name} via MCP: ${e instanceof Error ? e.message : String(e)}` };
    }
}
