/**
 * Example: Real-Time Call Analysis
 * Demonstrates how to use the RealTimeCallAnalysisServer
 */

import { RealTimeCallAnalysisServer } from '../src/lib/call-analysis/real-time-call-server';

async function example() {
  // Create and start the server
  const server = new RealTimeCallAnalysisServer({
    port: 8089,
    enableEchoCancellation: true,
    enableNoiseSuppression: true,
    enableAutoGainControl: true,
    analysisConfig: {
      sentimentWindowMs: 5000,
      interruptThresholdMs: 200,
      overlapThresholdMs: 300,
      pauseThresholdMs: 2000,
      volumeSpikeThreshold: 0.8,
      anomalySensitivity: 'medium',
      enableSpeakerDiarization: false,
    },
  });

  // Listen for events
  server.on('client:connected', ({ clientId }) => {
    console.log(`Client connected: ${clientId}`);
  });

  server.on('client:disconnected', ({ clientId }) => {
    console.log(`Client disconnected: ${clientId}`);
  });

  server.on('analysis:alert', ({ clientId, alert }) => {
    console.log(`Alert from ${clientId}: ${alert.message} (${alert.severity})`);
  });

  server.on('analysis:result', ({ clientId, status }) => {
    console.log(`Analysis status for ${clientId}: ${status}`);
  });

  server.on('analysis:error', ({ clientId, error }) => {
    console.error(`Error for ${clientId}:`, error);
  });

  // Start the server
  await server.start();
  console.log('Server started, waiting for clients...');

  // Example: Client connection simulation
  const WebSocket = require('ws');
  const client = new WebSocket('ws://localhost:8089?clientId=test-client');

  client.on('open', () => {
    console.log('Client connected');
    
    // Start audio capture
    client.send(JSON.stringify({ type: 'start' }));
  });

  client.on('message', (data: Buffer) => {
    const message = JSON.parse(data.toString());
    console.log('Received:', message.type, message);

    if (message.type === 'alert' || message.type === 'anomaly') {
      console.log(`  - ${message.alertType}: ${message.message}`);
    }

    if (message.type === 'analysis') {
      console.log(`  - MOS: ${message.callQuality.mosScore}`);
      console.log(`  - Sentiment: ${message.sentiment.sentiment}`);
      console.log(`  - Summary: ${message.summary}`);
    }
  });

  // Stop after 60 seconds
  setTimeout(async () => {
    console.log('Stopping server...');
    await server.stop();
    process.exit(0);
  }, 60000);
}

// Run example if called directly
if (require.main === module) {
  example().catch(console.error);
}

export default example;
