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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
const fetch = require('node-fetch');
const logger = require('../utils/logger');

class WebSearchService {
  constructor() {
    // Configuration for different search providers
    this.config = {
      // Google Custom Search API
      google: {
        apiKey: process.env.GOOGLE_SEARCH_API_KEY,
        searchEngineId: process.env.GOOGLE_SEARCH_ENGINE_ID,
        endpoint: 'https://www.googleapis.com/customsearch/v1'
      },

      // Bing Search API
      bing: {
        apiKey: process.env.BING_SEARCH_API_KEY,
        endpoint: 'https://api.bing.microsoft.com/v7.0/search'
      },

      // SearXNG (Self-hosted or public instance)
      searxng: {
        endpoint: process.env.SEARXNG_URL || 'https://searx.org',
        instance: process.env.SEARXNG_INSTANCE || 'searx.org'
      }
    };

    // Cache for search results (in-memory, could be Redis in production)
    this.searchCache = new Map();
    this.cacheTimeout = 30 * 60 * 1000; // 30 minutes in milliseconds

    // Rate limiting
    this.rateLimiter = new Map();
    this.rateLimitWindow = 60 * 1000; // 1 minute
    this.maxRequestsPerWindow = 10;

    // UGA-specific search patterns
    this.ugaPatterns = {
      news: ['uga news', 'university of georgia news', 'athens clarke news'],
      events: ['uga events', 'university of georgia events', 'uga calendar'],
      academics: ['uga academic calendar', 'uga registration', 'uga classes'],
      dining: ['uga dining', 'uga meal plans', 'uga food'],
      housing: ['uga housing', 'uga residence halls', 'uga dorms'],
      athletics: ['uga athletics', 'georgia bulldogs', 'uga sports'],
      admissions: ['uga admissions', 'uga applications', 'uga requirements'],
      campus: ['uga campus', 'athens georgia', 'uga facilities']
    };

    logger.info('WebSearchService initialized', {
      googleEnabled: !!this.config.google.apiKey,
      bingEnabled: !!this.config.bing.apiKey,
      searxngEnabled: !!this.config.searxng.endpoint
    });
  }

  /**
   * Main search method that determines the best provider and executes search
   */
  async search(query, options = {}) {
    try {
      const searchId = this.generateSearchId(query, options);

      // Check cache first
      const cachedResult = this.getCachedResult(searchId);
      if (cachedResult && !options.forceRefresh) {
        logger.info('Returning cached search result', { query, searchId });
        return cachedResult;
      }

      // Check rate limiting
      if (!this.checkRateLimit(options.userId || 'anonymous')) {
        throw new Error('Rate limit exceeded. Please try again later.');
      }

      // Enhance query for UGA-specific searches
      const enhancedQuery = this.enhanceUGAQuery(query, options);

      // Try different search providers in order of preference
      let searchResult = null;

      // Priority 1: Google Custom Search (most reliable)
      if (this.config.google.apiKey && this.config.google.searchEngineId) {
        try {
          searchResult = await this.googleSearch(enhancedQuery, options);
          logger.info('Google search successful', { query: enhancedQuery });
        } catch (error) {
          logger.warn('Google search failed, trying next provider', { error: error.message });
        }
      }

      // Priority 2: Bing Search API (fallback)
      if (!searchResult && this.config.bing.apiKey) {
        try {
          searchResult = await this.bingSearch(enhancedQuery, options);
          logger.info('Bing search successful', { query: enhancedQuery });
        } catch (error) {
          logger.warn('Bing search failed, trying next provider', { error: error.message });
        }
      }

      // Priority 3: SearXNG (open source fallback)
      if (!searchResult) {
        try {
          searchResult = await this.searxngSearch(enhancedQuery, options);
          logger.info('SearXNG search successful', { query: enhancedQuery });
        } catch (error) {
          logger.warn('SearXNG search failed', { error: error.message });
        }
      }

      if (!searchResult) {
        throw new Error('All search providers failed');
      }

      // Process and enhance results
      const processedResult = this.processSearchResults(searchResult, query, options);

      // Cache the result
      this.cacheResult(searchId, processedResult);

      return processedResult;

    } catch (error) {
      logger.error('Web search error:', error);
      throw new Error(`Search failed: ${error.message}`);
    }
  }

