/**
 * Test client for Streamable HTTP connection
 */

import fetch from 'node-fetch';
import { EventSource } from 'eventsource';

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

console.log('🔌 Testing Streamable HTTP connection...');

let sessionId = null;

async function testStreamableHttp() {
  try {
    // Step 1: Send initialization request
    console.log('🚀 Sending initialization request...');

    const initMessage = {
      jsonrpc: '2.0',
      id: 1,
      method: 'initialize',
      params: {
        protocolVersion: '2024-11-05',
        capabilities: {
          tools: {},
        },
        clientInfo: {
          name: 'test-streamable-http-client',
          version: '1.0.0',
        },
      },
    };

    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}`);
    }

    // Extract session ID from response headers
    sessionId = initResponse.headers.get('mcp-session-id');
    console.log(`✅ Initialization successful! Session ID: ${sessionId}`);

    const initResult = await initResponse.text();
    console.log('📨 Initialization response (SSE):', initResult);

    // Step 2: Establish SSE stream for this session
    console.log('🔌 Establishing SSE stream...');

    const eventSource = new EventSource(MCP_URL, {
      headers: {
        'MCP-Session-ID': sessionId,
      },
    });

    eventSource.onopen = () => {
      console.log('✅ SSE stream established!');
      // Test listing tools after stream is ready
      setTimeout(() => testListTools(), 1000);
    };

    eventSource.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        console.log('📨 Received streaming message:', JSON.stringify(data, null, 2));
      } catch (error) {
        console.log('📨 Received streaming data:', event.data);
      }
    };

    eventSource.onerror = (error) => {
      console.error('❌ SSE stream error:', error);
    };

    // Close after 10 seconds
    setTimeout(() => {
      console.log('⏰ Closing connections...');
      eventSource.close();
      process.exit(0);
    }, 10000);
  } catch (error) {
    console.error('❌ Error in streamable HTTP test:', error);
    process.exit(1);
  }
}

async function testListTools() {
  if (!sessionId) {
    console.error('❌ No session ID available');
    return;
  }

  console.log('📋 Testing tools/list via Streamable HTTP...');

  const message = {
    jsonrpc: '2.0',
    id: 2,
    method: 'tools/list',
    params: {},
  };

  try {
    const response = await fetch(MCP_URL, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'MCP-Session-ID': sessionId,
      },
      body: JSON.stringify(message),
    });

    if (!response.ok) {
      console.error('❌ Failed to send tools/list:', response.status, response.statusText);
    } else {
      console.log('✅ tools/list message sent successfully');
    }
  } catch (error) {
    console.error('❌ Error sending tools/list:', error);
  }
}

// Start the test
testStreamableHttp();
