import { Tool } from '@modelcontextprotocol/sdk/types.js';
import type { NotionClient } from '../clients/notion.js';

// Import all tool modules
import * as pages from './pages.js';
import * as databases from './databases.js';
import * as blocks from './blocks.js';
import * as users from './users.js';
import * as comments from './comments.js';
import * as search from './search.js';

/**
 * Get all Notion MCP tools
 */
export function getAllTools(client: NotionClient): Tool[] {
  return [
    ...pages.getTools(client),
    ...databases.getTools(client),
    ...blocks.getTools(client),
    ...users.getTools(client),
    ...comments.getTools(client),
    ...search.getTools(client),
  ];
}

/**
 * Handle tool execution - routes to appropriate module
 */
export async function handleToolCall(
  toolName: string,
  args: any,
  client: NotionClient
): Promise<any> {
  // Route to appropriate handler based on tool name prefix
  if (toolName.startsWith('notion_get_page') || 
      toolName.startsWith('notion_create_page') ||
      toolName.startsWith('notion_update_page') ||
      toolName.startsWith('notion_archive_page') ||
      toolName.startsWith('notion_restore_page')) {
    return pages.handlePageTool(toolName, args, client);
  }
  
  if (toolName.startsWith('notion_get_database') ||
      toolName.startsWith('notion_create_database') ||
      toolName.startsWith('notion_update_database') ||
      toolName.startsWith('notion_query_database')) {
    return databases.handleDatabaseTool(toolName, args, client);
  }
  
  if (toolName.includes('_block') || toolName.includes('_paragraph') ||
      toolName.includes('_heading') || toolName.includes('_todo') ||
      toolName.includes('_bulleted') || toolName.includes('_numbered') ||
      toolName.includes('_toggle') || toolName.includes('_code') ||
      toolName.includes('_quote') || toolName.includes('_callout') ||
      toolName.includes('_divider') || toolName.includes('_bookmark') ||
      toolName.includes('_image') || toolName.includes('_video') ||
      toolName.includes('_embed') || toolName.includes('_table')) {
    return blocks.handleBlockTool(toolName, args, client);
  }
  
  if (toolName.includes('_user') || toolName.includes('_me')) {
    return users.handleUserTool(toolName, args, client);
  }
  
  if (toolName.includes('_comment')) {
    return comments.handleCommentTool(toolName, args, client);
  }
  
  if (toolName.includes('_search')) {
    return search.handleSearchTool(toolName, args, client);
  }
  
  throw new Error(`Unknown tool: ${toolName}`);
}

// Export all handlers for direct use
export { handlePageTool } from './pages.js';
export { handleDatabaseTool } from './databases.js';
export { handleBlockTool } from './blocks.js';
export { handleUserTool } from './users.js';
export { handleCommentTool } from './comments.js';
export { handleSearchTool } from './search.js';
