File size: 48,309 Bytes
31ac6a0
89144ca
e272769
3c1c8e8
89144ca
 
 
 
 
7b56738
31ac6a0
ed2729e
64b4650
ed2729e
e272769
a46cfbe
f9be5c5
a46cfbe
7b56738
89144ca
a46cfbe
89144ca
a46cfbe
 
7b56738
a46cfbe
 
 
7b56738
89144ca
 
a46cfbe
e272769
 
 
 
 
89144ca
 
e272769
7b56738
 
e272769
 
 
 
 
89144ca
 
e272769
7b56738
 
89144ca
 
 
 
 
 
 
e272769
 
 
89144ca
a46cfbe
 
 
 
 
 
7b56738
e272769
 
 
 
7b56738
 
e272769
 
a46cfbe
7b56738
a46cfbe
 
 
e272769
 
 
 
7b56738
 
e272769
7b56738
 
 
 
 
a46cfbe
 
7b56738
 
 
 
 
 
 
 
a46cfbe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e272769
89144ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e272769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89144ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a46cfbe
 
e272769
ed2729e
bc34aee
89144ca
 
ed2729e
 
bc34aee
 
 
f9be5c5
bc34aee
 
f9be5c5
89144ca
 
bc34aee
 
 
 
f9be5c5
bc34aee
 
f9be5c5
89144ca
 
bc34aee
 
 
 
f9be5c5
bc34aee
 
f9be5c5
89144ca
 
bc34aee
ed2729e
bc34aee
f9be5c5
 
89144ca
ed2729e
bc34aee
 
ed2729e
bc34aee
ed2729e
f9be5c5
ed2729e
 
 
 
 
 
 
f9be5c5
89144ca
 
ed2729e
f9be5c5
31ac6a0
bc34aee
f16e071
a46cfbe
f9be5c5
ed2729e
c0bc8cc
f9be5c5
 
 
 
 
89144ca
 
f9be5c5
 
89144ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64b4650
a46cfbe
 
 
 
bc34aee
89144ca
 
ed2729e
89144ca
 
 
 
f9be5c5
31ac6a0
89144ca
 
 
 
 
31ac6a0
64b4650
bc34aee
31ac6a0
a46cfbe
 
ed2729e
 
31ac6a0
ed2729e
31ac6a0
ed2729e
f16e071
bc34aee
f16e071
ed2729e
 
f16e071
ed2729e
a46cfbe
f9be5c5
a46cfbe
89144ca
f9be5c5
a46cfbe
 
e272769
a46cfbe
 
f9be5c5
ed2729e
 
f9be5c5
 
f16e071
bc34aee
f9be5c5
 
 
 
 
 
db985c5
f16e071
ed2729e
 
 
 
 
db985c5
 
f9be5c5
db985c5
 
 
f9be5c5
db985c5
 
 
 
f9be5c5
db985c5
f9be5c5
 
db985c5
 
a46cfbe
db985c5
e272769
 
a46cfbe
 
 
 
 
db985c5
a46cfbe
db985c5
 
e272769
a46cfbe
e272769
89144ca
db985c5
 
e272769
f9be5c5
 
e272769
 
f9be5c5
 
 
 
 
 
 
db985c5
f9be5c5
 
db985c5
f9be5c5
db985c5
f9be5c5
 
 
 
 
a46cfbe
f9be5c5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89144ca
f9be5c5
 
db985c5
 
 
f9be5c5
db985c5
 
 
e272769
89144ca
e272769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89144ca
e272769
89144ca
e272769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89144ca
e272769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b56738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89144ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a46cfbe
 
 
89144ca
7b56738
a46cfbe
 
7b56738
 
 
a46cfbe
7b56738
a46cfbe
 
e272769
 
7b56738
 
 
 
 
a46cfbe
7b56738
 
a46cfbe
 
e272769
 
a46cfbe
7b56738
 
 
 
 
a46cfbe
 
 
 
 
 
e272769
 
 
a46cfbe
7b56738
 
 
 
a46cfbe
 
 
 
 
 
7b56738
a46cfbe
7b56738
a46cfbe
7b56738
 
a46cfbe
 
 
e272769
 
a46cfbe
7b56738
 
 
 
a46cfbe
 
7b56738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e272769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a46cfbe
e272769
 
 
 
a46cfbe
 
89144ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b56738
e272769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a46cfbe
db985c5
f9be5c5
db985c5
 
f9be5c5
 
 
7b56738
 
 
 
 
 
 
 
 
 
 
f9be5c5
7b56738
f9be5c5
 
 
 
 
7b56738
f9be5c5
 
 
 
7b56738
 
 
 
 
f9be5c5
 
 
 
7b56738
f9be5c5
 
 
 
 
7b56738
 
 
 
f9be5c5
89144ca
 
 
 
 
 
 
f9be5c5
 
a46cfbe
f9be5c5
 
7b56738
 
 
 
db985c5
a46cfbe
 
e272769
f9be5c5
e272769
 
 
 
a46cfbe
 
 
 
 
 
 
 
 
 
 
7b56738
 
 
 
 
 
a46cfbe
e272769
 
a46cfbe
 
 
 
e272769
a46cfbe
 
e272769
a46cfbe
e272769
 
 
a46cfbe
 
 
 
 
89144ca
a46cfbe
 
 
e272769
 
 
a46cfbe
e272769
 
 
a46cfbe
 
 
 
 
 
 
 
 
e272769
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a46cfbe
e272769
a46cfbe
e272769
 
a46cfbe
 
 
 
e272769
a46cfbe
 
 
 
 
 
 
 
 
7b56738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89144ca
 
a46cfbe
 
89144ca
e272769
 
a46cfbe
 
 
89144ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a46cfbe
e272769
a46cfbe
 
89144ca
a46cfbe
89144ca
a46cfbe
 
89144ca
a46cfbe
89144ca
 
 
 
 
 
a46cfbe
89144ca
 
 
 
 
 
 
 
 
 
 
 
 
 
a46cfbe
 
7b56738
db985c5
a46cfbe
 
 
 
 
e272769
7b56738
a46cfbe
 
