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54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const path = require('path');
const rateLimit = require('express-rate-limit');
require('dotenv').config();

// Import utilities and services
const logger = require('./src/utils/logger');
const { connectDB, isDatabaseConnected } = require('./src/utils/database');
const { connectRedis } = require('./src/utils/redis');

// Create Express application
const app = express();
const PORT = process.env.PORT || 5001;

// Security middleware with UGA-specific headers
app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      styleSrc: ["'self'", "'unsafe-inline'", "https://fonts.googleapis.com"],
      scriptSrc: ["'self'", "'unsafe-inline'"],
      fontSrc: ["'self'", "https://fonts.gstatic.com"],
      imgSrc: ["'self'", "data:", "https:", "http:"],
      connectSrc: ["'self'", "http://localhost:11434", "ws:", "wss:", "https://api.openai.com"]
    }
  },
  crossOriginEmbedderPolicy: false,
  hsts: {
    maxAge: 31536000,
    includeSubDomains: true,
    preload: true
  }
}));

// CORS configuration for UGA environment
app.use(cors({
  origin: function (origin, callback) {
    // Allow requests with no origin (like mobile apps or curl requests)
    if (!origin) return callback(null, true);

    const allowedOrigins = [
      'http://localhost:3000',
      'http://localhost:7860',
      'https://uga.edu',
      'https://*.uga.edu',
      'https://huggingface.co',
      'https://*.hf.space'
    ];

    // Check if origin matches any allowed pattern
    const isAllowed = allowedOrigins.some(pattern => {
      if (pattern.includes('*')) {
        const regex = new RegExp(pattern.replace(/\*/g, '.*'));
        return regex.test(origin);
      }
      return pattern === origin;
    });

    if (isAllowed || process.env.NODE_ENV === 'development') {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'));
    }
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With']
}));

// Request logging
app.use(morgan('combined', {
  stream: {
    write: message => logger.info(message.trim())
  },
  skip: (req) => req.url === '/health' && req.method === 'GET'
}));

// Rate limiting with different limits for different endpoints
const generalLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
  message: {
    success: false,
    error: 'Too many requests from this IP, please try again later.',
    retryAfter: '15 minutes'
  },
  standardHeaders: true,
  legacyHeaders: false,
});

const chatLimiter = rateLimit({
  windowMs: 1 * 60 * 1000, // 1 minute
  max: 20, // limit each IP to 20 chat requests per minute
  message: {
    success: false,
    error: 'Chat rate limit exceeded. Please wait before sending another message.',
    retryAfter: '1 minute'
  },
  standardHeaders: true,
  legacyHeaders: false,
});

const authLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 5, // limit each IP to 5 auth attempts per windowMs
  message: {
    success: false,
    error: 'Too many authentication attempts, please try again later.',
    retryAfter: '15 minutes'
  },
  standardHeaders: true,
  legacyHeaders: false,
});

// Apply rate limiting
app.use('/api/auth', authLimiter);
app.use('/api/chat', chatLimiter);
app.use('/api', generalLimiter);

// Body parsing with enhanced limits and validation
app.use(express.json({
  limit: '10mb',
  verify: (req, res, buf) => {
    try {
      JSON.parse(buf);
    } catch (e) {
      res.status(400).json({
        success: false,
        error: 'Invalid JSON format'
      });
      throw new Error('Invalid JSON');
    }
  }
}));

app.use(express.urlencoded({
  extended: true,
  limit: '10mb'
}));

// Trust proxy for proper IP detection in production
if (process.env.NODE_ENV === 'production') {
  app.set('trust proxy', 1);
}

// Serve static files
app.use(express.static(path.join(__dirname, 'public')));

// Database and Redis connections
const initializeServices = async () => {
  try {
    // Initialize database connection
    await connectDB();

    // Initialize Redis connection (optional)
    await connectRedis();

    logger.info('All services initialized successfully');
  } catch (error) {
    logger.error('Service initialization failed:', error);
    // Don't exit process - allow app to run without optional services
  }
};

