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
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
#!/usr/bin/env python3
"""

Integration Examples - How to use Chat Service in different scenarios.



This file shows practical examples of integrating the chat service

with various types of applications.

"""

from chat_service_client import ChatServiceClient, MultiUserChatManager
import asyncio
import time
from typing import Dict, List


# Example 1: Learning Management System (LMS) Integration
class LearningPlatformIntegration:
    """

    Example integration with a learning management system.

    

    This shows how to maintain separate chat sessions for different

    courses and students.

    """
    
    def __init__(self, chat_service_url: str = "http://localhost:5000"):
        self.chat_manager = MultiUserChatManager(chat_service_url, "LearningPlatform")
        self.course_languages = {
            "python-101": "python",
            "js-fundamentals": "javascript",
            "java-oop": "java",
            "cpp-advanced": "cpp"
        }
    
    def enroll_student_in_course(self, student_id: str, course_id: str) -> str:
        """

        Enroll a student in a course and start their chat session.

        

        Args:

            student_id: Unique student identifier

            course_id: Course identifier

            

        Returns:

            Session ID for the student's chat

        """
        language = self.course_languages.get(course_id, "python")
        
        # Create unique user ID combining student and course
        user_id = f"{student_id}_{course_id}"
        
        metadata = {
            "student_id": student_id,
            "course_id": course_id,
            "enrollment_date": time.strftime("%Y-%m-%d")
        }
        
        session_id = self.chat_manager.start_chat_for_user(user_id, language, metadata)
        
        # Send welcome message
        welcome_msg = f"Welcome to {course_id}! I'm your programming assistant. What would you like to learn about {language}?"
        self.chat_manager.send_user_message(user_id, welcome_msg)
        
        return session_id
    
    def student_ask_question(self, student_id: str, course_id: str, question: str) -> str:
        """

        Student asks a question in their course context.

        

        Args:

            student_id: Student identifier

            course_id: Course identifier

            question: Student's question

            

        Returns:

            AI assistant's response

        """
        user_id = f"{student_id}_{course_id}"
        
        try:
            response = self.chat_manager.send_user_message(user_id, question)
            return response['response']
        except Exception as e:
            return f"Sorry, I couldn't process your question right now: {e}"
    
    def get_student_progress(self, student_id: str, course_id: str) -> Dict:
        """

        Get student's chat history and progress.

        

        Args:

            student_id: Student identifier

            course_id: Course identifier

            

        Returns:

            Dict containing progress information

        """
        user_id = f"{student_id}_{course_id}"
        
        try:
            history = self.chat_manager.get_user_history(user_id)
            
            # Analyze progress
            questions_asked = len([msg for msg in history if msg['role'] == 'user'])
            topics_covered = set()
            
            # Simple topic extraction (in practice, you'd use NLP)
            for msg in history:
                if msg['role'] == 'user':
                    content = msg['content'].lower()
                    if 'loop' in content:
                        topics_covered.add('loops')
                    if 'function' in content:
                        topics_covered.add('functions')
                    if 'class' in content:
                        topics_covered.add('classes')
                    # Add more topic detection logic
            
            return {
                'student_id': student_id,
                'course_id': course_id,
                'questions_asked': questions_asked,
                'topics_covered': list(topics_covered),
                'last_activity': history[-1]['timestamp'] if history else None
            }
            
        except Exception as e:
            return {'error': str(e)}