db985c5
a46cfbe
 
 
 
 
f9be5c5
7b56738
 
 
 
 
 
f9be5c5
db985c5
 
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
"""
ThutoAI - Complete School Assistant with Teacher Assignments & Analytics Dashboard
Meaning: "Thuto" = Learning/Education (Setswana β€” used for branding only)

βœ… Teacher Assignment Posting β€” Assign work to class groups
βœ… πŸ“Š Analytics Dashboard β€” Track student engagement, assignments, groups
βœ… πŸŒ™ Dark Mode + πŸ–ΌοΈ Profile Pictures
βœ… πŸŽ™οΈ Voice Input + πŸ“… Assignment Tracker + πŸ‘₯ Class Groups
βœ… All deprecation warnings fixed (Gradio 4.0+ compatible)
βœ… Fully commented
"""

import os
import gradio as gr
from datetime import datetime, timedelta
from typing import List, Dict, Optional
import time
import json
import base64
from collections import Counter

# ==================== STUDENT SERVICE ====================

class StudentService:
    """Manages student accounts, chat history, files, assignments, groups, and profile pictures."""

    def __init__(self):
        self.students = {
            "student1": {"password": "pass123", "name": "John Doe", "avatar": None},
            "student2": {"password": "pass456", "name": "Jane Smith", "avatar": None},
            "student3": {"password": "pass789", "name": "Alex Johnson", "avatar": None}
        }
        self.student_sessions = {
            "student1": {
                "chat_history": [],
                "files": [],
                "assignments": [
                    {"id": 1, "title": "Math Quiz", "due_date": "2025-04-25", "course": "MATH10A", "status": "pending", "assigned_by": "Mr. Smith"},
                    {"id": 2, "title": "Science Lab Report", "due_date": "2025-04-30", "course": "SCI11B", "status": "pending", "assigned_by": "Dr. Lee"}
                ],
                "groups": ["MATH10A", "SCI11B"],
                "dark_mode": False
            },
            "student2": {
                "chat_history": [],
                "files": [],
                "assignments": [
                    {"id": 3, "title": "History Essay", "due_date": "2025-04-22", "course": "HIST9A", "status": "overdue", "assigned_by": "Ms. Brown"},
                    {"id": 4, "title": "English Reading", "due_date": "2025-04-28", "course": "ENG10A", "status": "pending", "assigned_by": "Mr. White"}
                ],
                "groups": ["HIST9A", "ENG10A"],
                "dark_mode": True
            },
            "student3": {
                "chat_history": [],
                "files": [],
                "assignments": [],
                "groups": ["MATH10A", "ENG10A"],
                "dark_mode": False
            }
        }
        self.valid_groups = ["MATH10A", "MATH10B", "SCI11A", "SCI11B", "ENG10A", "ENG10B", "HIST9A", "HIST9B"]
        self.all_assignments = []  # Master list for analytics

    def register_student(self, username: str, password: str, name: str) -> str:
        if not username or not password or not name:
            return "⚠️ All fields required."
        if username in self.students:
            return "⚠️ Username already exists."
        self.students[username] = {"password": password, "name": name, "avatar": None}
        self.student_sessions[username] = {
            "chat_history": [],
            "files": [],
            "assignments": [],
            "groups": [],
            "dark_mode": False
        }
        return "βœ… Account created! Please log in."

    def authenticate_student(self, username: str, password: str) -> Optional[Dict]:
        student = self.students.get(username)
        if student and student["password"] == password:
            if username not in self.student_sessions:
                self.student_sessions[username] = {
                    "chat_history": [],
                    "files": [],
                    "assignments": [],
                    "groups": [],
                    "dark_mode": False
                }
            return {
                "name": student["name"],
                "avatar": student["avatar"],
                "dark_mode": self.student_sessions[username]["dark_mode"]
            }
        return None

    def update_dark_mode(self, username: str, is_dark: bool):
        if username in self.student_sessions:
            self.student_sessions[username]["dark_mode"] = is_dark

    def update_avatar(self, username: str, avatar_path: str):
        if username in self.students and avatar_path:
            self.students[username]["avatar"] = avatar_path

    def get_chat_history(self, username: str) -> List:
        return self.student_sessions.get(username, {}).get("chat_history", [])

    def add_to_chat_history(self, username: str, user_msg: str, bot_reply: str):
        if username in self.student_sessions:
            self.student_sessions[username]["chat_history"].append((user_msg, bot_reply))

    def get_files(self, username: str) -> List:
        return self.student_sessions.get(username, {}).get("files", [])

    def add_file(self, username: str, filename: str):
        if username in self.student_sessions:
            self.student_sessions[username]["files"].append({
                "name": filename,
                "uploaded_at": datetime.now().strftime("%Y-%m-%d %H:%M")
            })

    def get_assignments(self, username: str) -> List:
        """Get assignments for groups student has joined."""
        if username not in self.student_sessions:
            return []
        student_groups = set(self.student_sessions[username]["groups"])
        all_assignments = []
        for user_data in self.student_sessions.values():
            for assignment in user_data.get("assignments", []):
                if assignment["course"] in student_groups:
                    all_assignments.append(assignment)
        # Remove duplicates by ID
        seen = set()
        unique_assignments = []
        for assignment in all_assignments:
            if assignment["id"] not in seen:
                seen.add(assignment["id"])
                unique_assignments.append(assignment)
        return sorted(unique_assignments, key=lambda x: x["due_date"])

    def get_groups(self, username: str) -> List:
        return self.student_sessions.get(username, {}).get("groups", [])

    def join_group(self, username: str, group_code: str) -> str:
        if group_code.upper() not in self.valid_groups:
            return "❌ Invalid group code. Ask your teacher for the correct code."
        if username in self.student_sessions:
            if group_code.upper() not in self.student_sessions[username]["groups"]:
                self.student_sessions[username]["groups"].append(group_code.upper())
            return f"βœ… Joined group: {group_code.upper()}"
        return "❌ Login required."

    def leave_group(self, username: str, group_code: str) -> str:
        if username in self.student_sessions:
            if group_code.upper() in self.student_sessions[username]["groups"]:
                self.student_sessions[username]["groups"].remove(group_code.upper())
                return f"βœ… Left group: {group_code.upper()}"
        return "❌ Group not found or not joined."

    # Analytics methods
    def get_total_students(self) -> int:
        return len(self.students)

    def get_active_students(self) -> int:
        return len([s for s in self.student_sessions.keys() if len(self.student_sessions[s]["assignments"]) > 0])

    def get_total_assignments(self) -> int:
        total = 0
        for user_data in self.student_sessions.values():
            total += len(user_data.get("assignments", []))
        return total

    def get_completed_assignments(self) -> int:
        completed = 0
        for user_data in self.student_sessions.values():
            for assignment in user_data.get("assignments", []):
                if assignment["status"] == "completed":
                    completed += 1
        return completed

    def get_group_popularity(self) -> Dict:
        all_groups = []
        for user_data in self.student_sessions.values():
            all_groups.extend(user_data.get("groups", []))
        return dict(Counter(all_groups))

    def get_recent_activity(self) -> List:
        activity = []
        for username, data in self.student_sessions.items():
            if data["assignments"]:
                latest = max(data["assignments"], key=lambda x: x.get("assigned_date", "2025-01-01"))
                activity.append({
                    "student": self.students[username]["name"],
                    "last_assignment": latest["title"],
                    "date": latest.get("assigned_date", "Unknown")
                })
        return sorted(activity, key=lambda x: x["date"], reverse=True)[:5]


