// Test MCP natural language navigation
// This simulates what Cherry Studio would do when sending "open google"

const MCP_HTTP_URL = 'http://localhost:3001/mcp';

async function testMCPToolCall() {
  console.log('🧪 Testing MCP Natural Language Navigation\n');

  try {
    // Test 0: Initialize the MCP session
    console.log('0️⃣ Initializing MCP session...');
    const initResponse = await fetch(MCP_HTTP_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 0,
        method: 'initialize',
        params: {
          protocolVersion: '2024-11-05',
          capabilities: {},
          clientInfo: { name: 'test-client', version: '1.0.0' },
        },
      }),
    });

    const initResult = await initResponse.json();
    console.log('✅ Initialization response:', initResult.result ? 'Success' : 'Failed');

    // Test 1: List available tools
    console.log('1️⃣ Testing tools/list...');
    const listResponse = await fetch(MCP_HTTP_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 1,
        method: 'tools/list',
        params: {},
      }),
    });

    const listResult = await listResponse.json();
    console.log('✅ Tools list response:', listResult.result?.tools?.length, 'tools found');

    // Find our natural language navigation tool
    const naturalNavTool = listResult.result?.tools?.find(
      (tool) => tool.name === 'chrome_navigate_natural',
    );
    if (naturalNavTool) {
      console.log('✅ Found chrome_navigate_natural tool:', naturalNavTool.description);
    } else {
      console.log('❌ chrome_navigate_natural tool not found');
    }

    // Test 2: Call the natural language navigation tool
    console.log('\n2️⃣ Testing chrome_navigate_natural tool call...');
    const toolCallResponse = await fetch(MCP_HTTP_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 2,
        method: 'tools/call',
        params: {
          name: 'chrome_navigate_natural',
          arguments: {
            query: 'open google',
          },
        },
      }),
    });

    const toolResult = await toolCallResponse.json();
    console.log('✅ Tool call response:', JSON.stringify(toolResult, null, 2));

    // Test 3: Call the regular navigation tool with processed URL
    console.log('\n3️⃣ Testing chrome_navigate tool call...');
    const regularNavResponse = await fetch(MCP_HTTP_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({
        jsonrpc: '2.0',
        id: 3,
        method: 'tools/call',
        params: {
          name: 'chrome_navigate',
          arguments: {
            url: 'https://www.google.com',
          },
        },
      }),
    });

    const regularResult = await regularNavResponse.json();
    console.log('✅ Regular navigation response:', JSON.stringify(regularResult, null, 2));

    // Test 4: Test various natural language queries
    console.log('\n4️⃣ Testing various natural language queries...');
    const testQueries = [
      'youtube',
      'open facebook',
      'go to github',
      'search for cats',
      'python tutorials',
    ];

    for (const query of testQueries) {
      console.log(`\n📝 Testing query: "${query}"`);
      const response = await fetch(MCP_HTTP_URL, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Accept: 'application/json',
        },
        body: JSON.stringify({
          jsonrpc: '2.0',
          id: Math.random(),
          method: 'tools/call',
          params: {
            name: 'chrome_navigate_natural',
            arguments: {
              query: query,
            },
          },
        }),
      });

      const result = await response.json();
      if (result.error) {
        console.log(`❌ Error: ${result.error.message}`);
      } else {
        console.log(`✅ Success: Tool executed`);
      }
    }
  } catch (error) {
    console.error('❌ Test failed:', error.message);
  }
}

// Run the test
testMCPToolCall()
  .then(() => {
    console.log('\n✨ Test completed!');
  })
  .catch((error) => {
    console.error('💥 Test failed:', error);
  });
