/**
 * MCP 插件测试脚本
 */

const { Framework } = require('../src');
const { MCPExecutorPlugin } = require('../src/executors/mcp-executor');

async function test() {
  console.log('=== MCP Plugin Test ===\n');

  console.log('1. Creating framework...');
  const framework = new Framework({ debug: true });

  console.log('2. Creating MCP plugin with fetch server...');
  const mcpPlugin = new MCPExecutorPlugin({
    servers: [
      {
        name: 'fetch',
        command: 'uvx',
        args: ['mcp-server-fetch'],
      },
    ],
  });

  console.log('3. Loading MCP plugin...');
  await framework.loadPlugin(mcpPlugin);

  console.log('4. Starting framework...');
  await framework.pluginManager.startAll();

  // 等待 MCP 服务器连接
  console.log('\n5. Waiting for MCP connection...');
  await new Promise((resolve) => setTimeout(resolve, 2000));

  console.log('\n6. Listing MCP servers...');
  const servers = mcpPlugin.getServers();
  console.log('Servers:', JSON.stringify(servers, null, 2));

  console.log('\n7. Listing MCP tools...');
  const mcpTools = framework.getTools().filter((t) => t.name.startsWith('mcp_'));
  console.log(
    'MCP Tools:',
    mcpTools.map((t) => t.name)
  );

  if (mcpTools.length > 0) {
    console.log('\n8. Testing mcp_list_servers...');
    const listResult = await framework.executeTool('mcp_list_servers', {});
    console.log('List Servers Result:', JSON.stringify(listResult, null, 2));

    console.log('\n9. Testing mcp_tool_schema...');
    const schemaResult = await framework.executeTool('mcp_tool_schema', {
      server: 'fetch',
      tool: 'fetch',
    });
    console.log('Tool Schema:', JSON.stringify(schemaResult, null, 2));

    console.log('\n10. Testing mcp_call (fetch a webpage)...');
    const callResult = await framework.executeTool('mcp_call', {
      server: 'fetch',
      tool: 'fetch',
      args_json: JSON.stringify({ url: 'https://httpbin.org/get' }),
    });
    console.log(
      'Fetch Result (truncated):',
      JSON.stringify(callResult, null, 2).substring(0, 500) + '...'
    );
  }

  console.log('\n11. Destroying framework...');
  await framework.destroy();

  console.log('\n=== Test Complete ===');
}

test()
  .then(() => {
    console.log('\n✓ Test completed successfully');
    process.exit(0);
  })
  .catch((err) => {
    console.error('\n✗ Test failed:', err.message);
    console.error(err.stack);
    process.exit(1);
  });
