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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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
const axios = require('axios');
const logger = require('../utils/logger');
const ugaService = require('./ugaService');
const aiService = require('./aiService');
const { redisUtils } = require('../utils/redis');

class AgenticService {
  constructor() {
    // Define available actions the agent can perform
    this.availableActions = {
      'register_for_course': this.registerForCourse.bind(this),
      'drop_course': this.dropCourse.bind(this),
      'check_prerequisites': this.checkPrerequisites.bind(this),
      'join_waitlist': this.joinWaitlist.bind(this),
      'submit_assignment': this.submitAssignment.bind(this),
      'schedule_advising': this.scheduleAdvising.bind(this),
      'apply_financial_aid': this.applyFinancialAid.bind(this),
      'pay_tuition': this.payTuition.bind(this),
      'apply_housing': this.applyHousing.bind(this),
      'select_meal_plan': this.selectMealPlan.bind(this),
      'book_study_room': this.bookStudyRoom.bind(this),
      'order_transcript': this.orderTranscript.bind(this),
      'update_address': this.updateAddress.bind(this),
      'reset_password': this.resetPassword.bind(this),
      'check_grades': this.checkGrades.bind(this),
      'find_textbooks': this.findTextbooks.bind(this),
      'check_bus_schedule': this.checkBusSchedule.bind(this),
      'find_parking': this.findParking.bind(this),
      'make_appointment': this.makeAppointment.bind(this)
    };
  }

  async processAgenticRequest(message, user, conversationHistory = []) {
    try {
      // Analyze the message to determine if it requires actions
      const actionAnalysis = await this.analyzeForActions(message, user);
      
      if (!actionAnalysis.requiresAction) {
        return { 
          requiresAction: false, 
          message: 'This request doesn\'t require any actions to be taken.' 
        };
      }

      // Plan the actions needed
      const actionPlan = await this.planActions(actionAnalysis, user, conversationHistory);
      
      // Execute the planned actions
      const executionResults = await this.executeActions(actionPlan, user);
      
      // Generate a comprehensive response
      const response = await this.generateAgenticResponse(
        message, 
        actionPlan, 
        executionResults, 
        user
      );

      return {
        requiresAction: true,
        actionsPlan: actionPlan,
        executionResults,
        response: response.content,
        metadata: response.metadata
      };

    } catch (error) {
      logger.error('Agentic processing error:', error);
      return {
        requiresAction: false,
        error: 'Failed to process agentic request',
        fallbackMessage: 'I encountered an issue while trying to help you. Please try again or contact support.'
      };
    }
  }

  async analyzeForActions(message, user) {
    try {
      const actionKeywords = {
        'register_for_course': ['register for', 'enroll in', 'add course', 'sign up for'],
        'drop_course': ['drop', 'withdraw from', 'remove course'],
        'check_prerequisites': ['prereq', 'prerequisite', 'requirements for'],
        'join_waitlist': ['waitlist', 'wait list', 'join waiting'],
        'submit_assignment': ['submit', 'turn in', 'upload assignment'],
        'schedule_advising': ['schedule', 'book', 'advising appointment'],
        'apply_financial_aid': ['apply for aid', 'fafsa', 'submit financial'],
        'pay_tuition': ['pay tuition', 'make payment', 'pay bill'],
        'apply_housing': ['apply for housing', 'housing application'],
        'select_meal_plan': ['choose meal plan', 'select dining'],
        'book_study_room': ['book room', 'reserve study'],
        'order_transcript': ['transcript', 'official transcript'],
        'update_address': ['change address', 'update address'],
        'reset_password': ['reset password', 'forgot password'],
        'check_grades': ['check grades', 'view grades', 'my gpa'],
        'find_textbooks': ['textbook', 'book list', 'course materials'],
        'check_bus_schedule': ['bus schedule', 'transit'],
        'find_parking': ['parking', 'parking spot'],
        'make_appointment': ['appointment', 'schedule meeting']
      };

      const lowerMessage = message.toLowerCase();
      const detectedActions = [];

      for (const [action, keywords] of Object.entries(actionKeywords)) {
        for (const keyword of keywords) {
          if (lowerMessage.includes(keyword)) {
            detectedActions.push(action);
            break;
          }
        }
      }

      return {
        requiresAction: detectedActions.length > 0,
        detectedActions,
        confidence: detectedActions.length > 0 ? 0.8 : 0,
        extractedEntities: this.extractEntities(message)
      };

    } catch (error) {
      logger.error('Action analysis error:', error);
      return { requiresAction: false, detectedActions: [], confidence: 0 };
    }
  }