  /**
   * Google Custom Search implementation
   */
  async googleSearch(query, options = {}) {
    const params = new URLSearchParams({
      key: this.config.google.apiKey,
      cx: this.config.google.searchEngineId,
      q: query,
      num: options.maxResults || 5,
      safe: 'active'
    });

    // Add site restriction for UGA-specific searches
    if (options.ugaOnly) {
      params.append('siteSearch', 'uga.edu');
      params.append('siteSearchFilter', 'i'); // include
    }

    const response = await fetch(`${this.config.google.endpoint}?${params}`, {
      headers: {
        'User-Agent': 'UGA-edi.chat/1.0'
      },
      timeout: 10000
    });

    if (!response.ok) {
      throw new Error(`Google Search API error: ${response.status}`);
    }

    const data = await response.json();

    return {
      provider: 'google',
      query,
      results: data.items || [],
      totalResults: parseInt(data.searchInformation?.totalResults) || 0,
      searchTime: parseFloat(data.searchInformation?.searchTime) || 0
    };
  }

  /**
   * Bing Search API implementation
   */
  async bingSearch(query, options = {}) {
    const params = new URLSearchParams({
      q: query,
      count: options.maxResults || 5,
      safeSearch: 'Moderate'
    });

    // Add site restriction for UGA-specific searches
    if (options.ugaOnly) {
      params.set('q', `${query} site:uga.edu`);
    }

    const response = await fetch(`${this.config.bing.endpoint}?${params}`, {
      headers: {
        'Ocp-Apim-Subscription-Key': this.config.bing.apiKey,
        'User-Agent': 'UGA-edi.chat/1.0'
      },
      timeout: 10000
    });

    if (!response.ok) {
      throw new Error(`Bing Search API error: ${response.status}`);
    }

    const data = await response.json();

    // Convert Bing format to standard format
    const results = (data.webPages?.value || []).map(item => ({
      title: item.name,
      link: item.url,
      snippet: item.snippet,
      displayLink: item.displayUrl
    }));

    return {
      provider: 'bing',
      query,
      results,
      totalResults: data.webPages?.totalEstimatedMatches || 0,
      searchTime: 0
    };
  }

  /**
   * SearXNG search implementation (open source)
   */
  async searxngSearch(query, options = {}) {
    const params = new URLSearchParams({
      q: query,
      format: 'json',
      engines: 'google,bing,duckduckgo',
      lang: 'en'
    });

    // Add site restriction for UGA-specific searches
    if (options.ugaOnly) {
      params.set('q', `${query} site:uga.edu`);
    }

    const response = await fetch(`${this.config.searxng.endpoint}/search?${params}`, {
      headers: {
        'User-Agent': 'UGA-edi.chat/1.0'
      },
      timeout: 15000
    });

    if (!response.ok) {
      throw new Error(`SearXNG error: ${response.status}`);
    }

    const data = await response.json();

    // Convert SearXNG format to standard format and limit results
    const results = (data.results || [])
      .slice(0, options.maxResults || 5)
      .map(item => ({
        title: item.title,
        link: item.url,
        snippet: item.content || '',
        displayLink: item.pretty_url || item.url
      }));

    return {
      provider: 'searxng',
      query,
      results,
      totalResults: data.results?.length || 0,
      searchTime: 0
    };
  }

