/**
 * Test Chrome extension connection to remote server
 */

import WebSocket from 'ws';

const CHROME_ENDPOINT = 'ws://localhost:3001/chrome';

async function testChromeConnection() {
  console.log('🔌 Testing Chrome extension connection...');

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

    ws.on('open', () => {
      console.log('✅ Connected to Chrome extension endpoint');
      
      // Send a test message to see if any Chrome extensions are connected
      const testMessage = {
        id: 'test-' + Date.now(),
        action: 'callTool',
        params: {
          name: 'chrome_navigate',
          arguments: {
            url: 'https://www.google.com',
            newWindow: false
          }
        }
      };

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

      // Set a timeout to close the connection
      setTimeout(() => {
        console.log('⏰ Test timeout - closing connection');
        ws.close();
        resolve('Test completed');
      }, 5000);
    });

    ws.on('message', (data) => {
      try {
        const response = JSON.parse(data.toString());
        console.log('📨 Received response:', JSON.stringify(response, null, 2));
      } catch (error) {
        console.error('❌ Error parsing response:', error);
      }
    });

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

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

testChromeConnection().catch(console.error);