# Example 2: Code Editor Plugin Integration
class CodeEditorPlugin:
    """

    Example integration with a code editor (like VS Code, Sublime, etc.).

    

    This shows how to provide contextual help based on the current file

    and programming language.

    """
    
    def __init__(self, chat_service_url: str = "http://localhost:5000"):
        self.client = ChatServiceClient(chat_service_url, "CodeEditor")
        self.user_sessions = {}  # user_id -> {language -> session_id}
    
    def get_or_create_session(self, user_id: str, language: str) -> str:
        """

        Get existing session for user+language or create new one.

        

        Args:

            user_id: User identifier

            language: Programming language

            

        Returns:

            Session ID

        """
        if user_id not in self.user_sessions:
            self.user_sessions[user_id] = {}
        
        if language not in self.user_sessions[user_id]:
            # Create new session for this language
            session_data = self.client.create_session(
                f"{user_id}_{language}", 
                language,
                {"context": "code_editor", "user_id": user_id}
            )
            self.user_sessions[user_id][language] = session_data['session_id']
        
        return self.user_sessions[user_id][language]
    
    def ask_about_code(self, user_id: str, language: str, code_snippet: str, 

                      question: str) -> str:
        """

        Ask a question about a specific code snippet.

        

        Args:

            user_id: User identifier

            language: Programming language

            code_snippet: The code in question

            question: User's question about the code

            

        Returns:

            AI assistant's response

        """
        session_id = self.get_or_create_session(user_id, language)
        
        # Format the question with code context
        formatted_question = f"""

I have this {language} code:



```{language}

{code_snippet}

```



{question}

"""
        
        try:
            response = self.client.send_message(session_id, formatted_question)
            return response['response']
        except Exception as e:
            return f"Error getting help: {e}"
    
    def explain_error(self, user_id: str, language: str, error_message: str, 

                     code_context: str = "") -> str:
        """

        Explain an error message in context.

        

        Args:

            user_id: User identifier

            language: Programming language

            error_message: The error message

            code_context: Optional code that caused the error

            

        Returns:

            Explanation of the error

        """
        session_id = self.get_or_create_session(user_id, language)
        
        question = f"I got this error in {language}:\n\n{error_message}"
        
        if code_context:
            question += f"\n\nThe code that caused it:\n```{language}\n{code_context}\n```"
        
        question += "\n\nCan you explain what's wrong and how to fix it?"
        
        try:
            response = self.client.send_message(session_id, question)
            return response['response']
        except Exception as e:
            return f"Error explaining error: {e}"


# Example 3: Chatbot for Website Integration
class WebsiteChatbot:
    """

    Example integration for a website chatbot.

    

    This shows how to handle anonymous users and session persistence

    across page reloads.

    """
    
    def __init__(self, chat_service_url: str = "http://localhost:5000"):
        self.client = ChatServiceClient(chat_service_url, "WebsiteChatbot")
        self.anonymous_sessions = {}  # browser_id -> session_id
    
    def start_anonymous_chat(self, browser_id: str, preferred_language: str = "python") -> Dict:
        """

        Start a chat session for an anonymous website visitor.

        

        Args:

            browser_id: Unique browser/session identifier

            preferred_language: User's preferred programming language

            

        Returns:

            Dict with session info and welcome message

        """
        # Create session with anonymous user ID
        user_id = f"anonymous_{browser_id}"
        
        metadata = {
            "session_type": "anonymous",
            "browser_id": browser_id,
            "start_time": time.strftime("%Y-%m-%d %H:%M:%S")
        }
        
        session_data = self.client.create_session(user_id, preferred_language, metadata)
        session_id = session_data['session_id']
        
        # Store mapping
        self.anonymous_sessions[browser_id] = session_id
        
        # Send welcome message
        welcome_response = self.client.send_message(
            session_id, 
            f"Hello! I'm a programming assistant. I can help you with {preferred_language} and other programming languages. What would you like to learn?"
        )
        
        return {
            'session_id': session_id,
            'welcome_message': welcome_response['response'],
            'language': preferred_language
        }
    
    def continue_anonymous_chat(self, browser_id: str, message: str) -> Dict:
        """

        Continue an existing anonymous chat session.

        

        Args:

            browser_id: Browser identifier

            message: User's message

            

        Returns:

            Dict with response and session info

        """
        if browser_id not in self.anonymous_sessions:
            # Session expired or doesn't exist, start new one
            return self.start_anonymous_chat(browser_id)
        
        session_id = self.anonymous_sessions[browser_id]
        
        try:
            response = self.client.send_message(session_id, message)
            return {
                'response': response['response'],
                'session_id': session_id,
                'message_id': response.get('message_id')
            }
        except Exception as e:
            # Session might have expired, start new one
            return self.start_anonymous_chat(browser_id)
    
    def get_chat_widget_data(self, browser_id: str) -> Dict:
        """

        Get data needed for the chat widget on the website.

        

        Args:

            browser_id: Browser identifier

            

        Returns:

            Dict with chat widget configuration

        """
        has_active_session = browser_id in self.anonymous_sessions
        
        return {
            'has_active_session': has_active_session,
            'supported_languages': ['python', 'javascript', 'java', 'cpp', 'csharp'],
            'welcome_message': "Hi! I'm here to help you with programming questions.",
            'placeholder_text': "Ask me anything about programming...",
            'session_id': self.anonymous_sessions.get(browser_id)
        }