  /**
   * Detect if a query needs current/live information
   */
  shouldUseWebSearch(message) {
    const currentInfoKeywords = [
      // Time-sensitive keywords
      'current', 'latest', 'recent', 'today', 'now', 'this week', 'this month',
      'new', 'upcoming', 'updated', '2024', '2025',

      // News and events
      'news', 'events', 'happening', 'schedule', 'calendar', 'announcement',

      // UGA-specific time-sensitive
      'registration', 'deadline', 'apply', 'application', 'semester',
      'academic calendar', 'finals', 'break', 'graduation',

      // Services and hours
      'hours', 'open', 'closed', 'available', 'operating',
      'weather', 'traffic', 'construction', 'closure',

      // Dining and facilities
      'dining hours', 'gym hours', 'library hours', 'menu'
    ];

    const ugaTimeKeywords = [
      'uga news', 'uga events', 'uga schedule', 'uga calendar',
      'registration dates', 'academic calendar', 'uga deadlines',
      'uga dining hours', 'uga facilities', 'uga construction'
    ];

    const lowerMessage = message.toLowerCase();

    // Check for general time-sensitive keywords
    const hasCurrentKeywords = currentInfoKeywords.some(keyword =>
      lowerMessage.includes(keyword)
    );

    // Check for UGA-specific time-sensitive keywords
    const hasUGATimeKeywords = ugaTimeKeywords.some(keyword =>
      lowerMessage.includes(keyword)
    );

    // Also check for question patterns that typically need current info
    const currentQuestionPatterns = [
      /what.*happening.*uga/i,
      /when.*registration/i,
      /what.*hours.*uga/i,
      /what.*new.*uga/i,
      /uga.*today/i,
      /current.*uga/i
    ];

    const hasCurrentQuestionPattern = currentQuestionPatterns.some(pattern =>
      pattern.test(message)
    );

    return hasCurrentKeywords || hasUGATimeKeywords || hasCurrentQuestionPattern;
  }

  /**
   * Enhance query with UGA-specific terms
   */
  enhanceUGAQuery(query, options = {}) {
    const lowerQuery = query.toLowerCase();
    let enhancedQuery = query;

    // Add UGA context if not already present
    if (!lowerQuery.includes('uga') && !lowerQuery.includes('university of georgia')) {
      // Determine query category and enhance accordingly
      for (const [category, patterns] of Object.entries(this.ugaPatterns)) {
        if (patterns.some(pattern => lowerQuery.includes(pattern.split(' ').slice(-1)[0]))) {
          enhancedQuery = `UGA ${query}`;
          break;
        }
      }

      // If no specific pattern matched, add general UGA context
      if (enhancedQuery === query) {
        enhancedQuery = `University of Georgia UGA ${query}`;
      }
    }

    // Add Athens context for location-based queries
    if (lowerQuery.includes('dining') || lowerQuery.includes('restaurant') ||
        lowerQuery.includes('food') || lowerQuery.includes('near')) {
      enhancedQuery += ' Athens Georgia';
    }

    return enhancedQuery;
  }

  /**
   * Process and summarize search results for AI context
   */
  processSearchResults(searchResult, originalQuery, options = {}) {
    const { results, provider, totalResults } = searchResult;

    if (!results || results.length === 0) {
      return {
        success: false,
        message: 'No search results found',
        provider,
        query: originalQuery,
        results: []
      };
    }

    // Create a summary for AI consumption
    const summary = this.createSearchSummary(results, originalQuery);

    // Extract key information
    const keyInfo = this.extractKeyInformation(results, originalQuery);

    return {
      success: true,
      provider,
      query: originalQuery,
      summary,
      keyInfo,
      results: results.map(result => ({
        title: result.title,
        url: result.link,
        snippet: result.snippet,
        domain: result.displayLink
      })),
      totalResults,
      searchTime: searchResult.searchTime,
      timestamp: new Date().toISOString()
    };
  }

  /**
   * Create a concise summary of search results for AI context
   */
  createSearchSummary(results, query) {
    const summaryPoints = results.slice(0, 3).map(result => {
      const title = result.title;
      const snippet = result.snippet || '';
      return `• ${title}: ${snippet.substring(0, 150)}${snippet.length > 150 ? '...' : ''}`;
    });

    return `Search results for "${query}":\n${summaryPoints.join('\n')}`;
  }