  extractEntities(message) {
    const entities = {
      courses: [],
      times: [],
      locations: [],
      amounts: [],
      dates: []
    };

    // Extract course codes (e.g., CSCI 1301, MATH 2250)
    const coursePattern = /\b[A-Z]{3,4}\s*\d{4}\b/g;
    const courses = message.match(coursePattern);
    if (courses) {
      entities.courses = courses;
    }

    // Extract times (e.g., 10:00 AM, 2:30 PM)
    const timePattern = /\b\d{1,2}:\d{2}\s*(AM|PM|am|pm)\b/g;
    const times = message.match(timePattern);
    if (times) {
      entities.times = times;
    }

    // Extract dollar amounts
    const amountPattern = /\$\d+(?:,\d{3})*(?:\.\d{2})?/g;
    const amounts = message.match(amountPattern);
    if (amounts) {
      entities.amounts = amounts;
    }

    // Extract dates
    const datePattern = /\b(?:\d{1,2}\/\d{1,2}\/\d{4}|\w+\s+\d{1,2},?\s+\d{4})\b/g;
    const dates = message.match(datePattern);
    if (dates) {
      entities.dates = dates;
    }

    return entities;
  }

  async planActions(actionAnalysis, user, conversationHistory) {
    const actionPlan = {
      actions: [],
      estimatedTime: 0,
      requiresConfirmation: false,
      prerequisites: [],
      risks: []
    };

    for (const actionType of actionAnalysis.detectedActions) {
      const actionDetails = await this.getActionDetails(actionType, actionAnalysis.extractedEntities, user);
      actionPlan.actions.push(actionDetails);
      actionPlan.estimatedTime += actionDetails.estimatedTime || 30; // seconds

      // Check if action requires confirmation
      if (actionDetails.requiresConfirmation) {
        actionPlan.requiresConfirmation = true;
      }

      // Add prerequisites
      if (actionDetails.prerequisites) {
        actionPlan.prerequisites.push(...actionDetails.prerequisites);
      }

      // Add risks
      if (actionDetails.risks) {
        actionPlan.risks.push(...actionDetails.risks);
      }
    }

    return actionPlan;
  }

  async getActionDetails(actionType, entities, user) {
    const actionDetails = {
      type: actionType,
      status: 'planned',
      parameters: {},
      estimatedTime: 30,
      requiresConfirmation: false,
      prerequisites: [],
      risks: []
    };

    switch (actionType) {
      case 'register_for_course':
        actionDetails.parameters.courses = entities.courses;
        actionDetails.requiresConfirmation = true;
        actionDetails.estimatedTime = 60;
        actionDetails.prerequisites = ['Valid registration window', 'Prerequisites met', 'No time conflicts'];
        actionDetails.risks = ['Course may fill up', 'Schedule conflicts possible'];
        break;

      case 'pay_tuition':
        actionDetails.parameters.amounts = entities.amounts;
        actionDetails.requiresConfirmation = true;
        actionDetails.estimatedTime = 120;
        actionDetails.prerequisites = ['Valid payment method', 'Outstanding balance'];
        actionDetails.risks = ['Payment processing fees may apply'];
        break;

      case 'drop_course':
        actionDetails.parameters.courses = entities.courses;
        actionDetails.requiresConfirmation = true;
        actionDetails.estimatedTime = 45;
        actionDetails.prerequisites = ['Within drop period'];
        actionDetails.risks = ['May affect full-time status', 'Financial aid implications'];
        break;

      case 'apply_housing':
        actionDetails.requiresConfirmation = true;
        actionDetails.estimatedTime = 300; // 5 minutes
        actionDetails.prerequisites = ['Housing application period open', 'Deposit payment ready'];
        actionDetails.risks = ['Limited availability', 'Preference not guaranteed'];
        break;

      case 'book_study_room':
        actionDetails.parameters.times = entities.times;
        actionDetails.parameters.dates = entities.dates;
        actionDetails.estimatedTime = 30;
        break;

      default:
        actionDetails.estimatedTime = 60;
        break;
    }

    return actionDetails;
  }

  async executeActions(actionPlan, user) {
    const results = [];

    for (const action of actionPlan.actions) {
      try {
        logger.info(`Executing action: ${action.type}`, { userId: user.id, action: action.type });
        
        action.status = 'executing';
        const result = await this.availableActions[action.type](action, user);
        
        action.status = result.success ? 'completed' : 'failed';
        results.push({
          action: action.type,
          success: result.success,
          message: result.message,
          data: result.data,
          executionTime: result.executionTime
        });

      } catch (error) {
        logger.error(`Action execution failed: ${action.type}`, error);
        action.status = 'failed';
        results.push({
          action: action.type,
          success: false,
          message: `Failed to execute ${action.type}: ${error.message}`,
          error: error.message
        });
      }
    }

    return results;
  }