// Enhanced health check endpoint
app.get('/health', async (req, res) => {
  const startTime = Date.now();

  try {
    const health = {
      status: 'healthy',
      timestamp: new Date().toISOString(),
      uptime: Math.floor(process.uptime()),
      memory: {
        used: Math.round(process.memoryUsage().heapUsed / 1024 / 1024),
        total: Math.round(process.memoryUsage().heapTotal / 1024 / 1024),
        external: Math.round(process.memoryUsage().external / 1024 / 1024)
      },
      services: {
        database: isDatabaseConnected() ? 'connected' : 'disconnected',
        redis: 'checking...',
        ollama: 'checking...'
      },
      environment: process.env.NODE_ENV || 'development',
      version: process.env.npm_package_version || '1.0.0',
      responseTime: 0
    };

    // Check Redis health
    try {
      const { redisUtils } = require('./src/utils/redis');
      await redisUtils.set('health_check', 'ok');
      const result = await redisUtils.get('health_check');
      health.services.redis = result === 'ok' ? 'connected' : 'error';
      await redisUtils.del('health_check');
    } catch (error) {
      health.services.redis = 'disconnected';
    }

    // Check Ollama health
    try {
      const ollamaUrl = process.env.LOCAL_AI_URL || 'http://localhost:11434';
      const controller = new AbortController();
      const timeoutId = setTimeout(() => controller.abort(), 3000);

      const response = await fetch(`${ollamaUrl}/api/tags`, {
        method: 'GET',
        signal: controller.signal
      });

      clearTimeout(timeoutId);
      health.services.ollama = response.ok ? 'connected' : 'error';
    } catch (error) {
      health.services.ollama = 'disconnected';
    }

    // Calculate overall health status
    const serviceStatuses = Object.values(health.services);
    if (serviceStatuses.every(status => status === 'connected')) {
      health.status = 'healthy';
    } else if (serviceStatuses.some(status => status === 'connected')) {
      health.status = 'degraded';
    } else {
      health.status = 'unhealthy';
    }

    health.responseTime = Date.now() - startTime;

    const statusCode = health.status === 'healthy' ? 200 :
                      health.status === 'degraded' ? 200 : 503;

    res.status(statusCode).json({
      success: true,
      data: health
    });

  } catch (error) {
    logger.error('Health check failed:', error);
    res.status(503).json({
      success: false,
      error: 'Health check failed',
      timestamp: new Date().toISOString(),
      responseTime: Date.now() - startTime
    });
  }
});

// API Routes with proper error handling
try {
  // Authentication routes
  app.use('/api/auth', require('./src/routes/auth'));

  // Chat routes
  app.use('/api/chat', require('./src/routes/chat'));

  // Dashboard routes
  app.use('/api/dashboard', require('./src/routes/dashboard'));

  // Search routes
  app.use('/api/search', require('./src/routes/search'));

  // Events routes
  app.use('/api/events', require('./src/routes/events'));

  // User routes
  app.use('/api/user', require('./src/routes/user'));

  // UGA-specific routes
  app.use('/api/uga', require('./src/routes/uga'));

  // Dining routes
  app.use('/api/dining', require('./src/routes/dining'));

  // Faculty routes
  app.use('/api/faculty', require('./src/routes/faculty'));

  // Document routes
  app.use('/api/documents', require('./src/routes/documents'));

  logger.info('All API routes loaded successfully');
} catch (error) {
  logger.error('Failed to load API routes:', error);
}

// Serve dashboard
app.get('/dashboard', (req, res) => {
  res.sendFile(path.join(__dirname, 'dashboard.html'));
});

// Serve demo
app.get('/demo', (req, res) => {
  res.sendFile(path.join(__dirname, 'demo.html'));
});

