# Career Guidance WebSocket Integration Guide

## How to Integrate Career Guidance WebSocket Server

### 1. Add the Route Import

Add this import to your `server.js` file after the existing route imports:

```javascript
// Add this import with your other route imports
const careerGuidanceRoutes = require('./routes/careerGuidanceRoutes');
```

### 2. Initialize the WebSocket Server

Add this code in your WebSocket initialization section (around line 52-82 in server.js):

```javascript
// Initialize WebSocket Servers with proper error handling
let wsServer, groupChatWS, careerGuidanceWS;

try {
    console.log('🔌 [WEBSOCKET] Initializing WebSocket servers...');
    
    // Initialize AI Chat WebSocket Server
    wsServer = new WebSocketServer(server);
    console.log('✅ [WEBSOCKET] AI Chat WebSocket server initialized on /ws');
    
    // Initialize Group Chat WebSocket Server
    groupChatWS = new GroupChatWebSocket(server);
    console.log('✅ [WEBSOCKET] Group Chat WebSocket server initialized on /ws/group-chat');
    
    // Initialize Career Guidance WebSocket Server
    careerGuidanceWS = careerGuidanceRoutes.initializeCareerGuidanceWS(server);
    console.log('✅ [WEBSOCKET] Career Guidance WebSocket server initialized on /ws/career-guidance');
    
    // Set up graceful shutdown for WebSocket servers
    process.on('SIGINT', () => {
        console.log('🔄 [WEBSOCKET] Shutting down WebSocket servers...');
        if (wsServer) {
            wsServer.wss.close();
            console.log('✅ [WEBSOCKET] AI Chat WebSocket server closed');
        }
        if (groupChatWS) {
            groupChatWS.wss.close();
            console.log('✅ [WEBSOCKET] Group Chat WebSocket server closed');
        }
        if (careerGuidanceWS) {
            careerGuidanceWS.wss.close();
            console.log('✅ [WEBSOCKET] Career Guidance WebSocket server closed');
        }
        process.exit(0);
    });
    
} catch (error) {
    console.error('❌ [WEBSOCKET] Failed to initialize WebSocket servers:', error);
    console.error('❌ [WEBSOCKET] Server will continue without WebSocket functionality');
}
```

### 3. Add the Route

Add this route after your existing route declarations (around line 444):

```javascript
// Add this route with your other routes
app.use('/api/career-guidance', careerGuidanceRoutes);
```

### 4. Complete Integration Example

Here's how your server.js should look with the integration:

```javascript
const express = require('express');
const http = require('http');
const cors = require('cors');
const mongoose = require('mongoose');
const path = require('path');
const fs = require('fs');
const compression = require('compression');
const connectDB = require('./utils/db');

// ... your existing route imports ...
const careerGuidanceRoutes = require('./routes/careerGuidanceRoutes');

// ... your existing WebSocket imports ...
const WebSocketServer = require('./websocketServer');
const GroupChatWebSocket = require('./websocketGroupChat');

require('dotenv').config();

const app = express();
const server = http.createServer(app);
const PORT = process.env.PORT || 5500;

// Initialize WebSocket Servers with proper error handling
let wsServer, groupChatWS, careerGuidanceWS;

try {
    console.log('🔌 [WEBSOCKET] Initializing WebSocket servers...');
    
    // Initialize AI Chat WebSocket Server
    wsServer = new WebSocketServer(server);
    console.log('✅ [WEBSOCKET] AI Chat WebSocket server initialized on /ws');
    
    // Initialize Group Chat WebSocket Server
    groupChatWS = new GroupChatWebSocket(server);
    console.log('✅ [WEBSOCKET] Group Chat WebSocket server initialized on /ws/group-chat');
    
    // Initialize Career Guidance WebSocket Server
    careerGuidanceWS = careerGuidanceRoutes.initializeCareerGuidanceWS(server);
    console.log('✅ [WEBSOCKET] Career Guidance WebSocket server initialized on /ws/career-guidance');
    
    // Set up graceful shutdown for WebSocket servers
    process.on('SIGINT', () => {
        console.log('🔄 [WEBSOCKET] Shutting down WebSocket servers...');
        if (wsServer) {
            wsServer.wss.close();
            console.log('✅ [WEBSOCKET] AI Chat WebSocket server closed');
        }
        if (groupChatWS) {
            groupChatWS.wss.close();
            console.log('✅ [WEBSOCKET] Group Chat WebSocket server closed');
        }
        if (careerGuidanceWS) {
            careerGuidanceWS.wss.close();
            console.log('✅ [WEBSOCKET] Career Guidance WebSocket server closed');
        }
        process.exit(0);
    });
    
} catch (error) {
    console.error('❌ [WEBSOCKET] Failed to initialize WebSocket servers:', error);
    console.error('❌ [WEBSOCKET] Server will continue without WebSocket functionality');
}

// ... your existing middleware and routes ...

// Add the career guidance route
app.use('/api/career-guidance', careerGuidanceRoutes);

// ... rest of your server setup ...
```