# Initialize student service
student_service = StudentService()

# ==================== SCHOOL SERVICE ====================

class SchoolService:
    """Handles announcements, AI context, and shared assignments."""

    def __init__(self):
        self.announcements = [
            {
                "id": 1,
                "title": "Math Final Exam",
                "content": "Covers chapters 1-5. Bring calculator and ruler.",
                "course": "Mathematics",
                "date": "2025-04-15",
                "priority": "high",
                "posted_by": "Mr. Smith",
                "views": 45
            },
            {
                "id": 2,
                "title": "Science Project Due",
                "content": "Submit your ecology report by Friday. Include bibliography.",
                "course": "Science",
                "date": "2025-04-12",
                "priority": "normal",
                "posted_by": "Dr. Lee",
                "views": 32
            },
            {
                "id": 3,
                "title": "Library Extended Hours",
                "content": "Open until 9 PM during exam week. Quiet study zones available.",
                "course": "General",
                "date": "2025-04-10",
                "priority": "low",
                "posted_by": "Librarian",
                "views": 67
            },
        ]
        self.courses = ["All", "Mathematics", "Science", "English", "History", "General"]
        self.total_announcements = len(self.announcements)
        self.total_files = 0
        self.assignment_id_counter = 5  # Start after existing assignments

    def get_announcements(self, course_filter: str = "All") -> List[Dict]:
        if course_filter == "All":
            return self.announcements
        return [a for a in self.announcements if a["course"] == course_filter]

    def add_announcement(self, title: str, content: str, course: str, priority: str, posted_by: str = "Admin"):
        new_id = max([a["id"] for a in self.announcements], default=0) + 1
        self.announcements.append({
            "id": new_id,
            "title": title,
            "content": content,
            "course": course,
            "date": datetime.now().strftime("%Y-%m-%d"),
            "priority": priority,
            "posted_by": posted_by,
            "views": 0
        })
        self.total_announcements += 1

    def get_school_context_for_ai(self) -> str:
        context = "Current School Announcements:\n"
        for ann in self.announcements[-5:]:
            context += f"- [{ann['course']}] {ann['title']}: {ann['content'][:80]}... (Priority: {ann['priority']})\n"
        return context

    def get_stats(self) -> Dict:
        return {
            "total_announcements": self.total_announcements,
            "total_files": self.total_files,
            "active_courses": len(set(a["course"] for a in self.announcements if a["course"] != "General")),
            "high_priority": len([a for a in self.announcements if a["priority"] == "high"]),
            "total_views": sum(a["views"] for a in self.announcements)
        }

    def create_assignment(self, title: str, description: str, due_date: str, course: str, assigned_by: str) -> int:
        """Create assignment for a specific class group."""
        assignment_id = self.assignment_id_counter
        self.assignment_id_counter += 1
        
        new_assignment = {
            "id": assignment_id,
            "title": title,
            "description": description,
            "due_date": due_date,
            "course": course,
            "assigned_by": assigned_by,
            "assigned_date": datetime.now().strftime("%Y-%m-%d"),
            "status": "pending"
        }
        
        # Assign to all students in this group
        for username, data in student_service.student_sessions.items():
            if course in data["groups"]:
                data["assignments"].append(new_assignment.copy())
        
        return assignment_id


school_service = SchoolService()

# ==================== ADMIN SERVICE ====================

class AdminService:
    """Handles teacher and admin authentication."""

    def __init__(self):
        self.teachers = {
            "[email protected]": {"password": "password123", "name": "Mr. Smith", "role": "teacher"},
            "[email protected]": {"password": "science123", "name": "Dr. Lee", "role": "teacher"},
            "[email protected]": {"password": "letmein", "name": "Admin", "role": "admin"}
        }

    def authenticate(self, username: str, password: str) -> Optional[Dict]:
        user = self.teachers.get(username)
        if user and user["password"] == password:
            return {"name": user["name"], "role": user["role"]}
        return None


admin_service = AdminService()

# ==================== OPENAI SETUP ====================

OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
USE_OPENAI = bool(OPENAI_API_KEY)

if USE_OPENAI:
    try:
        from openai import OpenAI
        client = OpenAI(api_key=OPENAI_API_KEY)
    except Exception as e:
        print(f"⚠️ OpenAI error: {e}")
        USE_OPENAI = False
else:
    print("⚠️ OPENAI_API_KEY not set. Using mock responses.")

# ==================== AI CHAT FUNCTION ====================