  /**
   * Extract key information from search results
   */
  extractKeyInformation(results, query) {
    const keyInfo = {
      ugaOfficial: [],
      news: [],
      events: [],
      dates: [],
      contacts: []
    };

    results.forEach(result => {
      const text = `${result.title} ${result.snippet}`.toLowerCase();
      const url = result.link || '';

      // UGA official sources
      if (url.includes('uga.edu')) {
        keyInfo.ugaOfficial.push({
          title: result.title,
          url: result.link,
          snippet: result.snippet
        });
      }

      // News items
      if (text.includes('news') || text.includes('announcement') || text.includes('update')) {
        keyInfo.news.push(result.title);
      }

      // Events
      if (text.includes('event') || text.includes('calendar') || text.includes('schedule')) {
        keyInfo.events.push(result.title);
      }

      // Extract dates
      const dateMatches = text.match(/\b\d{1,2}\/\d{1,2}\/\d{4}\b|\b\d{4}-\d{2}-\d{2}\b/g);
      if (dateMatches) {
        keyInfo.dates.push(...dateMatches);
      }

      // Extract contact information
      const phoneMatches = text.match(/\b\d{3}-\d{3}-\d{4}\b/g);
      if (phoneMatches) {
        keyInfo.contacts.push(...phoneMatches);
      }
    });

    return keyInfo;
  }

  /**
   * Generate unique search ID for caching
   */
  generateSearchId(query, options) {
    const optionsString = JSON.stringify(options);
    return `search_${Buffer.from(query + optionsString).toString('base64')}`;
  }

  /**
   * Get cached search result
   */
  getCachedResult(searchId) {
    const cached = this.searchCache.get(searchId);
    if (cached && (Date.now() - cached.timestamp) < this.cacheTimeout) {
      return cached.result;
    }
    return null;
  }

  /**
   * Cache search result
   */
  cacheResult(searchId, result) {
    this.searchCache.set(searchId, {
      result,
      timestamp: Date.now()
    });

    // Clean old cache entries periodically
    if (this.searchCache.size > 100) {
      this.cleanCache();
    }
  }

  /**
   * Clean expired cache entries
   */
  cleanCache() {
    const now = Date.now();
    for (const [key, value] of this.searchCache.entries()) {
      if ((now - value.timestamp) > this.cacheTimeout) {
        this.searchCache.delete(key);
      }
    }
  }

  /**
   * Check rate limiting
   */
  checkRateLimit(userId) {
    const now = Date.now();
    const userRequests = this.rateLimiter.get(userId) || [];

    // Remove old requests outside the window
    const recentRequests = userRequests.filter(timestamp =>
      (now - timestamp) < this.rateLimitWindow
    );

    if (recentRequests.length >= this.maxRequestsPerWindow) {
      return false;
    }

    // Add current request
    recentRequests.push(now);
    this.rateLimiter.set(userId, recentRequests);

    return true;
  }

  /**
   * Get search configuration status
   */
  getStatus() {
    return {
      providers: {
        google: {
          enabled: !!(this.config.google.apiKey && this.config.google.searchEngineId),
          configured: !!(this.config.google.apiKey && this.config.google.searchEngineId)
        },
        bing: {
          enabled: !!this.config.bing.apiKey,
          configured: !!this.config.bing.apiKey
        },
        searxng: {
          enabled: !!this.config.searxng.endpoint,
          configured: !!this.config.searxng.endpoint
        }
      },
      cache: {
        size: this.searchCache.size,
        maxAge: this.cacheTimeout
      },
      rateLimit: {
        windowMs: this.rateLimitWindow,
        maxRequests: this.maxRequestsPerWindow
      }
    };
  }
}

module.exports = new WebSearchService();