# Example 4: Mobile App Integration
class MobileAppIntegration:
    """

    Example integration for a mobile learning app.

    

    This shows how to handle user authentication and offline scenarios.

    """
    
    def __init__(self, chat_service_url: str = "http://localhost:5000"):
        self.chat_manager = MultiUserChatManager(chat_service_url, "MobileLearningApp")
        self.offline_messages = {}  # user_id -> List[messages]
    
    def login_user(self, user_id: str, user_profile: Dict) -> str:
        """

        Handle user login and restore their chat session.

        

        Args:

            user_id: User identifier

            user_profile: User profile information

            

        Returns:

            Session ID

        """
        # Determine preferred language from profile
        preferred_language = user_profile.get('preferred_language', 'python')
        
        metadata = {
            'user_profile': user_profile,
            'platform': 'mobile',
            'login_time': time.strftime("%Y-%m-%d %H:%M:%S")
        }
        
        session_id = self.chat_manager.start_chat_for_user(user_id, preferred_language, metadata)
        
        # Process any offline messages
        if user_id in self.offline_messages:
            for message in self.offline_messages[user_id]:
                try:
                    self.chat_manager.send_user_message(user_id, message)
                except Exception as e:
                    print(f"Failed to send offline message: {e}")
            
            # Clear offline messages
            del self.offline_messages[user_id]
        
        return session_id
    
    def send_message_with_offline_support(self, user_id: str, message: str) -> Dict:
        """

        Send message with offline support.

        

        Args:

            user_id: User identifier

            message: User's message

            

        Returns:

            Response dict or offline confirmation

        """
        try:
            # Try to send message
            response = self.chat_manager.send_user_message(user_id, message)
            return {
                'status': 'sent',
                'response': response['response'],
                'timestamp': response.get('timestamp')
            }
        except Exception as e:
            # Store message for later (offline mode)
            if user_id not in self.offline_messages:
                self.offline_messages[user_id] = []
            
            self.offline_messages[user_id].append(message)
            
            return {
                'status': 'offline',
                'message': 'Message saved. Will be sent when connection is restored.',
                'queued_messages': len(self.offline_messages[user_id])
            }
    
    def sync_offline_messages(self, user_id: str) -> Dict:
        """

        Sync offline messages when connection is restored.

        

        Args:

            user_id: User identifier

            

        Returns:

            Sync status

        """
        if user_id not in self.offline_messages:
            return {'status': 'no_messages', 'synced': 0}
        
        messages = self.offline_messages[user_id]
        synced = 0
        failed = 0
        
        for message in messages:
            try:
                self.chat_manager.send_user_message(user_id, message)
                synced += 1
            except Exception:
                failed += 1
        
        # Clear successfully synced messages
        if failed == 0:
            del self.offline_messages[user_id]
        else:
            self.offline_messages[user_id] = self.offline_messages[user_id][-failed:]
        
        return {
            'status': 'synced',
            'synced': synced,
            'failed': failed,
            'remaining': len(self.offline_messages.get(user_id, []))
        }


if __name__ == "__main__":
    print("🧪 Testing Integration Examples")
    
    # Test Learning Platform Integration
    print("\n1. Testing Learning Platform Integration...")
    lms = LearningPlatformIntegration()
    
    try:
        # Enroll student
        session_id = lms.enroll_student_in_course("student123", "python-101")
        print(f"✅ Student enrolled, session: {session_id}")
        
        # Student asks question
        response = lms.student_ask_question("student123", "python-101", "How do I create a list?")
        print(f"✅ Response: {response[:100]}...")
        
        # Get progress
        progress = lms.get_student_progress("student123", "python-101")
        print(f"✅ Progress: {progress}")
        
    except Exception as e:
        print(f"❌ LMS test failed: {e}")
    
    # Test Code Editor Plugin
    print("\n2. Testing Code Editor Plugin...")
    editor = CodeEditorPlugin()
    
    try:
        code = "def hello():\n    print('Hello World')"
        response = editor.ask_about_code("dev123", "python", code, "How can I improve this function?")
        print(f"✅ Code help: {response[:100]}...")
        
        error_help = editor.explain_error("dev123", "python", "NameError: name 'x' is not defined")
        print(f"✅ Error help: {error_help[:100]}...")
        
    except Exception as e:
        print(f"❌ Editor test failed: {e}")
    
    print("\n✅ Integration examples completed!")