def ai_chat(message: str, history: List, username: str = "guest") -> tuple:
    """Generate AI response with loading state and save to history."""
    if not message.strip():
        return history, ""

    thinking_msg = "πŸ€” ThutoAI is thinking..."
    history.append((message, thinking_msg))
    yield history, ""

    if USE_OPENAI:
        try:
            system_prompt = f"""You are ThutoAI, a friendly and knowledgeable AI assistant for students.
Context from school:
{school_service.get_school_context_for_ai()}

Guidelines:
- Be encouraging, clear, and concise.
- Use emojis sparingly to keep it fun πŸ˜ŠπŸ“šπŸŽ―
- If asked about deadlines or exams, refer to context.
- Offer study tips if appropriate.
- Never invent facts β€” say 'I don't know' if unsure."""

            response = client.chat.completions.create(
                model="gpt-3.5-turbo",
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": message}
                ],
                temperature=0.7,
                max_tokens=500
            )

            reply = response.choices[0].message.content.strip()

            keywords = ["exam", "test", "due", "assignment", "deadline", "when", "what", "grade", "score"]
            if any(kw in message.lower() for kw in keywords):
                matches = school_service.get_announcements()
                relevant = [a for a in matches if any(kw in a["title"].lower() or kw in a["content"].lower() for kw in keywords)]
                if relevant:
                    reply += "\n\nπŸ“Œ **Quick Info from School:**"
                    for ann in relevant[:2]:
                        emoji = "🚨" if ann["priority"] == "high" else "πŸ“Œ" if ann["priority"] == "normal" else "ℹ️"
                        reply += f"\n{emoji} **{ann['title']}** ({ann['course']})\n   β†’ {ann['content'][:70]}..."

        except Exception as e:
            reply = f"⚠️ Sorry, I had a glitch: {str(e)}"
    else:
        time.sleep(1.5)
        reply = f"πŸ‘‹ Hi! I'm ThutoAI. You asked: '{message}'.\nπŸ’‘ *Pro tip: Add your OpenAI API key in HF Secrets for smarter answers!*"

    history[-1] = (message, reply)

    if username != "guest":
        student_service.add_to_chat_history(username, message, reply)

    yield history, ""


# ==================== UI RENDERING HELPERS ====================

def render_announcements(course: str) -> str:
    """Render announcements with modern cards."""
    announcements = school_service.get_announcements(course)
    if not announcements:
        return """
        <div style='text-align: center; padding: 40px; color: #6c757d;'>
            <div style='font-size: 4em; margin-bottom: 16px;'>πŸ“­</div>
            <h3>No announcements for this course.</h3>
            <p>Check back later or select "All" to see everything.</p>
        </div>
        """

    html = "<div style='display: grid; gap: 16px;'>"
    priority_icons = {"high": "🚨", "normal": "πŸ“Œ", "low": "ℹ️"}
    priority_colors = {"high": "#dc3545", "normal": "#ffc107", "low": "#6c757d"}

    for ann in announcements:
        icon = priority_icons.get(ann["priority"], "πŸ“Œ")
        color = priority_colors.get(ann["priority"], "#6c757d")
        html += f"""
        <div style='
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            border-left: 4px solid {color};
            transition: transform 0.2s, box-shadow 0.2s;
        '>
            <div style='display: flex; align-items: flex-start; gap: 12px;'>
                <div style='font-size: 1.5em;'>{icon}</div>
                <div style='flex: 1;'>
                    <div style='display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px;'>
                        <h3 style='margin: 0; color: #212529;'>{ann['title']}</h3>
                        <span style='
                            background: {color};
                            color: white;
                            padding: 4px 10px;
                            border-radius: 20px;
                            font-size: 0.8em;
                            font-weight: bold;
                        '>{ann['priority'].upper()}</span>
                    </div>
                    <p style='margin: 8px 0; color: #495057; line-height: 1.5;'>{ann['content']}</p>
                    <div style='display: flex; justify-content: space-between; font-size: 0.85em; color: #6c757d; margin-top: 12px;'>
                        <span>πŸ“š {ann['course']}</span>
                        <span>πŸ“… {ann['date']}</span>
                        <span>πŸ‘¨β€πŸ« {ann['posted_by']}</span>
                        <span>πŸ‘οΈ {ann['views']} views</span>
                    </div>
                </div>
            </div>
        </div>
        """
    html += "</div>"
    return html


def render_assignments(assignments: List[Dict]) -> str:
    """Render assignments in a clean, prioritized list."""
    if not assignments:
        return """
        <div style='text-align: center; padding: 40px; color: #6c757d;'>
            <div style='font-size: 4em; margin-bottom: 16px;'>πŸ“…</div>
            <h3>No upcoming assignments.</h3>
            <p>Ask your teacher or join a class group to see assignments.</p>
        </div>
        """

    html = "<div style='display: grid; gap: 16px;'>"
    today = datetime.today().date()

    for task in assignments:
        due_date = datetime.strptime(task["due_date"], "%Y-%m-%d").date()
        days_left = (due_date - today).days
        is_overdue = days_left < 0
        is_today = days_left == 0

        if is_overdue:
            badge = "🚨 OVERDUE"
            color = "#dc3545"
        elif is_today:
            badge = "🎯 TODAY"
            color = "#fd7e14"
        elif days_left <= 2:
            badge = f"⚠️ Due in {days_left} day{'s' if days_left != 1 else ''}"
            color = "#ffc107"
        else:
            badge = f"βœ… Due in {days_left} days"
            color = "#28a745"

        html += f"""
        <div style='
            background: white;
            border-radius: 12px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.08);
            border-left: 4px solid {color};
            transition: transform 0.2s;
        '>
            <div style='display: flex; justify-content: space-between; align-items: flex-start;'>
                <div>
                    <h3 style='margin: 0 0 8px 0; color: #212529;'>{task['title']}</h3>
                    <div style='color: #6c757d; margin-bottom: 8px;'>πŸ“š {task['course']} Β· πŸ‘©β€πŸ« {task['assigned_by']}</div>
                    <div style='color: #495057;'>πŸ“… Due: {task['due_date']}</div>
                    <div style='color: #6c757d; font-size: 0.9em;'>{task.get('description', '')}</div>
                </div>
                <span style='
                    background: {color};
                    color: white;
                    padding: 6px 12px;
                    border-radius: 20px;
                    font-weight: bold;
                    font-size: 0.85em;
                    align-self: flex-start;
                '>{badge}</span>
            </div>
        </div>
        """

    html += "</div>"
    return html