  // Action implementations
  async registerForCourse(action, user) {
    const startTime = Date.now();
    
    try {
      const courses = action.parameters.courses || [];
      if (courses.length === 0) {
        return {
          success: false,
          message: 'No courses specified for registration',
          executionTime: Date.now() - startTime
        };
      }

      // Check registration window
      const registrationInfo = await ugaService.getRegistrationInfo(user.id, user.token);
      if (!registrationInfo.success) {
        return {
          success: false,
          message: 'Unable to verify registration eligibility',
          executionTime: Date.now() - startTime
        };
      }

      const results = [];
      for (const courseCode of courses) {
        // Simulate course registration via Athena API
        const registrationResult = await this.simulateAthenaRegistration(courseCode, user);
        results.push({
          course: courseCode,
          success: registrationResult.success,
          message: registrationResult.message
        });
      }

      return {
        success: results.every(r => r.success),
        message: `Registration attempt completed for ${courses.length} course(s)`,
        data: results,
        executionTime: Date.now() - startTime
      };

    } catch (error) {
      return {
        success: false,
        message: `Registration failed: ${error.message}`,
        executionTime: Date.now() - startTime
      };
    }
  }

  async simulateAthenaRegistration(courseCode, user) {
    // In a real implementation, this would connect to Athena API
    // For demo purposes, we'll simulate the registration process
    
    // Random success/failure for demo
    const success = Math.random() > 0.3; // 70% success rate
    
    if (success) {
      return {
        success: true,
        message: `Successfully registered for ${courseCode}`
      };
    } else {
      const reasons = [
        'Course is full',
        'Prerequisites not met',
        'Time conflict detected',
        'Registration window closed',
        'Course not found'
      ];
      const reason = reasons[Math.floor(Math.random() * reasons.length)];
      return {
        success: false,
        message: `Failed to register for ${courseCode}: ${reason}`
      };
    }
  }

  async payTuition(action, user) {
    const startTime = Date.now();
    
    try {
      const amounts = action.parameters.amounts || [];
      const paymentAmount = amounts[0] || 'full balance';

      // Get billing information
      const billing = await ugaService.getBillingInfo(user.id, user.token);
      if (!billing.success) {
        return {
          success: false,
          message: 'Unable to access billing information',
          executionTime: Date.now() - startTime
        };
      }

      // Simulate payment processing
      const paymentResult = await this.simulatePaymentProcessing(paymentAmount, user);

      return {
        success: paymentResult.success,
        message: paymentResult.message,
        data: {
          amount: paymentAmount,
          transactionId: paymentResult.transactionId,
          confirmationNumber: paymentResult.confirmationNumber
        },
        executionTime: Date.now() - startTime
      };

    } catch (error) {
      return {
        success: false,
        message: `Payment failed: ${error.message}`,
        executionTime: Date.now() - startTime
      };
    }
  }

  async simulatePaymentProcessing(amount, user) {
    // Simulate payment processing delay
    await new Promise(resolve => setTimeout(resolve, 2000));

    // Random success/failure for demo
    const success = Math.random() > 0.1; // 90% success rate

    if (success) {
      return {
        success: true,
        message: `Payment of ${amount} processed successfully`,
        transactionId: `TXN${Date.now()}`,
        confirmationNumber: `UGA${Math.random().toString(36).substr(2, 9).toUpperCase()}`
      };
    } else {
      return {
        success: false,
        message: 'Payment processing failed. Please verify your payment method and try again.'
      };
    }
  }

  async bookStudyRoom(action, user) {
    const startTime = Date.now();
    
    try {
      const times = action.parameters.times || ['next available'];
      const dates = action.parameters.dates || [new Date().toDateString()];

      // Simulate room booking
      const bookingResult = await this.simulateRoomBooking(times[0], dates[0], user);

      return {
        success: bookingResult.success,
        message: bookingResult.message,
        data: {
          room: bookingResult.room,
          time: times[0],
          date: dates[0],
          confirmationCode: bookingResult.confirmationCode
        },
        executionTime: Date.now() - startTime
      };

    } catch (error) {
      return {
        success: false,
        message: `Room booking failed: ${error.message}`,
        executionTime: Date.now() - startTime
      };
    }
  }

