/**
 * Test client for SSE (Server-Sent Events) streaming connection
 */

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

const SERVER_URL = 'http://localhost:3001';
const SSE_URL = `${SERVER_URL}/sse`;
const MESSAGES_URL = `${SERVER_URL}/messages`;

console.log('🔌 Testing SSE streaming connection...');

let sessionId = null;

// Create SSE connection
const eventSource = new EventSource(SSE_URL);

eventSource.onopen = () => {
  console.log('✅ SSE connection established!');
};

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

    // Extract session ID from the first message
    if (data.sessionId && !sessionId) {
      sessionId = data.sessionId;
      console.log(`🆔 Session ID: ${sessionId}`);

      // Test listing tools after connection is established
      setTimeout(() => testListTools(), 1000);
    }
  } catch (error) {
    console.log('📨 Received SSE data:', event.data);
  }
};

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

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

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

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

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

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

// Close connection after 10 seconds
setTimeout(() => {
  console.log('⏰ Closing SSE connection...');
  eventSource.close();
  process.exit(0);
}, 10000);
