/**
 * Tool System for AI Agents
 * Supports function calling and tool execution
 */

export interface Tool {
  name: string;
  description: string;
  parameters: {
    type: 'object';
    properties: Record<string, {
      type: string;
      description?: string;
      enum?: string[];
    }>;
    required?: string[];
  };
  execute: (args: any) => Promise<any> | any;
}

/**
 * Built-in Tools
 */

// Calculator tool
export const calculatorTool: Tool = {
  name: 'calculator',
  description: 'Perform mathematical calculations. Input should be a valid mathematical expression.',
  parameters: {
    type: 'object',
    properties: {
      expression: {
        type: 'string',
        description: 'Mathematical expression to evaluate (e.g., "2 + 2", "sqrt(16)", "10 * 5")',
      },
    },
    required: ['expression'],
  },
  execute: async (args: { expression: string }) => {
    try {
      // Safe evaluation (only math operations)
      const sanitized = args.expression.replace(/[^0-9+\-*/().\s]/g, '');
      const result = Function(`"use strict"; return (${sanitized})`)();
      return { result, expression: args.expression };
    } catch (error: any) {
      return { error: `Invalid expression: ${error.message}`, expression: args.expression };
    }
  },
};

// Web search tool (placeholder - requires API key)
export const webSearchTool: Tool = {
  name: 'web_search',
  description: 'Search the web for information. Requires a search API key to be configured.',
  parameters: {
    type: 'object',
    properties: {
      query: {
        type: 'string',
        description: 'Search query',
      },
    },
    required: ['query'],
  },
  execute: async (args: { query: string }) => {
    // Placeholder - would integrate with SerpAPI, Google Search API, etc.
    return { 
      error: 'Web search not configured. Add a search API key to enable this tool.',
      query: args.query 
    };
  },
};

// Current time tool
export const currentTimeTool: Tool = {
  name: 'get_current_time',
  description: 'Get the current date and time in ISO format.',
  parameters: {
    type: 'object',
    properties: {},
    required: [],
  },
  execute: async () => {
    return {
      time: new Date().toISOString(),
      timestamp: Date.now(),
      timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
    };
  },
};

// File read tool (safe, read-only)
export const fileReadTool: Tool = {
  name: 'read_file',
  description: 'Read the contents of a file. Only works with files in allowed directories.',
  parameters: {
    type: 'object',
    properties: {
      path: {
        type: 'string',
        description: 'Path to the file to read',
      },
    },
    required: ['path'],
  },
  execute: async (args: { path: string }) => {
    // Placeholder - would need file system access with security restrictions
    return {
      error: 'File reading not implemented. Requires secure file system access.',
      path: args.path,
    };
  },
};

/**
 * Tool Registry
 */
export const toolRegistry: Record<string, Tool> = {
  calculator: calculatorTool,
  web_search: webSearchTool,
  get_current_time: currentTimeTool,
  read_file: fileReadTool,
};

/**
 * Get a tool by name
 */
export function getTool(name: string): Tool | undefined {
  return toolRegistry[name];
}

/**
 * List all available tools
 */
export function listTools(): Tool[] {
  return Object.values(toolRegistry);
}

/**
 * Execute a tool with arguments
 */
export async function executeTool(toolName: string, args: any): Promise<any> {
  const tool = getTool(toolName);
  if (!tool) {
    throw new Error(`Tool not found: ${toolName}`);
  }
  return await tool.execute(args);
}

/**
 * Format tools for OpenAI function calling
 */
export function formatToolsForOpenAI(tools: Tool[]): any[] {
  return tools.map(tool => ({
    type: 'function',
    function: {
      name: tool.name,
      description: tool.description,
      parameters: tool.parameters,
    },
  }));
}