def render_groups(groups: List[str]) -> str:
    """Render joined class groups."""
    if not groups:
        return """
        <div style='text-align: center; padding: 40px; color: #6c757d;'>
            <div style='font-size: 4em; margin-bottom: 16px;'>πŸ‘₯</div>
            <h3>You haven't joined any class groups yet.</h3>
            <p>Ask your teacher for a group code to join your class.</p>
        </div>
        """

    html = "<div style='display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 16px;'>"
    for group in groups:
        html += f"""
        <div style='
            background: #e3f2fd;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
            border: 2px solid #2196f3;
        '>
            <div style='font-size: 1.5em; margin-bottom: 8px;'>πŸŽ’</div>
            <h3 style='margin: 0; color: #1976d2;'>{group}</h3>
            <p style='margin: 8px 0 0 0; color: #555; font-size: 0.9em;'>Class Group</p>
        </div>
        """
    html += "</div>"
    return html


def get_avatar_html(avatar_path: Optional[str], name: str) -> str:
    """Generate HTML for avatar display."""
    if avatar_path:
        try:
            with open(avatar_path, "rb") as f:
                img_data = base64.b64encode(f.read()).decode()
            img_html = f'<img src="data:image/png;base64,{img_data}" style="width: 60px; height: 60px; border-radius: 50%; object-fit: cover; border: 2px solid #6e8efb;">'
        except:
            img_html = f'<div style="width: 60px; height: 60px; border-radius: 50%; background: #6e8efb; color: white; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 1.2em; border: 2px solid #6e8efb;">{name[0].upper()}</div>'
    else:
        img_html = f'<div style="width: 60px; height: 60px; border-radius: 50%; background: #6e8efb; color: white; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 1.2em; border: 2px solid #6e8efb;">{name[0].upper()}</div>'

    return img_html


def render_analytics() -> str:
    """Render analytics dashboard for admins."""
    total_students = student_service.get_total_students()
    active_students = student_service.get_active_students()
    total_assignments = student_service.get_total_assignments()
    completed_assignments = student_service.get_completed_assignments()
    group_popularity = student_service.get_group_popularity()
    recent_activity = student_service.get_recent_activity()
    school_stats = school_service.get_stats()

    completion_rate = (completed_assignments / total_assignments * 100) if total_assignments > 0 else 0

    html = f"""
    <div style='display: grid; grid-template-columns: repeat(2, 1fr); gap: 24px; margin-bottom: 32px;'>
        <div style='background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.08);'>
            <h3 style='color: #212529; margin: 0 0 16px 0;'>πŸ‘₯ Student Engagement</h3>
            <div style='display: grid; grid-template-columns: 1fr 1fr; gap: 16px;'>
                <div style='text-align: center; padding: 16px; background: #e3f2fd; border-radius: 8px;'>
                    <div style='font-size: 2em; color: #1976d2;'>{total_students}</div>
                    <div>Total Students</div>
                </div>
                <div style='text-align: center; padding: 16px; background: #e8f5e8; border-radius: 8px;'>
                    <div style='font-size: 2em; color: #2e7d32;'>{active_students}</div>
                    <div>Active Students</div>
                </div>
            </div>
        </div>
        
        <div style='background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.08);'>
            <h3 style='color: #212529; margin: 0 0 16px 0;'>πŸ“Š Assignment Stats</h3>
            <div style='display: grid; grid-template-columns: 1fr 1fr; gap: 16px;'>
                <div style='text-align: center; padding: 16px; background: #fff3e0; border-radius: 8px;'>
                    <div style='font-size: 2em; color: #ef6c00;'>{total_assignments}</div>
                    <div>Total Assignments</div>
                </div>
                <div style='text-align: center; padding: 16px; background: #f3e5f5; border-radius: 8px;'>
                    <div style='font-size: 2em; color: #7b1fa2;'>{completion_rate:.1f}%</div>
                    <div>Completion Rate</div>
                </div>
            </div>
        </div>
    </div>

    <div style='display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin-bottom: 32px;'>
        <div style='background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.08);'>
            <h3 style='color: #212529; margin: 0 0 16px 0;'>πŸ“ˆ Popular Class Groups</h3>
            <div style='display: grid; gap: 12px;'>
    """

    sorted_groups = sorted(group_popularity.items(), key=lambda x: x[1], reverse=True)
    for group, count in sorted_groups[:5]:
        percentage = (count / total_students * 100) if total_students > 0 else 0
        html += f"""
                <div style='display: flex; align-items: center; gap: 12px;'>
                    <div style='width: 100%; background: #e0e0e0; height: 8px; border-radius: 4px;'>
                        <div style='width: {percentage}%; background: #6e8efb; height: 100%; border-radius: 4px;'></div>
                    </div>
                    <div style='min-width: 80px;'>{group}</div>
                    <div style='color: #6c757d;'>{count} students</div>
                </div>
        """

    html += """
            </div>
        </div>

        <div style='background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.08);'>
            <h3 style='color: #212529; margin: 0 0 16px 0;'>πŸ“’ Announcement Stats</h3>
            <div style='display: grid; gap: 12px;'>
    """

    for ann in school_service.announcements[:5]:
        views = ann.get("views", 0)
        max_views = max(a.get("views", 0) for a in school_service.announcements) if school_service.announcements else 1
        width_percent = (views / max_views * 100) if max_views > 0 else 0
        html += f"""
                <div style='display: flex; align-items: center; gap: 12px;'>
                    <div style='width: 100%; background: #e0e0e0; height: 8px; border-radius: 4px;'>
                        <div style='width: {width_percent}%; background: #ff7043; height: 100%; border-radius: 4px;'></div>
                    </div>
                    <div style='min-width: 120px; font-size: 0.9em;'>{ann['title'][:20]}...</div>
                    <div style='color: #6c757d;'>{views} views</div>
                </div>
        """

    html += """
            </div>
        </div>
    </div>

    <div style='background: white; padding: 20px; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.08);'>
        <h3 style='color: #212529; margin: 0 0 16px 0;'>⏱️ Recent Activity</h3>
        <div style='display: grid; gap: 12px;'>
    """

    for activity in recent_activity:
        html += f"""
            <div style='padding: 12px; background: #f8f9fa; border-radius: 8px; display: flex; justify-content: space-between; align-items: center;'>
                <div>
                    <strong>{activity['student']}</strong> received assignment: <em>{activity['last_assignment']}</em>
                </div>
                <div style='color: #6c757d; font-size: 0.9em;'>{activity['date']}</div>
            </div>
        """

    html += """
        </div>
    </div>
    """

    return html

