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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
"""
Enhanced Chatbot Controller
Phase 5: Integration & Orchestration

This service orchestrates all chatbot functionality:
- Conversation memory
- Intent classification
- Path modification
- Progress tracking
- Response generation
"""

from typing import Dict, Optional, List
import time
from datetime import datetime

from src.services.conversation_manager import ConversationManager
from src.services.intent_classifier import IntentClassifier
from src.services.path_modifier import PathModifier
from src.services.progress_tracker import ProgressTracker
from src.ml.model_orchestrator import ModelOrchestrator
from src.utils.helpers import count_tokens, estimate_api_cost
from web_app.models import UserLearningPath


class EnhancedChatbot:
    """
    Enhanced conversational chatbot with memory, intent understanding,
    and path modification capabilities.
    
    Features:
    - Multi-turn conversations with memory
    - Intent classification and routing
    - Dynamic path modifications
    - Progress tracking and insights
    - Contextual responses
    """
    
    def __init__(self):
        """Initialize the enhanced chatbot."""
        self.conversation_manager = ConversationManager(context_window_size=10)
        self.intent_classifier = IntentClassifier()
        self.path_modifier = PathModifier()
        self.progress_tracker = ProgressTracker()
        self.orchestrator = ModelOrchestrator()
    
    def process_message(
        self,
        user_id: int,
        message: str,
        learning_path_id: Optional[str] = None
    ) -> Dict:
        """
        Process a user message and generate response.
        
        This is the main entry point for the chatbot.
        
        Args:
            user_id: User ID
            message: User's message
            learning_path_id: Optional learning path ID for context
            
        Returns:
            Dictionary with response and metadata
        """
        start_time = time.time()
        
        try:
            # Step 1: Store user message
            user_msg = self.conversation_manager.add_message(
                user_id=user_id,
                message=message,
                role='user',
                learning_path_id=learning_path_id
            )
            
            # Step 2: Get conversation context
            conversation_context = self.conversation_manager.get_context_window(
                user_id=user_id,
                learning_path_id=learning_path_id
            )
            
            # Step 3: Get learning path data if available
            learning_path_data = None
            if learning_path_id:
                learning_path = UserLearningPath.query.get(learning_path_id)
                if learning_path and learning_path.user_id == user_id:
                    learning_path_data = learning_path.path_data_json
            
            # Step 4: Classify intent
            intent, entities, confidence = self.intent_classifier.classify_intent(
                message=message,
                conversation_context=conversation_context,
                learning_path_data=learning_path_data
            )
            
            print(f"🎯 Intent: {intent} (confidence: {confidence:.2f})")
            print(f"πŸ“¦ Entities: {entities}")
            
            # Step 5: Route to appropriate handler
            if intent == 'MODIFY_PATH' and learning_path_id:
                response_data = self._handle_path_modification(
                    user_id=user_id,
                    learning_path_id=learning_path_id,
                    message=message,
                    entities=entities,
                    chat_message_id=user_msg.id
                )
            
            elif intent == 'CHECK_PROGRESS' and learning_path_id:
                response_data = self._handle_progress_check(
                    user_id=user_id,
                    learning_path_id=learning_path_id,
                    entities=entities
                )
            
            elif intent == 'ASK_QUESTION':
                response_data = self._handle_question(
                    message=message,
                    conversation_context=conversation_context,
                    learning_path_data=learning_path_data
                )
            
            elif intent == 'REQUEST_HELP':
                response_data = self._handle_help_request(
                    message=message,
                    learning_path_data=learning_path_data,
                    conversation_context=conversation_context
                )
            
            else:  # GENERAL_CHAT
                response_data = self._handle_general_chat(
                    message=message,
                    conversation_context=conversation_context
                )
            
            # Step 6: Store assistant response
            response_time_ms = int((time.time() - start_time) * 1000)
            tokens_used = response_data.get('tokens_used', 0)
            
            self.conversation_manager.add_message(
                user_id=user_id,
                message=response_data['response'],
                role='assistant',
                learning_path_id=learning_path_id,
                intent=intent,
                entities=entities,
                tokens_used=tokens_used,
                response_time_ms=response_time_ms
            )
            
            # Step 7: Return response with metadata
            return {
                'success': True,
                'response': response_data['response'],
                'intent': intent,
                'entities': entities,
                'confidence': confidence,
                'response_time_ms': response_time_ms,
                'tokens_used': tokens_used,
                'metadata': response_data.get('metadata', {})
            }
        
        except Exception as e:
            print(f"Chatbot error: {e}")
            import traceback
            traceback.print_exc()
            
            # Return error response
            error_response = "I apologize, but I encountered an error processing your message. Please try again."
            
            self.conversation_manager.add_message(
                user_id=user_id,
                message=error_response,
                role='assistant',
                learning_path_id=learning_path_id
            )
            
            return {
                'success': False,
                'response': error_response,
                'error': str(e)
            }
    
    def _handle_path_modification(
        self,
        user_id: int,
        learning_path_id: str,
        message: str,
        entities: Dict,
        chat_message_id: int
    ) -> Dict:
        """Handle path modification requests."""
        print("πŸ”§ Handling path modification...")
        
        # Attempt to modify the path
        result = self.path_modifier.modify_path(
            learning_path_id=learning_path_id,
            user_id=user_id,
            modification_request=message,
            entities=entities,
            chat_message_id=chat_message_id
        )
        
        if result['success']:
            response = f"βœ… {result['description']}\n\nYour learning path has been updated successfully!"
            
            # Add details if available
            if 'changes' in result:
                changes = result['changes']
                if 'data' in changes:
                    response += "\n\nWhat changed:"
                    # Format the changes nicely
                    if 'resources' in changes.get('data', {}):
                        resources = changes['data']['resources']
                        response += f"\n- Added {len(resources)} new resource(s)"
        else:
            response = f"I couldn't modify your learning path: {result.get('error', 'Unknown error')}\n\n"
            response += "Could you please rephrase your request or be more specific?"
        
        return {
            'response': response,
            'tokens_used': 0,  # Modification doesn't use many tokens
            'metadata': result
        }
    
    def _handle_progress_check(
        self,
        user_id: int,
        learning_path_id: str,
        entities: Dict
    ) -> Dict:
        """Handle progress check requests."""
        print("πŸ“Š Handling progress check...")
        
        # Get progress summary
        progress = self.progress_tracker.get_progress_summary(
            user_id=user_id,
            learning_path_id=learning_path_id
        )
        
        if 'error' in progress:
            return {
                'response': f"I couldn't retrieve your progress: {progress['error']}",
                'tokens_used': 0
            }
        
        # Format progress report
        response = self._format_progress_report(progress)
        
        return {
            'response': response,
            'tokens_used': 0,  # Progress calculation doesn't use tokens
            'metadata': progress
        }
    
    def _handle_question(
        self,
        message: str,
        conversation_context: List[Dict],
        learning_path_data: Optional[Dict]
    ) -> Dict:
        """Handle content questions."""
        print("❓ Handling question...")
        
        # Build context for AI
        context_parts = []
        
        if learning_path_data:
            context_parts.append(f"Learning Path: {learning_path_data.get('title', 'Unknown')}")
            context_parts.append(f"Topic: {learning_path_data.get('topic', 'Unknown')}")
        
        # Build prompt
        system_message = """You are an expert educational AI assistant. Answer the user's question clearly and helpfully.
If the question is about their learning path, provide specific, actionable advice.
Keep your response concise but informative."""
        
        # Add conversation context
        messages = [{"role": "system", "content": system_message}]
        
        # Add recent context (last 4 messages)
        if conversation_context:
            messages.extend(conversation_context[-4:])
        
        # Add current question if not already in context
        if not conversation_context or conversation_context[-1]['content'] != message:
            messages.append({"role": "user", "content": message})
        
        # Generate response
        full_prompt = "\n".join([f"{m['role']}: {m['content']}" for m in messages])
        tokens = count_tokens(full_prompt)
        
        response = self.orchestrator.generate_response(
            prompt=message,
            relevant_documents=context_parts if context_parts else None,
            temperature=0.7,
            use_cache=True
        )
        
        return {
            'response': response,
            'tokens_used': tokens
        }
    
    def _handle_help_request(
        self,
        message: str,
        learning_path_data: Optional[Dict],
        conversation_context: List[Dict]
    ) -> Dict:
        """Handle help requests."""
        print("πŸ†˜ Handling help request...")
        
        # Build supportive response
        context_parts = []
        
        if learning_path_data:
            context_parts.append(f"User is learning: {learning_path_data.get('title', 'Unknown')}")
            context_parts.append(f"Expertise level: {learning_path_data.get('expertise_level', 'Unknown')}")
        
        system_message = """You are a supportive learning coach. The user is asking for help.
Provide encouraging, specific guidance. Break down complex topics into manageable steps.
Be empathetic and motivating."""
        
        messages = [{"role": "system", "content": system_message}]
        if conversation_context:
            messages.extend(conversation_context[-4:])
        messages.append({"role": "user", "content": message})
        
        full_prompt = "\n".join([f"{m['role']}: {m['content']}" for m in messages])
        tokens = count_tokens(full_prompt)
        
        response = self.orchestrator.generate_response(
            prompt=message,
            relevant_documents=context_parts if context_parts else None,
            temperature=0.8,  # Slightly higher for more empathetic responses
            use_cache=True
        )
        
        return {
            'response': response,
            'tokens_used': tokens
        }
    
    def _handle_general_chat(
        self,
        message: str,
        conversation_context: List[Dict]
    ) -> Dict:
        """Handle general conversation."""
        print("πŸ’¬ Handling general chat...")
        
        system_message = """You are a friendly AI learning assistant. Engage in natural conversation
while staying focused on helping the user with their learning journey."""
        
        messages = [{"role": "system", "content": system_message}]
        if conversation_context:
            messages.extend(conversation_context[-4:])
        messages.append({"role": "user", "content": message})
        
        full_prompt = "\n".join([f"{m['role']}: {m['content']}" for m in messages])
        tokens = count_tokens(full_prompt)
        
        response = self.orchestrator.generate_response(
            prompt=message,
            temperature=0.8,
            use_cache=True
        )
        
        return {
            'response': response,
            'tokens_used': tokens
        }
    
    def _format_progress_report(self, progress: Dict) -> str:
        """Format progress data into a readable report."""
        report = f"""πŸ“Š **Your Learning Progress**

**Overall Progress:** {progress['completion_percentage']}% complete
({progress['completed_milestones']}/{progress['total_milestones']} milestones)

⏱️ **Time Spent:** {progress['time_spent_hours']} hours
"""
        
        # Current milestone
        if progress.get('current_milestone'):
            current = progress['current_milestone']
            report += f"\n🎯 **Current Milestone:** {current['title']}"
            report += f"\n   Estimated: {current['estimated_hours']} hours"
        
        # Estimated completion
        if progress.get('estimated_completion_date'):
            report += f"\n\nπŸ“… **Estimated Completion:** {progress['estimated_completion_date']}"
        
        # Streak
        if progress.get('streak_days', 0) > 0:
            report += f"\n\nπŸ”₯ **Streak:** {progress['streak_days']} days - Keep it up!"
        
        # Pace analysis
        if progress.get('pace_analysis'):
            pace = progress['pace_analysis']
            report += f"\n\nπŸ“ˆ **Pace:** You're {pace['description']}"
        
        # Skills acquired
        if progress.get('skills_acquired'):
            skills = progress['skills_acquired'][:5]  # Show first 5
            if skills:
                report += f"\n\nβœ… **Skills Acquired:**"
                for skill in skills:
                    report += f"\n   β€’ {skill}"
                if len(progress['skills_acquired']) > 5:
                    report += f"\n   β€’ ...and {len(progress['skills_acquired']) - 5} more!"
        
        # Insights
        if progress.get('insights'):
            report += "\n\nπŸ’‘ **Insights:**"
            for insight in progress['insights'][:3]:  # Show top 3
                report += f"\n   β€’ {insight}"
        
        return report