  async simulateRoomBooking(time, date, user) {
    const rooms = [
      'Miller Learning Center - Room 234',
      'Main Library - Study Room 12',
      'Science Library - Group Room A',
      'Student Center - Conference Room 3'
    ];

    const success = Math.random() > 0.2; // 80% success rate

    if (success) {
      return {
        success: true,
        message: `Study room booked successfully`,
        room: rooms[Math.floor(Math.random() * rooms.length)],
        confirmationCode: `ROOM${Math.random().toString(36).substr(2, 6).toUpperCase()}`
      };
    } else {
      return {
        success: false,
        message: 'No rooms available at the requested time. Please try a different time slot.'
      };
    }
  }

  // Implement other action methods similarly...
  async dropCourse(action, user) { 
    // Implementation for dropping courses
    return { success: true, message: 'Course drop functionality would be implemented here', executionTime: 1000 };
  }

  async checkPrerequisites(action, user) { 
    // Implementation for checking prerequisites
    return { success: true, message: 'Prerequisite check functionality would be implemented here', executionTime: 500 };
  }

  async joinWaitlist(action, user) { 
    // Implementation for joining waitlists
    return { success: true, message: 'Waitlist functionality would be implemented here', executionTime: 750 };
  }

  async submitAssignment(action, user) { 
    // Implementation for submitting assignments
    return { success: true, message: 'Assignment submission functionality would be implemented here', executionTime: 2000 };
  }

  async scheduleAdvising(action, user) { 
    // Implementation for scheduling advising appointments
    return { success: true, message: 'Advising scheduling functionality would be implemented here', executionTime: 1500 };
  }

  async applyFinancialAid(action, user) { 
    // Implementation for financial aid applications
    return { success: true, message: 'Financial aid application functionality would be implemented here', executionTime: 3000 };
  }

  async applyHousing(action, user) { 
    // Implementation for housing applications
    return { success: true, message: 'Housing application functionality would be implemented here', executionTime: 2500 };
  }

  async selectMealPlan(action, user) { 
    // Implementation for meal plan selection
    return { success: true, message: 'Meal plan selection functionality would be implemented here', executionTime: 1000 };
  }

  async orderTranscript(action, user) { 
    // Implementation for transcript orders
    return { success: true, message: 'Transcript order functionality would be implemented here', executionTime: 1500 };
  }

  async updateAddress(action, user) { 
    // Implementation for address updates
    return { success: true, message: 'Address update functionality would be implemented here', executionTime: 800 };
  }

  async resetPassword(action, user) { 
    // Implementation for password resets
    return { success: true, message: 'Password reset functionality would be implemented here', executionTime: 600 };
  }

  async checkGrades(action, user) { 
    // Implementation for grade checking
    return { success: true, message: 'Grade check functionality would be implemented here', executionTime: 400 };
  }

  async findTextbooks(action, user) { 
    // Implementation for textbook finding
    return { success: true, message: 'Textbook search functionality would be implemented here', executionTime: 700 };
  }

  async checkBusSchedule(action, user) { 
    // Implementation for bus schedule checking
    return { success: true, message: 'Bus schedule functionality would be implemented here', executionTime: 300 };
  }

  async findParking(action, user) { 
    // Implementation for parking finding
    return { success: true, message: 'Parking finder functionality would be implemented here', executionTime: 400 };
  }

  async makeAppointment(action, user) { 
    // Implementation for general appointment making
    return { success: true, message: 'Appointment scheduling functionality would be implemented here', executionTime: 1200 };
  }

  async generateAgenticResponse(message, actionPlan, executionResults, user) {
    try {
      const contextPrompt = `
You are UGA Assistant executing actions for a student. Here's what happened:

ORIGINAL REQUEST: "${message}"

ACTIONS PLANNED:
${actionPlan.actions.map(action => 
  `- ${action.type}: ${action.status}`
).join('\n')}

EXECUTION RESULTS:
${executionResults.map(result => 
  `- ${result.action}: ${result.success ? 'SUCCESS' : 'FAILED'} - ${result.message}`
).join('\n')}

Generate a helpful response that:
1. Confirms what actions were taken
2. Reports the results clearly
3. Provides next steps if needed
4. Maintains a helpful, professional tone
`;

      const aiResponse = await aiService.generateResponse([
        { role: 'system', content: contextPrompt },
        { role: 'user', content: message }
      ], { userId: user.id });

      return aiResponse;

    } catch (error) {
      logger.error('Agentic response generation error:', error);
      return {
        content: 'I attempted to help you with your request. Please check the results and let me know if you need further assistance.',
        metadata: { error: error.message }
      };
    }
  }
}

module.exports = new AgenticService();