# ==================== STATE MANAGEMENT ====================

CURRENT_USER = "guest"
CURRENT_TEACHER = None
DARK_MODE = False

def login_student(username: str, password: str) -> tuple:
    global CURRENT_USER, DARK_MODE
    student_data = student_service.authenticate_student(username, password)
    if student_data:
        CURRENT_USER = username
        DARK_MODE = student_data["dark_mode"]
        chat_history = student_service.get_chat_history(username)
        files = student_service.get_files(username)
        assignments = student_service.get_assignments(username)
        groups = student_service.get_groups(username)
        avatar_html = get_avatar_html(student_data["avatar"], student_data["name"])
        welcome_msg = f"Welcome back, {student_data['name']}!"

        css_class = "dark-mode" if DARK_MODE else ""

        return (
            gr.update(visible=False),
            gr.update(visible=True),
            chat_history,
            files,
            render_assignments(assignments),
            render_groups(groups),
            welcome_msg,
            gr.update(value=student_data["name"], visible=True),
            gr.update(visible=True),
            gr.update(value=avatar_html),
            gr.update(value="πŸŒ™ Light Mode" if DARK_MODE else "β˜€οΈ Dark Mode"),
            css_class
        )
    return (
        gr.update(visible=True),
        gr.update(visible=False),
        [],
        [],
        "",
        "",
        "❌ Invalid username or password",
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(),
        gr.update(),
        ""
    )

def register_student(username: str, password: str, name: str) -> str:
    return student_service.register_student(username, password, name)

def logout_student() -> tuple:
    global CURRENT_USER, DARK_MODE
    CURRENT_USER = "guest"
    DARK_MODE = False
    return (
        gr.update(visible=True),
        gr.update(visible=False),
        [],
        [],
        "",
        "",
        "",
        gr.update(visible=False),
        gr.update(visible=False),
        gr.update(),
        gr.update(value="β˜€οΈ Dark Mode"),
        ""
    )

def toggle_dark_mode() -> tuple:
    global DARK_MODE, CURRENT_USER
    DARK_MODE = not DARK_MODE
    if CURRENT_USER != "guest":
        student_service.update_dark_mode(CURRENT_USER, DARK_MODE)
    btn_text = "πŸŒ™ Light Mode" if DARK_MODE else "β˜€οΈ Dark Mode"
    css_class = "dark-mode" if DARK_MODE else ""
    return btn_text, css_class

def upload_avatar(file) -> str:
    if not file:
        return "❌ No file selected"
    if CURRENT_USER == "guest":
        return "❌ Please log in first"
    student_service.update_avatar(CURRENT_USER, file.name)
    return f"βœ… Avatar updated!"

def join_group(group_code: str) -> tuple:
    if CURRENT_USER == "guest":
        return "❌ Please log in first.", ""
    result = student_service.join_group(CURRENT_USER, group_code)
    groups = student_service.get_groups(CURRENT_USER)
    return result, render_groups(groups)

def leave_group(group_code: str) -> tuple:
    if CURRENT_USER == "guest":
        return "❌ Please log in first.", ""
    result = student_service.leave_group(CURRENT_USER, group_code)
    groups = student_service.get_groups(CURRENT_USER)
    return result, render_groups(groups)

def upload_file_for_student(file) -> str:
    if not file:
        return "❌ No file selected"
    result = f"βœ… Uploaded: {file.name}"
    if CURRENT_USER != "guest":
        student_service.add_file(CURRENT_USER, file.name)
    return result

# ==================== TEACHER FUNCTIONS ====================

def teacher_login(username: str, password: str) -> tuple:
    global CURRENT_TEACHER
    teacher_data = admin_service.authenticate(username, password)
    if teacher_data and teacher_data["role"] == "teacher":
        CURRENT_TEACHER = teacher_data
        return (
            gr.update(visible=False),
            gr.update(visible=True),
            f"βœ… Welcome, {teacher_data['name']}!",
            gr.update(visible=True)
        )
    elif teacher_data and teacher_data["role"] == "admin":
        CURRENT_TEACHER = teacher_data
        return (
            gr.update(visible=False),
            gr.update(visible=True),
            f"βœ… Welcome, Admin {teacher_data['name']}!",
            gr.update(visible=True)
        )
    return (
        gr.update(visible=True),
        gr.update(visible=False),
        "❌ Invalid credentials or not a teacher account",
        gr.update(visible=False)
    )

def teacher_logout():
    global CURRENT_TEACHER
    CURRENT_TEACHER = None
    return (
        gr.update(visible=True),
        gr.update(visible=False),
        "",
        gr.update(visible=False)
    )

def create_assignment(title: str, description: str, due_date: str, course: str) -> str:
    if not CURRENT_TEACHER:
        return "πŸ”’ Please log in as teacher first."
    if not title or not due_date or not course:
        return "⚠️ Title, due date, and course are required."
    if course not in student_service.valid_groups:
        return "⚠️ Invalid course/group. Choose from available groups."

    assignment_id = school_service.create_assignment(
        title=title,
        description=description,
        due_date=due_date,
        course=course,
        assigned_by=CURRENT_TEACHER["name"]
    )

    # Count how many students received this assignment
    recipients = 0
    for data in student_service.student_sessions.values():
        if course in data["groups"]:
            recipients += 1

    return f"βœ… Assignment created! ID: {assignment_id}. Sent to {recipients} students in {course}."

