import { createErrorResponse } from '@/common/tool-handler';
import { ERROR_MESSAGES } from '@/common/constants';
import * as browserTools from './browser';

const tools = { ...browserTools };
const toolsMap = new Map(Object.values(tools).map((tool) => [tool.name, tool]));

/**
 * Tool call parameter interface
 */
export interface ToolCallParam {
  name: string;
  args: any;
}

/**
 * Handle tool execution
 */
export const handleCallTool = async (param: ToolCallParam) => {
  console.log('🛠️ [Tool Handler] Executing tool:', {
    toolName: param.name,
    hasArgs: !!param.args,
    availableTools: Array.from(toolsMap.keys()),
    args: param.args,
  });

  const tool = toolsMap.get(param.name);
  if (!tool) {
    console.error('🛠️ [Tool Handler] Tool not found:', param.name);
    return createErrorResponse(`Tool ${param.name} not found`);
  }

  try {
    console.log('🛠️ [Tool Handler] Starting tool execution for:', param.name);
    const result = await tool.execute(param.args);
    console.log('🛠️ [Tool Handler] Tool execution completed:', {
      toolName: param.name,
      hasResult: !!result,
      isError: result?.isError,
      result,
    });
    return result;
  } catch (error) {
    console.error(`🛠️ [Tool Handler] Tool execution failed for ${param.name}:`, error);
    return createErrorResponse(
      error instanceof Error ? error.message : ERROR_MESSAGES.TOOL_EXECUTION_FAILED,
    );
  }
};