// API documentation endpoint
app.get('/api', (req, res) => {
  res.json({
    success: true,
    message: 'UGA edi.chat Backend API',
    version: '1.0.0',
    endpoints: {
      authentication: {
        'POST /api/auth/register': 'Register new user account',
        'POST /api/auth/login': 'Login with username/password',
        'POST /api/auth/logout': 'Logout user',
        'GET /api/auth/me': 'Get current user profile',
        'PUT /api/auth/profile': 'Update user profile',
        'POST /api/auth/forgot-password': 'Request password reset',
        'POST /api/auth/reset-password': 'Reset password with token',
        'POST /api/auth/change-password': 'Change password',
        'POST /api/auth/verify-email': 'Verify email address'
      },
      chat: {
        'POST /api/chat': 'Send chat message and get AI response',
        'GET /api/chat/history': 'Get chat history',
        'DELETE /api/chat/history/:id': 'Delete chat session'
      },
      uga: {
        'GET /api/uga/info': 'Get UGA information',
        'GET /api/uga/calendar': 'Get academic calendar',
        'GET /api/uga/directory': 'Search UGA directory'
      },
      events: {
        'GET /api/events': 'Get UGA events',
        'GET /api/events/:id': 'Get specific event',
        'GET /api/events/search': 'Search events'
      },
      dining: {
        'GET /api/dining/menus': 'Get dining hall menus',
        'GET /api/dining/locations': 'Get dining locations',
        'GET /api/dining/hours': 'Get dining hours'
      },
      search: {
        'POST /api/search': 'Perform web search',
        'GET /api/search/status': 'Get search service status',
        'GET /api/search/suggestions': 'Get search suggestions'
      },
      system: {
        'GET /health': 'System health check',
        'GET /api/dashboard/*': 'Dashboard analytics',
        'GET /dashboard': 'Dashboard interface'
      }
    },
    documentation: 'Visit /dashboard for system monitoring'
  });
});

// Request ID middleware for tracking
app.use((req, res, next) => {
  req.id = Math.random().toString(36).substr(2, 9);
  res.setHeader('X-Request-ID', req.id);
  next();
});

// Error handling middleware
app.use((err, req, res, next) => {
  const errorId = req.id || Math.random().toString(36).substr(2, 9);

  logger.error('Unhandled error:', {
    errorId,
    message: err.message,
    stack: err.stack,
    url: req.url,
    method: req.method,
    ip: req.ip,
    userAgent: req.get('User-Agent')
  });

  // Don't leak error details in production
  const isDevelopment = process.env.NODE_ENV === 'development';

  res.status(err.status || 500).json({
    success: false,
    error: isDevelopment ? err.message : 'Internal server error',
    errorId,
    ...(isDevelopment && { stack: err.stack })
  });
});

// 404 handler
app.use((req, res) => {
  res.status(404).json({
    success: false,
    error: 'Endpoint not found',
    message: `The endpoint ${req.method} ${req.path} does not exist`,
    availableEndpoints: '/api'
  });
});

// Graceful shutdown handlers
const gracefulShutdown = (signal) => {
  logger.info(`Received ${signal}, shutting down gracefully`);

  server.close((err) => {
    if (err) {
      logger.error('Error during server shutdown:', err);
      process.exit(1);
    }

    logger.info('Server closed successfully');
    process.exit(0);
  });

  // Force close after 30 seconds
  setTimeout(() => {
    logger.error('Forced shutdown after timeout');
    process.exit(1);
  }, 30000);
};

process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
process.on('SIGUSR2', () => gracefulShutdown('SIGUSR2')); // Nodemon restart

// Handle uncaught exceptions
process.on('uncaughtException', (err) => {
  logger.error('Uncaught Exception:', err);
  process.exit(1);
});

process.on('unhandledRejection', (reason, promise) => {
  logger.error('Unhandled Rejection at:', promise, 'reason:', reason);
  process.exit(1);
});

// Start server
const server = app.listen(PORT, '0.0.0.0', async () => {
  logger.info(`UGA edi.chat backend server running on port ${PORT}`);
  logger.info(`Environment: ${process.env.NODE_ENV || 'development'}`);
  logger.info(`Database: ${process.env.MONGODB_URI ? 'MongoDB enabled' : 'No database configured'}`);
  logger.info(`Redis: ${process.env.REDIS_URL ? 'Redis enabled' : 'No Redis configured'}`);
  logger.info(`Ollama: ${process.env.LOCAL_AI_URL || 'http://localhost:11434'}`);
  logger.info('Server started successfully');

  // Initialize services after server starts
  await initializeServices();

  logger.info('Backend initialization complete');
});

// Export for testing
module.exports = { app, server };