# ==================== VOICE INPUT ====================

VOICE_JS = """
async function startVoiceInput() {
    if (!('webkitSpeechRecognition' in window) && !('SpeechRecognition' in window)) {
        alert('πŸŽ™οΈ Voice input is not supported in your browser. Try Chrome or Edge.');
        return '';
    }

    const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
    recognition.lang = 'en-US';
    recognition.interimResults = false;
    recognition.maxAlternatives = 1;

    return new Promise((resolve) => {
        recognition.start();
        recognition.onresult = (event) => {
            const transcript = event.results[0][0].transcript;
            resolve(transcript);
        };
        recognition.onerror = (event) => {
            alert('πŸŽ™οΈ Error: ' + event.error);
            resolve('');
        };
    });
}
"""

def voice_input_handler() -> str:
    return ""

# ==================== CUSTOM CSS ====================

CUSTOM_CSS = """
.gradio-container {
    font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
    max-width: 1200px;
    margin: 0 auto;
    padding: 16px;
    transition: background-color 0.3s, color 0.3s;
}

.dark-mode {
    --background-fill-primary: #1e1e1e !important;
    --background-fill-secondary: #2d2d2d !important;
    --text-color: #f0f0f0 !important;
    --button-primary-background-fill: #5a5a5a !important;
    --button-secondary-background-fill: #3a3a3a !important;
    --input-background-fill: #2d2d2d !important;
    --input-border-color: #444 !important;
}

.primary {
    background: linear-gradient(135deg, #6e8efb, #a777e3) !important;
    border: none !important;
    color: white !important;
}

.chatbot-container {
    background: #f8f9fa !important;
    border-radius: 16px !important;
}

.dark-mode .chatbot-container {
    background: #2d2d2d !important;
}

.user, .bot {
    border-radius: 18px !important;
    padding: 12px 16px !important;
}

.file-upload {
    border: 2px dashed #6e8efb !important;
    border-radius: 12px !important;
    background: #f8f9ff !important;
}

.dark-mode .file-upload {
    background: #2a2a2a !important;
    border-color: #5a5a5a !important;
}

.analytics-card {
    background: white;
    padding: 20px;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
"""

# ==================== BUILD UI ====================

