/**
 * Test tools/list via streamable HTTP
 */

import fetch from 'node-fetch';

const SERVER_URL = 'http://localhost:3001';
const MCP_URL = `${SERVER_URL}/mcp`;

async function testToolsList() {
  try {
    console.log('🔍 Testing tools/list via streamable HTTP...');
    
    // Step 1: Initialize session
    const initMessage = {
      jsonrpc: '2.0',
      id: 1,
      method: 'initialize',
      params: {
        protocolVersion: '2024-11-05',
        capabilities: {
          tools: {}
        },
        clientInfo: {
          name: 'test-tools-list-client',
          version: '1.0.0'
        }
      }
    };

    console.log('🚀 Step 1: Initializing session...');
    const initResponse = await fetch(MCP_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json, text/event-stream'
      },
      body: JSON.stringify(initMessage)
    });

    if (!initResponse.ok) {
      throw new Error(`Initialization failed: ${initResponse.status} ${initResponse.statusText}`);
    }

    const sessionId = initResponse.headers.get('mcp-session-id');
    console.log(`✅ Session initialized! Session ID: ${sessionId}`);

    // Step 2: Send tools/list request
    const toolsListMessage = {
      jsonrpc: '2.0',
      id: 2,
      method: 'tools/list',
      params: {}
    };

    console.log('📋 Step 2: Requesting tools list...');
    const toolsResponse = await fetch(MCP_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json, text/event-stream',
        'MCP-Session-ID': sessionId
      },
      body: JSON.stringify(toolsListMessage)
    });

    if (!toolsResponse.ok) {
      throw new Error(`Tools list failed: ${toolsResponse.status} ${toolsResponse.statusText}`);
    }

    const toolsResult = await toolsResponse.text();
    console.log('📋 Tools list response (SSE):', toolsResult);

    // Step 3: Test a tool call (navigate_to_url)
    const toolCallMessage = {
      jsonrpc: '2.0',
      id: 3,
      method: 'tools/call',
      params: {
        name: 'navigate_to_url',
        arguments: {
          url: 'https://example.com'
        }
      }
    };

    console.log('🔧 Step 3: Testing tool call (navigate_to_url)...');
    const toolCallResponse = await fetch(MCP_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json, text/event-stream',
        'MCP-Session-ID': sessionId
      },
      body: JSON.stringify(toolCallMessage)
    });

    if (!toolCallResponse.ok) {
      throw new Error(`Tool call failed: ${toolCallResponse.status} ${toolCallResponse.statusText}`);
    }

    const toolCallResult = await toolCallResponse.text();
    console.log('🔧 Tool call response (SSE):', toolCallResult);

    console.log('✅ All tests completed successfully!');
    
  } catch (error) {
    console.error('❌ Error:', error);
  }
}

testToolsList();
