#!/usr/bin/env node
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import {
  CallToolRequestSchema,
  ListToolsRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';
import { WrikeClient } from './clients/wrike.js';
import { createTaskTools } from './tools/tasks-tools.js';
import { createFolderTools } from './tools/folders-tools.js';
import { createCommentTools } from './tools/comments-tools.js';
import { createAttachmentTools } from './tools/attachments-tools.js';
import { createTimelogTools } from './tools/timelogs-tools.js';
import { createContactTools } from './tools/contacts-tools.js';
import { createSpaceTools } from './tools/spaces-tools.js';
import { createGroupTools } from './tools/groups-tools.js';
import { createWorkflowTools } from './tools/workflows-tools.js';
import { createCustomFieldTools } from './tools/customfields-tools.js';
import { createApprovalTools } from './tools/approvals-tools.js';
import { createWebhookTools } from './tools/webhooks-tools.js';
import { createMiscTools } from './tools/misc-tools.js';

const WRIKE_API_TOKEN = process.env.WRIKE_API_TOKEN;

if (!WRIKE_API_TOKEN) {
  throw new Error('WRIKE_API_TOKEN environment variable is required');
}

// Initialize Wrike client
const client = new WrikeClient(WRIKE_API_TOKEN);

// Initialize MCP server
const server = new Server(
  {
    name: 'wrike-mcp-server',
    version: '1.0.0',
  },
  {
    capabilities: {
      tools: {},
    },
  }
);

// Collect all tools
const allTools = {
  ...createTaskTools(client),
  ...createFolderTools(client),
  ...createCommentTools(client),
  ...createAttachmentTools(client),
  ...createTimelogTools(client),
  ...createContactTools(client),
  ...createSpaceTools(client),
  ...createGroupTools(client),
  ...createWorkflowTools(client),
  ...createCustomFieldTools(client),
  ...createApprovalTools(client),
  ...createWebhookTools(client),
  ...createMiscTools(client),
};

// List tools handler
server.setRequestHandler(ListToolsRequestSchema, async () => {
  return {
    tools: Object.values(allTools).map((tool) => ({
      name: tool.name,
      description: tool.description,
      inputSchema: tool.inputSchema,
    })),
  };
});

// Call tool handler
server.setRequestHandler(CallToolRequestSchema, async (request) => {
  const tool = allTools[request.params.name as keyof typeof allTools];
  
  if (!tool) {
    throw new Error(`Unknown tool: ${request.params.name}`);
  }
  
  try {
    return await tool.handler(request.params.arguments as any || {});
  } catch (error) {
    if (error instanceof Error) {
      return {
        content: [
          {
            type: 'text',
            text: `Error: ${error.message}`,
          },
        ],
        isError: true,
      };
    }
    throw error;
  }
});

// Start server
async function main() {
  const transport = new StdioServerTransport();
  await server.connect(transport);
  console.error('Wrike MCP Server running on stdio');
}

main().catch((error) => {
  console.error('Fatal error:', error);
  process.exit(1);
});