with gr.Blocks(css=CUSTOM_CSS, theme=gr.themes.Soft(primary_hue="indigo")) as demo:
    # Header with dark mode toggle
    with gr.Row():
        gr.Markdown("# πŸŽ“ ThutoAI β€” Your AI School Assistant")
        dark_mode_btn = gr.Button("β˜€οΈ Dark Mode", variant="secondary")

    # ========= STUDENT LOGIN/REGISTER =========
    with gr.Group() as login_group:
        gr.Markdown("### πŸ” Student Login")
        with gr.Row():
            login_username = gr.Textbox(label="Username", scale=3)
            login_password = gr.Textbox(label="Password", type="password", scale=3)
        login_btn = gr.Button("πŸ”“ Login", variant="primary")
        register_btn = gr.Button("πŸ“ Register", variant="secondary")
        login_status = gr.Textbox(label="Status", interactive=False)

        with gr.Accordion("πŸ“ Register New Account", open=False):
            reg_username = gr.Textbox(label="Username")
            reg_password = gr.Textbox(label="Password", type="password")
            reg_name = gr.Textbox(label="Full Name")
            reg_btn = gr.Button("Create Account")
            reg_status = gr.Textbox(label="Registration Status")

    # ========= MAIN APP (hidden until login) =========
    with gr.Group(visible=False) as main_app:
        # Profile header
        with gr.Row():
            avatar_display = gr.HTML()
            user_display = gr.Textbox(label="Logged in as", interactive=False, visible=True)
            logout_btn = gr.Button("⬅️ Logout", variant="secondary")

        with gr.Tabs():
            with gr.Tab("πŸ“’ Announcements"):
                gr.Markdown("### Filter by Course or Subject")
                with gr.Row():
                    course_filter = gr.Dropdown(
                        choices=school_service.courses,
                        value="All",
                        label="Select Course",
                        scale=3
                    )
                    refresh_btn = gr.Button("πŸ”„ Refresh", variant="secondary", scale=1)
                announcements_html = gr.HTML()
                course_filter.change(fn=render_announcements, inputs=course_filter, outputs=announcements_html)
                refresh_btn.click(fn=render_announcements, inputs=course_filter, outputs=announcements_html)
                demo.load(fn=render_announcements, inputs=course_filter, outputs=announcements_html)

            with gr.Tab("πŸ’¬ Ask ThutoAI"):
                gr.Markdown("### πŸ’‘ Ask me anything β€” I'm here to help!")
                chatbot = gr.Chatbot(
                    height=480,
                    type='messages'  # βœ… FIXED: Replaced deprecated bubble_full_width
                )
                with gr.Row():
                    msg = gr.Textbox(
                        label="Type your question",
                        placeholder="E.g., How do I prepare for the Math exam?",
                        scale=7
                    )
                    voice_btn = gr.Button("πŸŽ™οΈ Speak", variant="secondary", scale=1)
                    submit_btn = gr.Button("➀ Send", variant="primary", scale=1)
                clear_btn = gr.Button("πŸ—‘οΈ Clear Chat", variant="secondary")

                def respond(message, chat_history):
                    for updated_history, _ in ai_chat(message, chat_history, CURRENT_USER):
                        yield updated_history, ""

                msg.submit(respond, [msg, chatbot], [msg, chatbot])
                submit_btn.click(respond, [msg, chatbot], [msg, chatbot])
                clear_btn.click(lambda: [], None, chatbot)

                voice_btn.click(
                    fn=voice_input_handler,
                    inputs=None,
                    outputs=msg,
                    js=VOICE_JS + "return startVoiceInput();"
                )

            with gr.Tab("πŸ“… Assignments"):
                gr.Markdown("### πŸ“Œ Your Upcoming Assignments & Exams")
                assignments_display = gr.HTML()
                demo.load(
                    fn=lambda: render_assignments(student_service.get_assignments(CURRENT_USER)) if CURRENT_USER != "guest" else "",
                    inputs=None,
                    outputs=assignments_display
                )

            with gr.Tab("πŸ‘₯ Class Groups"):
                gr.Markdown("### πŸŽ’ Join Your Class Groups")
                with gr.Row():
                    group_code_input = gr.Textbox(label="Group Code (e.g., MATH10A)", scale=3)
                    join_btn = gr.Button("βž• Join Group", variant="primary", scale=1)
                    leave_btn = gr.Button("βž– Leave Group", variant="secondary", scale=1)
                group_status = gr.Textbox(label="Status")
                groups_display = gr.HTML()
                join_btn.click(
                    fn=join_group,
                    inputs=group_code_input,
                    outputs=[group_status, groups_display]
                )
                leave_btn.click(
                    fn=leave_group,
                    inputs=group_code_input,
                    outputs=[group_status, groups_display]
                )
                demo.load(
                    fn=lambda: render_groups(student_service.get_groups(CURRENT_USER)) if CURRENT_USER != "guest" else "",
                    inputs=None,
                    outputs=groups_display
                )

            with gr.Tab("πŸ“‚ My Files"):
                gr.Markdown("### πŸ“ Upload & Manage Study Materials")
                with gr.Row():
                    file_input = gr.File(label="Drag & drop or click to upload", elem_classes=["file-upload"])
                    upload_btn = gr.Button("πŸ“€ Upload", variant="primary")
                upload_status = gr.Textbox(label="Status")
                file_list = gr.JSON(label="Your Files")

                upload_btn.click(
                    fn=upload_file_for_student,
                    inputs=file_input,
                    outputs=upload_status
                )
                demo.load(
                    fn=lambda: student_service.get_files(CURRENT_USER) if CURRENT_USER != "guest" else [],
                    inputs=None,
                    outputs=file_list
                )

            with gr.Tab("πŸ–ΌοΈ Profile"):
                gr.Markdown("### πŸ–ΌοΈ Update Your Profile Picture")
                with gr.Row():
                    avatar_input = gr.File(label="Choose an image (PNG, JPG)", file_types=["image"])
                    upload_avatar_btn = gr.Button("πŸ“€ Upload Avatar", variant="primary")
                avatar_status = gr.Textbox(label="Status")
                upload_avatar_btn.click(
                    fn=upload_avatar,
                    inputs=avatar_input,
                    outputs=avatar_status
                )
                demo.load(
                    fn=lambda: get_avatar_html(
                        student_service.students[CURRENT_USER]["avatar"] if CURRENT_USER != "guest" else None,
                        student_service.students[CURRENT_USER]["name"] if CURRENT_USER != "guest" else "Guest"
                    ) if CURRENT_USER != "guest" else "",
                    inputs=None,
                    outputs=avatar_display
                )

            with gr.Tab("πŸ‘©β€πŸ« Teacher Panel"):
                gr.Markdown("### πŸ”‘ Teacher Login (for assignment creation)")

                with gr.Group() as teacher_login_group:
                    teacher_username = gr.Textbox(label="Teacher Username")
                    teacher_password = gr.Textbox(label="Password", type="password")
                    teacher_login_btn = gr.Button("πŸ”“ Login", variant="primary")
                    teacher_status = gr.Textbox(label="Status")

                with gr.Group(visible=False) as teacher_dashboard:
                    gr.Markdown("### ✍️ Create New Assignment")
                    assignment_title = gr.Textbox(label="Assignment Title", placeholder="e.g., Chapter 5 Quiz")
                    assignment_description = gr.Textbox(label="Description", placeholder="Instructions for students...", lines=2)
                    assignment_due_date = gr.Textbox(label="Due Date (YYYY-MM-DD)", placeholder="2025-05-01")
                    assignment_course = gr.Dropdown(
                        choices=student_service.valid_groups,
                        label="Assign to Class Group",
                        value="MATH10A"
                    )
                    create_assignment_btn = gr.Button("πŸ“¬ Create Assignment", variant="primary")
                    assignment_result = gr.Textbox(label="Result")

                    # βœ… FIXED: Removed deprecated 'inline' parameter
                    assignment_priority = gr.Radio(
                        ["low", "normal", "high"],
                        label="Priority",
                        value="normal"
                    )

                    teacher_logout_btn = gr.Button("⬅️ Logout", variant="secondary")

                teacher_login_btn.click(
                    fn=teacher_login,
                    inputs=[teacher_username, teacher_password],
                    outputs=[teacher_login_group, teacher_dashboard, teacher_status, create_assignment_btn]
                )
                teacher_logout_btn.click(
                    fn=teacher_logout,
                    inputs=None,
                    outputs=[teacher_login_group, teacher_dashboard, teacher_status, assignment_result]
                )
                create_assignment_btn.click(
                    fn=create_assignment,
                    inputs=[assignment_title, assignment_description, assignment_due_date, assignment_course],
                    outputs=assignment_result
                )

            with gr.Tab("πŸ“Š Admin Analytics"):
                gr.Markdown("### πŸ“ˆ School Analytics Dashboard")
                analytics_display = gr.HTML()
                refresh_analytics_btn = gr.Button("πŸ”„ Refresh Analytics")
                refresh_analytics_btn.click(
                    fn=render_analytics,
                    inputs=None,
                    outputs=analytics_display
                )
                demo.load(
                    fn=render_analytics,
                    inputs=None,
                    outputs=analytics_display
                )

        # Logout button (already in header)

    # ========= EVENT HANDLERS =========
    login_btn.click(
        fn=login_student,
        inputs=[login_username, login_password],
        outputs=[
            login_group, main_app, chatbot, gr.update(), assignments_display, groups_display,
            login_status, user_display, logout_btn, avatar_display, dark_mode_btn, gr.update()
        ]
    )

    register_btn.click(
        fn=register_student,
        inputs=[reg_username, reg_password, reg_name],
        outputs=reg_status
    )

    dark_mode_btn.click(
        fn=toggle_dark_mode,
        inputs=None,
        outputs=[dark_mode_btn, gr.update()]
    )

# Launch app
if __name__ == "__main__":
    demo.launch()