## Available Endpoints After Integration

Once integrated, you'll have these new endpoints available:

### WebSocket Connection
- **URL**: `ws://localhost:5500/ws/career-guidance?token=YOUR_JWT_TOKEN`
- **Purpose**: Real-time career guidance

### REST API Endpoints
- **GET** `/api/career-guidance/health` - Health check
- **GET** `/api/career-guidance/clients` - Get connected clients
- **POST** `/api/career-guidance/broadcast` - Broadcast message
- **GET** `/api/career-guidance/stats` - Get server statistics
- **POST** `/api/career-guidance/test-guidance` - Test career guidance
- **GET** `/api/career-guidance/connection-info` - Get connection info

## Testing the Integration

### 1. Test Health Check
```bash
curl -X GET http://localhost:5500/api/career-guidance/health
```

### 2. Test WebSocket Connection
```javascript
const WebSocket = require('ws');
const token = 'your_jwt_token_here';

const ws = new WebSocket(`ws://localhost:5500/ws/career-guidance?token=${token}`);

ws.onopen = function() {
    console.log('Connected to Career Guidance WebSocket');
    
    // Send career guidance request
    ws.send(JSON.stringify({
        type: 'career_guidance',
        userId: 'user123',
        occupation: 'software engineer'
    }));
};

ws.onmessage = function(event) {
    const data = JSON.parse(event.data);
    console.log('Received:', data);
};
```

### 3. Test REST API
```bash
# Test career guidance generation
curl -X POST http://localhost:5500/api/career-guidance/test-guidance \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "user123",
    "occupation": "software engineer"
  }'
```

## Console Output

After successful integration, you should see these console messages:

```
🔌 [WEBSOCKET] Initializing WebSocket servers...
✅ [WEBSOCKET] AI Chat WebSocket server initialized on /ws
✅ [WEBSOCKET] Group Chat WebSocket server initialized on /ws/group-chat
✅ [WEBSOCKET] Career Guidance WebSocket server initialized on /ws/career-guidance
🎯 [WEBSOCKET] Career Guidance WebSocket server started on /ws/career-guidance
🎯 [WEBSOCKET] Career Guidance WebSocket server initialized
```

## Troubleshooting

### Common Issues

1. **Port conflicts**: Make sure no other service is using the same port
2. **JWT token issues**: Ensure valid JWT tokens are being used
3. **Database connection**: Make sure MongoDB is running and accessible
4. **File permissions**: Ensure the server has read access to all required files

### Debug Mode

To enable debug logging, set the environment variable:
```bash
DEBUG=websocket:career-guidance
```

## Production Considerations

1. **Rate limiting**: Implement rate limiting for WebSocket connections
2. **Authentication**: Ensure JWT tokens are properly validated
3. **Monitoring**: Set up monitoring for WebSocket connections
4. **Scaling**: Consider using Redis for WebSocket scaling in production
5. **Security**: Implement proper CORS and security headers

## Support

If you encounter any issues with the integration, check:
1. Console logs for error messages
2. Network connectivity
3. JWT token validity
4. Database connection status
