/**
 * Test tool call to verify Chrome extension connection using MCP WebSocket
 */

import WebSocket from 'ws';

const MCP_SERVER_URL = 'ws://localhost:3001/ws/mcp';

async function testToolCall() {
  console.log('🔌 Testing tool call via MCP WebSocket...');

  return new Promise((resolve, reject) => {
    const ws = new WebSocket(MCP_SERVER_URL);

    ws.on('open', () => {
      console.log('✅ Connected to MCP WebSocket');

      // Send a proper MCP tool call
      const message = {
        jsonrpc: '2.0',
        id: 1,
        method: 'tools/call',
        params: {
          name: 'chrome_navigate',
          arguments: {
            url: 'https://www.google.com',
            newWindow: false,
          },
        },
      };

      console.log('📤 Sending MCP message:', JSON.stringify(message, null, 2));
      ws.send(JSON.stringify(message));
    });

    ws.on('message', (data) => {
      try {
        const response = JSON.parse(data.toString());
        console.log('📨 MCP Response:', JSON.stringify(response, null, 2));

        if (response.error) {
          console.error('❌ Tool call failed:', response.error);
          reject(new Error(response.error.message || response.error));
        } else if (response.result) {
          console.log('✅ Tool call successful!');
          resolve(response.result);
        } else {
          console.log('📨 Received other message:', response);
        }
        ws.close();
      } catch (error) {
        console.error('❌ Error parsing response:', error);
        reject(error);
        ws.close();
      }
    });

    ws.on('error', (error) => {
      console.error('❌ WebSocket error:', error);
      reject(error);
    });

    ws.on('close', () => {
      console.log('🔌 WebSocket connection closed');
    });

    // Timeout after 10 seconds
    setTimeout(() => {
      if (ws.readyState === WebSocket.OPEN) {
        ws.close();
        reject(new Error('Test timeout'));
      }
    }, 10000);
  });
}

testToolCall().catch(console.error);
