File size: 109,321 Bytes
d810052
f202266
2afd9e5
d810052
 
 
 
 
 
 
0a9b204
 
d810052
 
 
f202266
ccbdc68
0a9b204
f202266
ccbdc68
f202266
d810052
 
 
 
 
 
 
 
f29c5eb
 
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f29c5eb
0a9b204
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6ea927b
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d810052
 
 
0a9b204
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
0a9b204
 
d810052
0a9b204
f202266
 
 
 
0a9b204
f202266
 
 
 
 
0a9b204
 
 
f202266
 
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
0a9b204
f202266
 
d810052
0a9b204
 
f202266
0a9b204
 
 
 
 
 
 
 
 
 
f202266
 
 
0a9b204
 
 
 
 
 
 
 
d810052
 
 
 
0a9b204
 
 
d810052
0a9b204
d810052
 
 
 
 
 
 
0a9b204
d810052
 
0a9b204
d810052
 
 
 
0a9b204
 
d810052
0a9b204
 
f202266
 
 
0a9b204
f202266
 
0a9b204
 
 
 
 
 
f202266
0a9b204
 
 
 
f202266
 
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
 
0a9b204
 
f202266
 
 
0a9b204
f202266
0a9b204
 
 
 
 
 
 
f202266
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
f202266
 
 
0a9b204
 
 
 
 
 
 
 
d810052
 
 
 
 
 
 
6ea927b
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
 
d810052
f202266
 
 
 
 
 
 
 
 
 
 
d810052
6ea927b
f202266
 
6ea927b
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
6ea927b
f202266
 
6ea927b
f202266
 
 
 
6ea927b
 
f202266
 
 
 
d810052
f202266
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
 
 
 
 
 
 
 
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
6ea927b
d810052
 
6ea927b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d810052
 
 
 
6ea927b
 
 
 
 
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
 
 
 
 
 
 
 
 
 
 
 
 
d810052
 
 
 
 
 
 
0a9b204
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
 
 
 
 
 
 
 
 
 
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a9b204
d810052
 
0a9b204
d810052
 
 
 
 
 
 
 
 
 
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a9b204
 
 
 
 
 
 
 
f202266
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a9b204
d810052
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
0a9b204
f202266
 
 
0a9b204
 
 
 
 
 
 
 
f202266
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a9b204
d810052
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
 
d810052
f202266
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d810052
f202266
 
 
 
 
 
 
 
d810052
ccbdc68
f202266
d810052
 
 
 
 
 
 
 
 
 
f202266
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2afd9e5
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2afd9e5
d810052
 
2afd9e5
d810052
2afd9e5
d810052
2afd9e5
 
 
d810052
 
2afd9e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d810052
2afd9e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d810052
2afd9e5
 
d810052
2afd9e5
d810052
 
2afd9e5
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a9b204
d810052
 
 
 
 
 
 
 
 
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f202266
2afd9e5
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d810052
 
 
 
 
 
 
 
2afd9e5
 
d810052
 
 
 
 
 
 
 
 
 
 
 
0a9b204
 
d810052
 
 
 
 
 
 
 
 
 
 
0a9b204
 
 
 
d810052
0a9b204
d810052
 
 
 
 
 
 
0a9b204
d810052
0a9b204
 
 
 
 
 
 
 
 
 
 
 
d810052
0a9b204
 
 
fbbfcf2
0a9b204
d810052
 
 
 
 
fbbfcf2
 
0a9b204
fbbfcf2
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d810052
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2afd9e5
 
0a9b204
 
 
 
 
 
 
 
 
 
 
2afd9e5
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2afd9e5
 
0a9b204
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2afd9e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
from fastapi import APIRouter, Depends, HTTPException, Request, Cookie, UploadFile, File, Form
from typing import List, Optional, Dict, Any, Callable
from pydantic import BaseModel, Field
from services.api.db.token_utils import decode_token
from dotenv import load_dotenv
import os
import pymysql
import pandas as pd
import boto3
import json
import threading
import asyncio
from botocore.exceptions import ClientError
from datetime import datetime
from fastapi.middleware.cors import CORSMiddleware
from services.utils.cache_utils import cache_data, cache_with_fallback, clear_cache
from services.config.valkey_config import get_redis_client
from services.utils.api_cache import get_cached_data, invalidate_cache, invalidate_cache_pattern

# Get Valkey client
redis_client = get_redis_client()

# Load environment variables
load_dotenv()
MYSQL_USER = os.getenv("MYSQL_USER")
MYSQL_PASSWORD = os.getenv("MYSQL_PASSWORD")
MYSQL_HOST = os.getenv("MYSQL_HOST", "localhost")
MYSQL_DB = os.getenv("MYSQL_DB")
MYSQL_PORT = int(os.getenv("MYSQL_PORT", "3306"))
SSL = {
    "ca": os.path.join(os.path.dirname(__file__), "ca.pem")
}

# AWS Configuration
AWS_ACCESS_KEY = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
REGION = os.getenv("REGION_NAME", "ap-southeast-1")

# Initialize S3 client
s3 = boto3.client('s3',
    aws_access_key_id=AWS_ACCESS_KEY,
    aws_secret_access_key=AWS_SECRET_KEY,
    region_name=REGION
)

router = APIRouter(
    tags=["courses"],
    responses={404: {"description": "Not found"}},
)

# Simple test endpoint to verify routing
@router.post("/test")
async def test_post():
    return {"message": "POST test endpoint works"}

def connect_db():
    try:
        print(f"Connecting to database {MYSQL_DB} on {MYSQL_HOST}:{MYSQL_PORT}")
        connection = pymysql.connect(
            host=MYSQL_HOST,
            user=MYSQL_USER,
            password=MYSQL_PASSWORD,
            database=MYSQL_DB,
            port=MYSQL_PORT,
            ssl=False
        )
        print("Database connection successful")
        return connection
    except Exception as e:
        print(f"Database connection error: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Database connection error: {str(e)}")

# Models
class Course(BaseModel):
    id: int
    name: str
    instructor: str
    description: Optional[str]
    rating: Optional[float] = None
    enrolled: Optional[int] = 0

class QuestionOption(BaseModel):
    text: str
    isCorrect: bool = False

class QuizQuestion(BaseModel):
    question: str
    options: list[str]
    correctAnswer: int

class Quiz(BaseModel):
    title: str
    description: Optional[str] = None
    questions: Dict[str, QuizQuestion]

class LectureListItem(BaseModel):
    id: int
    title: str
    courseId: int
    description: Optional[str] = None
    passed: Optional[bool] = False

class Lecture(BaseModel):
    id: int
    courseId: int
    title: str
    description: Optional[str] = None
    content: Optional[str] = None
    videoUrl: Optional[str] = None
    quiz: Optional[Quiz] = None
    
class LectureDetails(Lecture):
    courseName: Optional[str] = None
    courseDescription: Optional[str] = None
    courseLectures: Optional[List[LectureListItem]] = None

# Add the missing CourseDetails model
class CourseDetails(BaseModel):
    id: int
    name: str
    description: Optional[str]
    duration: Optional[str]
    skills: Optional[List[str]] = []
    difficulty: Optional[str]
    instructor: str
    instructor_id: Optional[int]
    enrolled: Optional[int] = 0
    rating: Optional[float] = None
    is_enrolled: Optional[bool] = False

# Optimized /courses endpoint
@router.get("/courses", response_model=List[Course])
async def get_courses(request: Request, auth_token: str = Cookie(None)):
    try:
        # Authentication (keep existing code)
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
        
        if not auth_token:
            raise HTTPException(status_code=401, detail="No authentication token provided")
            
        try:
            user_data = decode_token(auth_token)
        except Exception as e:
            print(f"Token decode error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token")
        
        # Better cache key with shorter TTL for faster updates
        cache_key = "courses:public:v2"
        
        # Optimized database fetch function
        async def fetch_courses_from_db():
            conn = connect_db()
            try:
                with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                    # Single optimized query with JOINs instead of N+1 queries
                    query = """
                    SELECT 
                        c.CourseID as id, 
                        c.CourseName as name, 
                        CONCAT(i.InstructorName, ' (', i.AccountName, ')') as instructor,
                        c.Descriptions as description,
                        COALESCE(enrollment_stats.enrolled, 0) as enrolled,
                        COALESCE(rating_stats.avg_rating, NULL) as rating
                    FROM Courses c
                    JOIN Instructors i ON c.InstructorID = i.InstructorID
                    LEFT JOIN (
                        SELECT 
                            CourseID, 
                            COUNT(*) as enrolled
                        FROM Enrollments 
                        GROUP BY CourseID
                    ) enrollment_stats ON c.CourseID = enrollment_stats.CourseID
                    LEFT JOIN (
                        SELECT 
                            CourseID, 
                            AVG(Rating) as avg_rating
                        FROM Enrollments 
                        WHERE Rating IS NOT NULL 
                        GROUP BY CourseID
                    ) rating_stats ON c.CourseID = rating_stats.CourseID
                    ORDER BY c.CourseID DESC
                    LIMIT 50
                    """
                    
                    cursor.execute(query)
                    courses = cursor.fetchall()
                    
                    # Format the data efficiently
                    formatted_courses = []
                    for course in courses:
                        formatted_courses.append({
                            'id': course['id'],
                            'name': course['name'],
                            'instructor': course['instructor'],
                            'description': course['description'],
                            'enrolled': course['enrolled'],
                            'rating': float(course['rating']) if course['rating'] else None
                        })
                    
                    return formatted_courses
            finally:
                conn.close()
        
        # Use optimized caching with compression and shorter TTL
        return await get_cached_data(
            cache_key, 
            fetch_courses_from_db, 
            ttl=900,  # 15 minutes instead of 1 hour for faster updates
            use_compression=True  # Enable compression for faster transfer
        )
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Get course details
# Optimize the course details endpoint with caching
@router.get("/courses/{course_id}", response_model=CourseDetails)
async def get_course_details(course_id: int, request: Request, auth_token: str = Cookie(None)):
    try:
        # Authentication
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
        
        if not auth_token:
            raise HTTPException(status_code=401, detail="No authentication token provided")
        
        try:
            user_data = decode_token(auth_token)
            user_id = user_data.get('user_id')
        except Exception as e:
            print(f"Token decode error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token")
        
        # Cache key for course details
        cache_key = f"course:details:{course_id}:user:{user_id}"
        
        # Optimized database fetch function
        async def fetch_course_details_from_db():
            conn = connect_db()
            try:
                with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                    # Single query with all course info, enrollment status, and user's enrollment
                    query = """
                    SELECT 
                        c.CourseID as id,
                        c.CourseName as name,
                        c.Descriptions as description,
                        c.EstimatedDuration as duration,
                        c.Skills as skills,
                        c.Difficulty as difficulty,
                        CONCAT(i.InstructorName, ' (', i.AccountName, ')') as instructor,
                        i.InstructorID as instructor_id,
                        COALESCE(enrollment_stats.enrolled, 0) as enrolled,
                        COALESCE(rating_stats.avg_rating, NULL) as rating,
                        CASE WHEN user_enrollment.LearnerID IS NOT NULL THEN TRUE ELSE FALSE END as is_enrolled
                    FROM Courses c
                    JOIN Instructors i ON c.InstructorID = i.InstructorID
                    LEFT JOIN (
                        SELECT CourseID, COUNT(*) as enrolled
                        FROM Enrollments 
                        GROUP BY CourseID
                    ) enrollment_stats ON c.CourseID = enrollment_stats.CourseID
                    LEFT JOIN (
                        SELECT CourseID, AVG(Rating) as avg_rating
                        FROM Enrollments 
                        WHERE Rating IS NOT NULL 
                        GROUP BY CourseID
                    ) rating_stats ON c.CourseID = rating_stats.CourseID
                    LEFT JOIN (
                        SELECT CourseID, LearnerID
                        FROM Enrollments e2
                        JOIN Learners l ON e2.LearnerID = l.LearnerID
                        WHERE l.LearnerID = %s
                    ) user_enrollment ON c.CourseID = user_enrollment.CourseID
                    WHERE c.CourseID = %s
                    """
                    
                    cursor.execute(query, (user_id, course_id))
                    course = cursor.fetchone()
                    
                    if not course:
                        raise HTTPException(status_code=404, detail="Course not found")
                    
                    # Format skills if it's JSON
                    skills = []
                    if course['skills']:
                        try:
                            skills = json.loads(course['skills'])
                        except:
                            skills = []
                    
                    return {
                        'id': course['id'],
                        'name': course['name'],
                        'description': course['description'],
                        'duration': course['duration'],
                        'skills': skills,
                        'difficulty': course['difficulty'],
                        'instructor': course['instructor'],
                        'instructor_id': course['instructor_id'],
                        'enrolled': course['enrolled'],
                        'rating': float(course['rating']) if course['rating'] else None,
                        'is_enrolled': course['is_enrolled']
                    }
            finally:
                conn.close()
        
        # Use caching with 30 minutes TTL
        return await get_cached_data(
            cache_key,
            fetch_course_details_from_db,
            ttl=1800,  # 30 minutes
            use_compression=True
        )
        
    except HTTPException:
        raise
    except Exception as e:
        print(f"Error in get_course_details: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# Get lectures for a course
@router.get("/courses/{course_id}/lectures", response_model=List[LectureListItem])
async def get_course_lectures(request: Request, course_id: int, auth_token: str = Cookie(None)):
    try:
        # Try to get token from Authorization header if cookie is not present
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
        
        if not auth_token:
            raise HTTPException(status_code=401, detail="No authentication token provided")
            
        try:
            user_data = decode_token(auth_token)
        except Exception as e:
            print(f"Token decode error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token")
        
        # Create cache key using course ID and user ID
        cache_key = f"courses:id:{course_id}:lectures:user:{user_data.get('user_id', 'anonymous')}"
        
        # Define database fetch function
        async def fetch_lectures_from_db():
            conn = connect_db()
            lectures = []
            
            try:
                with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                    # First verify the course exists
                    cursor.execute("SELECT CourseID FROM Courses WHERE CourseID = %s", (course_id,))
                    if not cursor.fetchone():
                        raise HTTPException(status_code=404, detail="Course not found")

                    # Get lectures with pass status for the current user
                    query = """
                    SELECT 
                        l.LectureID as id, 
                        l.CourseID as courseId,
                        l.Title as title, 
                        l.Description as description,
                        CASE 
                            WHEN lr.State = 'passed' THEN 1
                            ELSE 0
                        END as passed
                    FROM Lectures l
                    LEFT JOIN LectureResults lr ON l.LectureID = lr.LectureID 
                        AND lr.LearnerID = %s 
                        AND lr.CourseID = %s
                    WHERE l.CourseID = %s
                    ORDER BY l.LectureID
                    """
                    cursor.execute(query, (user_data.get('user_id'), course_id, course_id))
                    lectures = cursor.fetchall()
                    
                    # Ensure all fields match the LectureListItem model
                    for lecture in lectures:
                        # Ensure the fields exist and have appropriate null values if missing
                        if lecture.get('description') is None:
                            lecture['description'] = None
                        # Convert passed from 1/0 to True/False
                        lecture['passed'] = bool(lecture.get('passed', 0))
            finally:
                conn.close()
                
            return lectures
            
        # Use cached data helper
        return await get_cached_data(cache_key, fetch_lectures_from_db, ttl=3600)
    except HTTPException:
        raise
    except Exception as e:
        print(f"Error in get_course_lectures: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# Get lecture details
@router.get("/lectures/{lecture_id}", response_model=LectureDetails)
async def get_lecture_details(request: Request, lecture_id: int, auth_token: str = Cookie(None)):
    try:
        # Try to get token from Authorization header if cookie is not present
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
        
        if not auth_token:
            raise HTTPException(status_code=401, detail="No authentication token provided")
            
        # Verify user is authenticated
        try:
            user_data = decode_token(auth_token)
        except Exception as e:
            print(f"Token decode error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token")
        
        # Create cache key using lecture ID and user ID
        cache_key = f"lectures:id:{lecture_id}:user:{user_data.get('user_id', 'anonymous')}"
        
        # Define database fetch function
        async def fetch_lecture_from_db():
            conn = connect_db()
            cursor = None
            try:
                cursor = conn.cursor(pymysql.cursors.DictCursor)
                # Get lecture details with course data
                query = """
                SELECT 
                    l.LectureID as id,
                    l.CourseID as courseId,
                    l.Title as title,
                    l.Description as description,
                    l.Content as content,
                    c.CourseName as courseName,
                    c.CourseID,
                    c.Descriptions as courseDescription
                FROM Lectures l
                JOIN Courses c ON l.CourseID = c.CourseID
                WHERE l.LectureID = %s
                """
                cursor.execute(query, (lecture_id,))
                lecture = cursor.fetchone()
                
                if not lecture:
                    raise HTTPException(status_code=404, detail="Lecture not found")
            
                # Get course lectures with pass status
                cursor.execute("""
                SELECT 
                    l.LectureID as id,
                    l.CourseID as courseId,
                    l.Title as title,
                    l.Description as description,
                    CASE 
                        WHEN lr.State = 'passed' THEN 1
                        ELSE 0
                    END as passed
                FROM Lectures l
                LEFT JOIN LectureResults lr ON l.LectureID = lr.LectureID 
                    AND lr.LearnerID = %s 
                    AND lr.CourseID = %s
                WHERE l.CourseID = %s
                ORDER BY l.LectureID
                """, (user_data.get('user_id'), lecture['courseId'], lecture['courseId']))
                
                course_lectures = cursor.fetchall()
                if not course_lectures:
                    course_lectures = []
                else:
                    # Convert passed from 1/0 to True/False for each lecture
                    for course_lecture in course_lectures:
                        if course_lecture.get('description') is None:
                            course_lecture['description'] = None
                        course_lecture['passed'] = bool(course_lecture.get('passed', 0))

                response_data = {
                    "id": lecture['id'],
                    "courseId": lecture['courseId'],
                    "title": lecture['title'],
                    "description": lecture['description'],
                    "content": lecture['content'],
                    "courseName": lecture['courseName'],
                    "courseDescription": lecture['courseDescription'],
                    "courseLectures": course_lectures,
                    "videoUrl": None,
                    "quiz": None  # Initialize quiz as None
                }

                # Get video URL if exists
                video_path = f"videos/cid{lecture['courseId']}/lid{lecture['id']}/vid_lecture.mp4"
                try:
                    s3.head_object(Bucket="tlhmaterials", Key=video_path)
                    response_data['videoUrl'] = f"https://tlhmaterials.s3-{REGION}.amazonaws.com/{video_path}"
                except:
                    pass  # Keep videoUrl as None if no video exists

                # Get quiz if exists - fixing this part
                cursor.execute("""
                SELECT q.QuizID, q.Title, q.Description
                FROM Quizzes q
                WHERE q.LectureID = %s
                """, (lecture_id,))
                
                quiz_data = cursor.fetchone()
                if quiz_data:
                    quiz = {
                        "id": quiz_data['QuizID'],
                        "title": quiz_data['Title'],
                        "description": quiz_data['Description'],
                        "questions": {}
                    }
                    
                    # Get quiz questions
                    cursor.execute("""
                    SELECT 
                        q.QuestionID, 
                        q.QuestionText,
                        o.OptionID,
                        o.OptionText,
                        o.IsCorrect
                    FROM Questions q
                    JOIN Options o ON q.QuestionID = o.QuestionID
                    WHERE q.QuizID = %s
                    ORDER BY q.QuestionID, o.OptionID
                    """, (quiz_data['QuizID'],))
                    
                    questions_data = cursor.fetchall()
                    current_question_id = None
                    current_options = []
                    correct_option_index = 0
                    
                    for row in questions_data:
                        if current_question_id != row['QuestionID']:
                            # Save previous question data
                            if current_question_id is not None:
                                quiz['questions'][str(current_question_id)] = {
                                    'question': question_text,
                                    'options': current_options,
                                    'correctAnswer': correct_option_index
                                }
                            
                            # Start new question
                            current_question_id = row['QuestionID']
                            question_text = row['QuestionText']
                            current_options = []
                            correct_option_index = 0
                        
                        current_options.append(row['OptionText'])
                        if row['IsCorrect']:
                            correct_option_index = len(current_options) - 1
                    
                    # Save the last question
                    if current_question_id is not None:
                        quiz['questions'][str(current_question_id)] = {
                            'question': question_text,
                            'options': current_options,
                            'correctAnswer': correct_option_index
                        }
                    
                    response_data['quiz'] = quiz
                
                return response_data
            finally:
                if cursor:
                    cursor.close()
                if conn:
                    conn.close()
        
        # Use the caching mechanism to get the data
        return await get_cached_data(
            cache_key,
            fetch_lecture_from_db,
            ttl=3600,  # Cache for 1 hour
            use_compression=True  # Enable compression for large response
        )
            
    except HTTPException:
        raise
    except Exception as e:
        print(f"Error in get_lecture_details: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# Get instructor's courses with proper caching
@router.get("/instructor/courses", response_model=List[Course])
async def get_instructor_courses(
    request: Request,
    auth_token: str = Cookie(None)
):
    try:
        # Get token from header if not in cookie
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")
        
        # Verify token and get user data
        user_data = decode_token(auth_token)
        username = user_data['username']
        role = user_data['role']
        instructor_id = user_data.get('user_id')
        
        # Verify user is an instructor
        if role != "Instructor":
            raise HTTPException(status_code=403, detail="Only instructors can access this endpoint")
        
        # Create a cache key for instructor courses
        cache_key = f"instructor:courses:{instructor_id or username}"
        
        # Define database fetch function
        async def fetch_instructor_courses_from_db():
            conn = connect_db()
            try:
                with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                    # Get instructor ID from token or fallback to database lookup
                    current_instructor_id = instructor_id
                    if not current_instructor_id:
                        # Fallback for old tokens without user_id
                        cursor.execute("""
                            SELECT InstructorID 
                            FROM Instructors 
                            WHERE AccountName = %s
                        """, (username,))
                        
                        instructor = cursor.fetchone()
                        if not instructor:
                            raise HTTPException(status_code=404, detail="Instructor not found")
                        
                        current_instructor_id = instructor['InstructorID']
                    
                    # Get courses by this instructor
                    query = """
                        SELECT 
                            c.CourseID as id, 
                            c.CourseName as name, 
                            CONCAT(i.InstructorName, ' (', i.AccountName, ')') as instructor,
                            c.Descriptions as description,
                            (SELECT COUNT(*) FROM Enrollments WHERE CourseID = c.CourseID) as enrolled,
                            COALESCE(
                                (SELECT AVG(Rating) 
                                 FROM Enrollments 
                                 WHERE CourseID = c.CourseID AND Rating IS NOT NULL),
                                0
                            ) as rating
                        FROM Courses c
                        JOIN Instructors i ON c.InstructorID = i.InstructorID
                        WHERE c.InstructorID = %s
                        ORDER BY c.CourseID DESC
                    """
                    
                    cursor.execute(query, (current_instructor_id,))
                    courses = cursor.fetchall()
                    
                    # Format the courses data
                    formatted_courses = []
                    for course in courses:
                        formatted_course = {
                            'id': course['id'],
                            'name': course['name'],
                            'instructor': course['instructor'],
                            'description': course['description'],
                            'enrolled': course['enrolled'],
                            'rating': float(course['rating']) if course['rating'] else None
                        }
                        formatted_courses.append(formatted_course)
                    
                    return formatted_courses
            finally:
                conn.close()
        
        # Use the caching mechanism to get the data
        return await get_cached_data(
            cache_key,
            fetch_instructor_courses_from_db,
            ttl=1800,  # Cache for 30 minutes
            use_compression=True  # Enable compression for large response
        )
            
    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Error fetching instructor courses: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# Create a new course
class CourseCreate(BaseModel):
    name: str
    description: str
    skills: List[str]
    difficulty: str
    duration: Optional[int] = None

@router.post("/instructor/courses", response_model=Course)
async def create_course(
    course_data: CourseCreate,
    request: Request,
    auth_token: str = Cookie(None)
):
    try:
        # Get token from header if not in cookie
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")
        
        # Verify token and get user data
        try:
            user_data = decode_token(auth_token)
            username = user_data['username']
            role = user_data['role']
            instructor_id = user_data.get('user_id')
            
            # Log debugging information
            print(f"POST /instructor/courses - User: {username}, Role: {role}, InstructorID: {instructor_id}")
            print(f"Course data: {course_data}")
            
            # Verify user is an instructor
            if role != "Instructor":
                raise HTTPException(status_code=403, detail="Only instructors can create courses")
            
            # Connect to database
            conn = connect_db()
            
            with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                # Get instructor ID from token or fallback to database lookup
                if not instructor_id:
                    # Fallback for old tokens without user_id
                    cursor.execute("""
                        SELECT InstructorID 
                        FROM Instructors 
                        WHERE AccountName = %s
                    """, (username,))
                    
                    instructor = cursor.fetchone()
                    if not instructor:
                        raise HTTPException(status_code=404, detail="Instructor not found")
                    
                    instructor_id = instructor['InstructorID']
                
                # Insert new course
                cursor.execute("""
                    INSERT INTO Courses 
                    (CourseName, Descriptions, Skills, Difficulty, EstimatedDuration, InstructorID) 
                    VALUES (%s, %s, %s, %s, %s, %s)
                """, (
                    course_data.name, 
                    course_data.description, 
                    json.dumps(course_data.skills), 
                    course_data.difficulty, 
                    course_data.duration or "Self-paced", 
                    instructor_id
                ))
                
                # Get the created course ID
                course_id = cursor.lastrowid
                conn.commit()
                
                # Return the created course
                cursor.execute("""
                    SELECT 
                        c.CourseID as id, 
                        c.CourseName as name, 
                        CONCAT(i.InstructorName, ' (', i.AccountName, ')') as instructor,
                        c.Descriptions as description,
                        0 as enrolled,
                        NULL as rating
                    FROM Courses c
                    JOIN Instructors i ON c.InstructorID = i.InstructorID
                    WHERE c.CourseID = %s
                """, (course_id,))
                
                new_course = cursor.fetchone()
                if not new_course:
                    raise HTTPException(status_code=500, detail="Course was created but couldn't be retrieved")
                
                # Invalidate Valkey cache for all courses and instructor-specific cache
                pattern_all = "courses:all"
                pattern_instructor = f"instructor:courses:{instructor_id or username}"
                pattern_course_details = f"courses:id"  # Invalidate specific course details too
                print(f"Invalidating cache patterns: {pattern_all}, {pattern_instructor}, and {pattern_course_details}")
                invalidate_cache_pattern(pattern_all)
                invalidate_cache_pattern(pattern_course_details)
                invalidate_cache([pattern_instructor])
                
                return new_course
                
        except Exception as e:
            if 'conn' in locals():
                conn.rollback()
            print(f"Database error: {str(e)}")
            raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")
            
    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Error creating course: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        if 'conn' in locals():
            conn.close()

# Enroll in a course
@router.post("/courses/{course_id}/enroll")
async def enroll_in_course(
    course_id: int,
    request: Request,
    auth_token: str = Cookie(None)
):
    try:
        # Get token from header if not in cookie
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")
        
        # Verify token and get user data
        try:
            user_data = decode_token(auth_token)
            learner_id = user_data.get('user_id')
            
            if not learner_id:
                # Fallback for old tokens without user_id - do database lookup
                conn = connect_db()
                with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                    cursor.execute("""
                        SELECT LearnerID 
                        FROM Learners 
                        WHERE AccountName = %s
                    """, (user_data['username'],))
                    learner = cursor.fetchone()
                    if not learner:
                        raise HTTPException(status_code=404, detail="Learner not found")
                    learner_id = learner['LearnerID']
            else:
                # Use user_id from token
                conn = connect_db()
        except Exception as e:
            print(f"Token/user verification error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token or user not found")

        # Check if the course exists
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute("""
                SELECT CourseID 
                FROM Courses 
                WHERE CourseID = %s
            """, (course_id,))
            course = cursor.fetchone()
            if not course:
                raise HTTPException(status_code=404, detail="Course not found")
            
            # Check if already enrolled
            cursor.execute("""
                SELECT EnrollmentID 
                FROM Enrollments 
                WHERE LearnerID = %s AND CourseID = %s
            """, (learner_id, course_id))
            existing_enrollment = cursor.fetchone()
            if existing_enrollment:
                return {"message": "Already enrolled in this course"}
            
            # Get the actual column names from the Enrollments table
            cursor.execute("DESCRIBE Enrollments")
            columns = cursor.fetchall()
            column_names = [col['Field'] for col in columns]
            print(f"Available columns in Enrollments table: {column_names}")
            
            # Enroll the learner in the course with the correct date column
            try:
                # Try different common column names for the enrollment date
                enroll_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                cursor.execute(
                    "CALL sp_EnrollLearner(%s, %s, %s)",
                    (learner_id, course_id, enroll_date)
                )
                
                conn.commit()
                
                # Invalidate Valkey cache for this course and user-specific data
                redis_client = get_redis_client()
                # Clear specific course cache for all users
                pattern_course = f"courses:id:{course_id}:*"
                # Clear course preview cache for all users (this is the missing piece!)
                pattern_preview = f"course:preview:{course_id}:*"
                # Clear user-specific enrolled courses cache
                pattern_user_courses = f"learner:courses:{learner_id}"
                print(f"Invalidating cache patterns: {pattern_course}, {pattern_preview}, and {pattern_user_courses}")
                invalidate_cache_pattern(pattern_course)
                invalidate_cache_pattern(pattern_preview)
                invalidate_cache([pattern_user_courses])
                
                return {"message": "Successfully enrolled in the course"}
            except Exception as e:
                conn.rollback()
                print(f"Error enrolling in course: {str(e)}")
                raise HTTPException(status_code=500, detail=f"Failed to enroll in course: {str(e)}")
        
    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Error enrolling in course: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error enrolling in course: {str(e)}")
    finally:
        if 'conn' in locals():
            conn.close()

# Get enrolled courses for the current learner
@router.get("/learner/courses", response_model=List[Course])
async def get_enrolled_courses(
    request: Request,
    auth_token: str = Cookie(None)
):
    try:
        # Get token from header if not in cookie
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")
        
        # Verify token and get user data
        try:
            user_data = decode_token(auth_token)
            learner_id = user_data.get('user_id')
            
            if not learner_id:
                # Fallback for old tokens without user_id - do database lookup
                conn = connect_db()
                with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                    cursor.execute("""
                        SELECT LearnerID 
                        FROM Learners 
                        WHERE AccountName = %s
                    """, (user_data['username'],))
                    learner = cursor.fetchone()
                    if not learner:
                        raise HTTPException(status_code=404, detail="Learner not found")
                    learner_id = learner['LearnerID']
            else:
                # Use user_id from token
                conn = connect_db()
        except Exception as e:
            print(f"Token/user verification error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token or user not found")

        # Get enrolled courses
        courses = []
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            query = """
                SELECT 
                    c.CourseID as id, 
                    c.CourseName as name, 
                    CONCAT(i.InstructorName, ' (', i.AccountName, ')') as instructor,
                    c.Descriptions as description
                FROM Courses c
                JOIN Instructors i ON c.InstructorID = i.InstructorID
                JOIN Enrollments e ON c.CourseID = e.CourseID
                WHERE e.LearnerID = %s
            """
            cursor.execute(query, (learner_id,))
            courses = cursor.fetchall()
            
            # Get ratings and enrollment count for each course
            for course in courses:
                cursor.execute("""
                    SELECT AVG(Rating) as avg_rating, COUNT(*) as count
                    FROM Enrollments
                    WHERE CourseID = %s AND Rating IS NOT NULL
                """, (course['id'],))
                
                rating_data = cursor.fetchone()
                if rating_data and rating_data['avg_rating']:
                    course['rating'] = float(rating_data['avg_rating'])
                else:
                    course['rating'] = None
                    
                # Get enrollment count
                cursor.execute("""
                    SELECT COUNT(*) as enrolled
                    FROM Enrollments
                    WHERE CourseID = %s
                """, (course['id'],))
                
                enrolled_data = cursor.fetchone()
                if enrolled_data:
                    course['enrolled'] = enrolled_data['enrolled']
                else:
                    course['enrolled'] = 0
        
        return courses
        
    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Error fetching enrolled courses: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error fetching enrolled courses: {str(e)}")
    finally:
        if 'conn' in locals():
            conn.close()

# Get user profile
@router.get("/user/profile")
async def get_user_profile(
    request: Request,
    auth_token: str = Cookie(None)
):
    try:
        # Get token from header if not in cookie
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")
        
        # Verify token and get user data
        try:
            user_data = decode_token(auth_token)
            username = user_data['username']
            role = user_data['role']
            
            # Create a unique cache key for this user's profile
            cache_key = f"user:profile:{username}:{role}"
            
            # Define the database fetch function
            async def fetch_profile_from_db():
                # Connect to database
                conn = connect_db()
                try:
                    # Get user information based on role
                    with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                        if role == "Learner":
                            cursor.execute("""
                                SELECT 
                                    LearnerName as name,
                                    Email as email,
                                    PhoneNumber as phoneNumber
                                FROM Learners
                                WHERE AccountName = %s
                            """, (username,))
                            user_info = cursor.fetchone()
                            
                            if not user_info:
                                raise HTTPException(status_code=404, detail="Learner not found")
                                
                        elif role == "Instructor":
                            cursor.execute("""
                                SELECT 
                                    InstructorName as name,
                                    Email as email,
                                    Expertise as expertise
                                FROM Instructors
                                WHERE AccountName = %s
                            """, (username,))
                            user_info = cursor.fetchone()
                            
                            if not user_info:
                                raise HTTPException(status_code=404, detail="Instructor not found")
                        else:
                            raise HTTPException(status_code=403, detail="Invalid user role")
                        
                        # Add role and username to the response
                        user_info['role'] = role
                        user_info['username'] = username
                        
                        return user_info
                finally:
                    if 'conn' in locals():
                        conn.close()
                
            # Use the cached data helper to implement the Valkey caching pattern
            return await get_cached_data(cache_key, fetch_profile_from_db, ttl=1800)  # 30 minutes TTL
                
        except Exception as e:
            print(f"Token/user verification error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token or user not found")
    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Error fetching user profile: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error fetching user profile: {str(e)}")
    finally:
        pass  # Connection is closed in the fetch function

# Update user profile
@router.put("/user/profile")
async def update_user_profile(
    request: Request,
    auth_token: str = Cookie(None)
):
    try:
        # Get token from header if not in cookie
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")
        
        # Verify token and get user data
        try:
            user_data = decode_token(auth_token)
            username = user_data['username']
            role = user_data['role']
            
            # Get request body
            profile_data = await request.json()
            
            # Connect to database
            conn = connect_db()
            
            # Update user information based on role
            with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                if role == "Learner":
                    # Prepare update fields
                    update_fields = []
                    params = []
                    
                    if 'name' in profile_data:
                        update_fields.append("LearnerName = %s")
                        params.append(profile_data['name'])
                    
                    if 'email' in profile_data:
                        update_fields.append("Email = %s")
                        params.append(profile_data['email'])
                    
                    if 'phoneNumber' in profile_data:
                        update_fields.append("PhoneNumber = %s")
                        params.append(profile_data['phoneNumber'])
                    
                    if not update_fields:
                        return {"message": "No fields to update"}
                    
                    # Add username to params
                    params.append(username)
                    
                    # Construct and execute SQL
                    sql = f"""
                        UPDATE Learners
                        SET {', '.join(update_fields)}
                        WHERE AccountName = %s
                    """
                    cursor.execute(sql, params)
                    
                elif role == "Instructor":
                    # Prepare update fields
                    update_fields = []
                    params = []
                    
                    if 'name' in profile_data:
                        update_fields.append("InstructorName = %s")
                        params.append(profile_data['name'])
                    
                    if 'email' in profile_data:
                        update_fields.append("Email = %s")
                        params.append(profile_data['email'])
                    
                    if 'expertise' in profile_data:
                        update_fields.append("Expertise = %s")
                        params.append(profile_data['expertise'])
                    
                    if not update_fields:
                        return {"message": "No fields to update"}
                    
                    # Add username to params
                    params.append(username)
                    
                    # Construct and execute SQL
                    sql = f"""
                        UPDATE Instructors
                        SET {', '.join(update_fields)}
                        WHERE AccountName = %s
                    """
                    cursor.execute(sql, params)
                    
                else:
                    raise HTTPException(status_code=403, detail="Invalid user role")
                
                conn.commit()
                return {"message": "Profile updated successfully"}
                
        except Exception as e:
            print(f"Token/user verification error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token or user not found")
    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Error updating user profile: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error updating user profile: {str(e)}")
    finally:
        if 'conn' in locals():
            conn.close()

# Get dashboard data for the current user
@router.get("/learner/dashboard")
async def get_learner_dashboard(
    request: Request,
    auth_token: str = Cookie(None)
):
    try:
        # Get token from header if not in cookie
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")
        
        # Verify token and get user data
        try:
            user_data = decode_token(auth_token)
            
            # Get LearnerID from Learners table using the username
            conn = connect_db()
            with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                cursor.execute("""
                    SELECT LearnerID, LearnerName 
                    FROM Learners 
                    WHERE AccountName = %s
                """, (user_data['username'],))
                learner = cursor.fetchone()
                if not learner:
                    raise HTTPException(status_code=404, detail="Learner not found")
                learner_id = learner['LearnerID']
                learner_name = learner['LearnerName']
        except Exception as e:
            print(f"Token/user verification error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token or user not found")

        # Calculate dashboard metrics
        dashboard_data = {
            "learnerName": learner_name,
            "enrolled": 0,
            "completed": 0,
            "completionRate": "0%",
            "lecturesPassed": 0,
            "statistics": {
                "lecturesPassed": [],
                "averageScores": []
            },
            "enrolledCourses": []
        }
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # Get enrollment count
            cursor.execute("SELECT COUNT(*) as count FROM Enrollments WHERE LearnerID = %s", (learner_id,))
            enrolled_data = cursor.fetchone()
            dashboard_data["enrolled"] = enrolled_data['count'] if enrolled_data else 0
            
            # Get completed courses count
            cursor.execute(
                "SELECT COUNT(*) as count FROM Enrollments WHERE LearnerID = %s AND Percentage = 100",
                (learner_id,)
            )
            completed_data = cursor.fetchone()
            completed = completed_data['count'] if completed_data else 0
            dashboard_data["completed"] = completed
            
            # Calculate completion rate
            if dashboard_data["enrolled"] > 0:
                rate = (completed / dashboard_data["enrolled"]) * 100
                dashboard_data["completionRate"] = f"{rate:.1f}%"
            
            # Get passed lectures count
            cursor.execute(
                "SELECT COUNT(*) as count FROM LectureResults WHERE LearnerID = %s AND State = 'passed'",
                (learner_id,)
            )
            passed_data = cursor.fetchone()
            dashboard_data["lecturesPassed"] = passed_data['count'] if passed_data else 0
            
            # Get statistics data - passed lectures over time
            # Fix the learner dashboard query around line 1270
            cursor.execute("""
                SELECT Date, Score, 
                        DATE_FORMAT(Date, '%%Y-%%m-%%d') as formatted_date
                FROM LectureResults
                WHERE LearnerID = %s AND State = 'passed'
                ORDER BY Date
            """, (learner_id,))
            
            stats_data = cursor.fetchall()
            date_groups = {}
            score_groups = {}
            
            for row in stats_data:
                date_str = row['formatted_date']
                if date_str not in date_groups:
                    date_groups[date_str] = 0
                date_groups[date_str] += 1
                
                if date_str not in score_groups:
                    score_groups[date_str] = {"total": 0, "count": 0}
                score_groups[date_str]["total"] += row['Score']
                score_groups[date_str]["count"] += 1
            
            # Format the statistics data
            for date_str in date_groups:
                dashboard_data["statistics"]["lecturesPassed"].append({
                    "date": date_str,
                    "count": date_groups[date_str]
                })
                
                avg_score = score_groups[date_str]["total"] / score_groups[date_str]["count"]
                dashboard_data["statistics"]["averageScores"].append({
                    "date": date_str,
                    "score": round(avg_score, 2)
                })
            
            # Get enrolled courses with percentage
            cursor.execute("""
                SELECT
                    c.CourseID as id, 
                    c.CourseName as name, 
                    CONCAT(i.InstructorName, ' (', i.AccountName, ')') as instructor,
                    c.Descriptions as description,
                    e.Percentage as percentage
                FROM Courses c
                JOIN Instructors i ON c.InstructorID = i.InstructorID
                JOIN Enrollments e ON c.CourseID = e.CourseID
                WHERE e.LearnerID = %s
            """, (learner_id,))
            
            courses = cursor.fetchall()
            dashboard_data["enrolledCourses"] = courses
            
        return dashboard_data
        
    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Error fetching dashboard data: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error fetching dashboard data: {str(e)}")
    finally:
        if 'conn' in locals():
            conn.close()

# Get dashboard data for instructor
@router.get("/instructor/dashboard")
async def get_instructor_dashboard(
    request: Request,
    course_id: Optional[int] = None,
    auth_token: str = Cookie(None)
):
    conn = None
    try:
        # 1) Auth token via cookie or header
        if not auth_token:
            auth_header = request.headers.get("Authorization")
            if auth_header and auth_header.startswith("Bearer "):
                auth_token = auth_header.split(" ", 1)[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")

        # 2) Decode and verify
        user_data = decode_token(auth_token)
        username = user_data.get("username")
        role = user_data.get("role")
        instructor_id = user_data.get("user_id")
        if role != "Instructor":
            raise HTTPException(status_code=403, detail="Only instructors can access this endpoint")
        if not username:
            raise HTTPException(status_code=401, detail="Invalid token payload")

        # 3) DB connection
        conn = connect_db()
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:

            # Fallback for old tokens without user_id
            if not instructor_id:
                cursor.execute(
                    "SELECT InstructorID FROM Instructors WHERE AccountName = %s",
                    (username,)
                )
                row = cursor.fetchone()
                if not row:
                    raise HTTPException(status_code=404, detail="Instructor not found")
                instructor_id = row["InstructorID"]

            # --- General metrics ---
            cursor.execute("""
                SELECT COUNT(*) AS total_courses
                FROM Courses
                WHERE InstructorID = %s
            """, (instructor_id,))
            total_courses = cursor.fetchone()["total_courses"]

            cursor.execute("""
                SELECT
                    COUNT(DISTINCT e.LearnerID) AS total_students,
                    COALESCE(AVG(e.Rating), 0) AS average_rating,
                    COUNT(*) AS total_enrollments,
                    SUM(CASE WHEN e.Percentage = 100 THEN 1 ELSE 0 END) AS completed_enrollments
                FROM Courses c
                LEFT JOIN Enrollments e ON c.CourseID = e.CourseID
                WHERE c.InstructorID = %s
            """, (instructor_id,))
            stats = cursor.fetchone() or {}

            completion_rate = (
                round(
                    stats.get("completed_enrollments", 0)
                    / stats.get("total_enrollments", 1)
                    * 100,
                    1
                )
                if stats.get("total_enrollments") else 0.0
            )

            # --- Student growth (last 2 months) ---
            cursor.execute("""
                SELECT
                    DATE_FORMAT(EnrollmentDate, '%%Y-%%m') AS month,
                    COUNT(DISTINCT LearnerID) AS students
                FROM Courses c
                JOIN Enrollments e ON c.CourseID = e.CourseID
                WHERE c.InstructorID = %s
                  AND EnrollmentDate >= DATE_SUB(CURRENT_DATE, INTERVAL 2 MONTH)
                GROUP BY month
                ORDER BY month DESC
                LIMIT 2
            """, (instructor_id,))
            growth = cursor.fetchall()
            current = growth[0]["students"] if len(growth) > 0 else 0
            previous = growth[1]["students"] if len(growth) > 1 else 0
            student_growth = (
                round((current - previous) / previous * 100, 1)
                if previous else 0.0
            )

            # --- Course list summary ---
            cursor.execute("""
                SELECT
                    c.CourseID   AS id,
                    c.CourseName AS name,
                    c.Descriptions     AS description,
                    c.AverageRating    AS rating,
                    COUNT(DISTINCT e.LearnerID) AS enrollments,
                    AVG(e.Percentage)  AS completionRate
                FROM Courses c
                LEFT JOIN Enrollments e ON c.CourseID = e.CourseID
                WHERE c.InstructorID = %s
                GROUP BY c.CourseID
                ORDER BY c.CreatedAt DESC
            """, (instructor_id,))
            raw_courses = cursor.fetchall()
            formatted_courses = [
                {
                    "id": c["id"],
                    "name": c["name"],
                    "description": c["description"] or "",
                    "enrollments": c["enrollments"] or 0,
                    "rating": round(float(c["rating"]), 1) if c["rating"] else 0.0,
                    "completionRate": round(float(c["completionRate"]), 1) if c["completionRate"] else 0.0
                }
                for c in raw_courses
            ]

            # --- Enrollment trends (last 30 days) ---
            cursor.execute("""
                SELECT
                    DATE_FORMAT(e.EnrollmentDate, '%%Y-%%m-%%d') AS date,
                    COUNT(*)                              AS value
                FROM Courses c
                JOIN Enrollments e ON c.CourseID = e.CourseID
                WHERE c.InstructorID = %s
                  AND e.EnrollmentDate >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY)
                GROUP BY date
                ORDER BY date
            """, (instructor_id,))
            enroll_trends = cursor.fetchall()

            # --- Rating trends (last 30 days) ---
            cursor.execute("""
                SELECT
                    DATE_FORMAT(e.EnrollmentDate, '%%Y-%%m-%%d') AS date,
                    AVG(e.Rating)                         AS value
                FROM Courses c
                JOIN Enrollments e ON c.CourseID = e.CourseID
                WHERE c.InstructorID = %s
                  AND e.Rating IS NOT NULL
                  AND e.EnrollmentDate >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY)
                GROUP BY date
                ORDER BY date
            """, (instructor_id,))
            rating_trends = cursor.fetchall()

            # --- Build base payload ---
            dashboard_data = {
                "metrics": {
                    "totalCourses": total_courses,
                    "totalStudents": stats.get("total_students", 0),
                    "averageRating": round(stats.get("average_rating", 0), 1),
                    "completionRate": completion_rate,
                    "studentGrowth": student_growth
                },
                "courses": formatted_courses,
                "enrollmentTrends": [
                    {"date": r["date"], "value": r["value"]} for r in enroll_trends
                ],
                "ratingTrends": [
                    {"date": r["date"], "value": round(r["value"], 1)}
                    for r in rating_trends if r["value"] is not None
                ],
                "courseEnrollments": [
                    {"courseName": c["name"], "enrollments": c["enrollments"]}
                    for c in formatted_courses
                ],
                "courseAnalytics": {}
            }

            # --- Detailed courseAnalytics if course_id given ---
            if course_id:
                # Ownership check
                cursor.execute("""
                    SELECT CourseID, CourseName
                    FROM Courses
                    WHERE CourseID = %s AND InstructorID = %s
                """, (course_id, instructor_id))
                course_row = cursor.fetchone()
                if not course_row:
                    raise HTTPException(status_code=404, detail="Course not found or not owned")
                course_name = course_row["CourseName"]

                # Basic course metrics
                cursor.execute("""
                    SELECT
                        COUNT(DISTINCT e.LearnerID) AS total_enrollments,
                        COALESCE(AVG(e.Rating), 0)   AS average_rating,
                        SUM(CASE WHEN e.Percentage = 100 THEN 1 ELSE 0 END) AS completed_enrollments,
                        COUNT(*) AS all_with_progress
                    FROM Enrollments e
                    WHERE e.CourseID = %s
                """, (course_id,))
                cm = cursor.fetchone() or {}
                total_enr = cm.get("total_enrollments", 0)
                total_with = cm.get("all_with_progress", 0)
                comp_rate = (
                    round(cm.get("completed_enrollments", 0) / total_with * 100, 1)
                    if total_with else 0.0
                )

                # Enroll/Ratings trends (60 days)
                cursor.execute("""
                    SELECT
                        DATE_FORMAT(EnrollmentDate, '%%Y-%%m-%%d') AS date,
                        COUNT(*)                               AS value
                    FROM Enrollments
                    WHERE CourseID = %s
                      AND EnrollmentDate >= DATE_SUB(CURRENT_DATE, INTERVAL 60 DAY)
                    GROUP BY date
                    ORDER BY date
                """, (course_id,))
                ce_trends = cursor.fetchall()

                cursor.execute("""
                    SELECT
                        DATE_FORMAT(EnrollmentDate, '%%Y-%%m-%%d') AS date,
                        AVG(Rating)                          AS value
                    FROM Enrollments
                    WHERE CourseID = %s
                      AND Rating IS NOT NULL
                      AND EnrollmentDate >= DATE_SUB(CURRENT_DATE, INTERVAL 60 DAY)
                    GROUP BY date
                    ORDER BY date
                """, (course_id,))
                cr_trends = cursor.fetchall()

                # Completion via LectureResults (30 days)
                cursor.execute("""
                    SELECT
                        DATE_FORMAT(lr.Date, '%%Y-%%m-%%d') AS date,
                        COUNT(DISTINCT CASE WHEN e.Percentage = 100 THEN e.LearnerID END) AS completed,
                        COUNT(DISTINCT lr.LearnerID)                           AS total
                    FROM LectureResults lr
                    JOIN Enrollments e
                      ON lr.LearnerID = e.LearnerID AND lr.CourseID = e.CourseID
                    WHERE lr.CourseID = %s
                      AND lr.Date >= DATE_SUB(CURRENT_DATE, INTERVAL 30 DAY)
                    GROUP BY date
                    ORDER BY date
                """, (course_id,))
                comp_rows = cursor.fetchall()
                completion_trends = [
                    {
                        "date": r["date"],
                        "value": round(r["completed"] / r["total"] * 100, 1) if r["total"] else 0.0
                    }
                    for r in comp_rows
                ]

                # Lecture-level analytics
                cursor.execute("""
                    SELECT
                        l.LectureID                           AS lectureId,
                        l.Title                               AS lecture_title,
                        COUNT(DISTINCT lr.LearnerID)         AS total_attempts,
                        SUM(lr.State = 'passed')             AS passed_count,
                        COALESCE(AVG(lr.Score), 0)           AS average_score
                    FROM Lectures l
                    LEFT JOIN LectureResults lr
                      ON l.LectureID = lr.LectureID
                    WHERE l.CourseID = %s
                    GROUP BY l.LectureID, l.Title
                    ORDER BY l.LectureID
                """, (course_id,))
                lects = cursor.fetchall()
                lecture_analytics = [
                    {
                        "lectureId": l["lectureId"],
                        "title": l["lecture_title"],
                        "totalAttempts": l["total_attempts"],
                        "passedCount": l["passed_count"],
                        "passRate": round(l["passed_count"] / l["total_attempts"] * 100, 1)
                            if l["total_attempts"] else 0.0,
                        "averageScore": round(float(l["average_score"]), 1)
                    }
                    for l in lects
                ]

                # Student progress distribution
                cursor.execute("""
                    SELECT
                        CASE
                          WHEN Percentage = 0 THEN 'Not Started'
                          WHEN Percentage < 25 THEN '0-25%%'
                          WHEN Percentage < 50 THEN '25-50%%'
                          WHEN Percentage < 75 THEN '50-75%%'
                          WHEN Percentage < 100 THEN '75-99%%'
                          ELSE 'Completed'
                        END AS progress_range,
                        COUNT(*) AS student_count
                    FROM Enrollments
                    WHERE CourseID = %s
                    GROUP BY progress_range
                    ORDER BY
                      FIELD(progress_range,
                            'Not Started','0-25%%','25-50%%',
                            '50-75%%','75-99%%','Completed')
                """, (course_id,))
                pd = cursor.fetchall()
                progress = [
                    {"range": p["progress_range"], "count": p["student_count"]}
                    for p in pd
                ]

                dashboard_data["courseAnalytics"] = {
                    "courseId": course_id,
                    "courseName": course_name,
                    "totalEnrollments": total_enr,
                    "averageRating": round(float(cm.get("average_rating", 0)), 1),
                    "completionRate": comp_rate,
                    "enrollmentTrends": [
                        {"date": r["date"], "value": int(r["value"])}
                        for r in ce_trends
                    ],
                    "ratingTrends": [
                        {"date": r["date"], "value": round(float(r["value"]), 1)}
                        for r in cr_trends if r["value"] is not None
                    ],
                    "completionTrends": completion_trends,
                    "lectureAnalytics": lecture_analytics,
                    "studentProgress": progress
                }

            # 4) Return final payload
            return dashboard_data

    except HTTPException:
        raise
    except Exception as e:
        print(f"[ERROR] get_instructor_dashboard: {e}")
        raise HTTPException(status_code=500, detail="Internal server error")
    finally:
        if conn:
            conn.close()


# Quiz submission model
class QuizSubmission(BaseModel):
    answers: dict[int, str]  # questionId -> selected answer text

@router.post("/lectures/{lecture_id}/quiz/submit")
async def submit_quiz_answers(
    lecture_id: int,
    submission: QuizSubmission,
    request: Request,
    auth_token: str = Cookie(None)
):
    try:
        # Get token from header if not in cookie
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")

        # Verify token and get user data
        try:
            user_data = decode_token(auth_token)
            # Get LearnerID from Learners table using the username
            conn = connect_db()
            with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                cursor.execute("""
                    SELECT LearnerID 
                    FROM Learners 
                    WHERE AccountName = %s
                """, (user_data['username'],))
                learner = cursor.fetchone()
                if not learner:
                    raise HTTPException(status_code=404, detail="Learner not found")
                learner_id = learner['LearnerID']
        except Exception as e:
            print(f"Token/user verification error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token or user not found")

        try:
            with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                # First verify the quiz exists for this lecture
                cursor.execute("""
                    SELECT QuizID 
                    FROM Quizzes 
                    WHERE LectureID = %s
                """, (lecture_id,))
                quiz = cursor.fetchone()
                if not quiz:
                    raise HTTPException(status_code=404, detail="Quiz not found for this lecture")

                quiz_id = quiz['QuizID']

                # Get correct answers for validation
                cursor.execute("""
                    SELECT q.QuestionID, o.OptionText
                    FROM Questions q
                    JOIN Options o ON q.QuestionID = o.QuestionID
                    WHERE q.QuizID = %s AND o.IsCorrect = 1
                """, (quiz_id,))
                
                correct_answers = {row['QuestionID']: row['OptionText'] for row in cursor.fetchall()}
                
                # Calculate score
                total_questions = len(correct_answers)
                if total_questions == 0:
                    raise HTTPException(status_code=500, detail="No questions found for this quiz")

                correct_count = sum(
                    1 for q_id, answer in submission.answers.items()
                    if str(q_id) in map(str, correct_answers.keys()) and answer == correct_answers[int(q_id)]
                )
                
                score = (correct_count / total_questions) * 100

                # Get the CourseID for this lecture
                cursor.execute("""
                    SELECT CourseID
                    FROM Lectures
                    WHERE LectureID = %s
                """, (lecture_id,))
                lecture_data = cursor.fetchone()
                if not lecture_data:
                    raise HTTPException(status_code=404, detail="Lecture not found")
                
                course_id = lecture_data['CourseID']

                # Save or update the score using direct SQL instead of stored procedure
                try:
                    # Use stored procedure to update or insert the lecture result
                    cursor.execute(
                        "CALL sp_update_lecture_result(%s, %s, %s, %s)",
                        (learner_id, course_id, lecture_id, score)
                    )
                    
                    # Update course completion percentage
                    try:
                        # Get total lectures in the course
                        cursor.execute("""
                            SELECT COUNT(*) as total_lectures 
                            FROM Lectures 
                            WHERE CourseID = %s
                        """, (course_id,))
                        total_lectures = cursor.fetchone()['total_lectures']
                        
                        # Get passed lectures
                        cursor.execute("""
                            SELECT COUNT(*) as passed_lectures 
                            FROM LectureResults 
                            WHERE LearnerID = %s AND CourseID = %s AND State = 'passed'
                        """, (learner_id, course_id))
                        passed_lectures = cursor.fetchone()['passed_lectures']
                        
                        # Calculate percentage
                        if total_lectures > 0:
                            percentage_raw = (passed_lectures * 100.0) / total_lectures
                            
                            # Convert to percentage scale
                            if percentage_raw < 10:
                                percentage = 0
                            elif percentage_raw < 30:
                                percentage = 20
                            elif percentage_raw < 50:
                                percentage = 40
                            elif percentage_raw < 70:
                                percentage = 60
                            elif percentage_raw < 90:
                                percentage = 80
                            else:
                                percentage = 100
                                
                            # Update enrollment record
                            cursor.execute("""
                                UPDATE Enrollments
                                SET Percentage = %s
                                WHERE LearnerID = %s AND CourseID = %s
                            """, (percentage, learner_id, course_id))
                    except Exception as e:
                        print(f"Error updating course percentage: {str(e)}")
                        # Continue even if percentage update fails
                    
                    conn.commit()
                    print(f"Score updated successfully for learner {learner_id}, lecture {lecture_id}")
                except Exception as e:
                    print(f"Error saving quiz score: {str(e)}")
                    conn.rollback()
                    raise HTTPException(status_code=500, detail=f"Failed to save quiz score: {str(e)}")

                return {
                    "score": score,
                    "total_questions": total_questions,
                    "correct_answers": correct_count
                }

        finally:
            conn.close()

    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Error submitting quiz: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error submitting quiz: {str(e)}")

@router.get("/lectures/{lecture_id}/quiz/results")
async def get_quiz_results(
    lecture_id: int,
    request: Request,
    auth_token: str = Cookie(None)
):
    try:
        # Verify auth token
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
        
        if not auth_token:
            raise HTTPException(status_code=401, detail="No authentication token provided")
            
        try:
            user_data = decode_token(auth_token)
            user_id = user_data.get("id")
            
            # Create a cache key based on user ID and lecture ID
            cache_key = f"quiz:results:lecture:{lecture_id}:learner:{user_id}"
            
            # Define the database fetch function
            async def fetch_quiz_results_from_db():
                conn = connect_db()
                try:
                    with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                        cursor.execute("""
                            SELECT Score, State, Date
                            FROM LectureResults
                            WHERE LearnerID = %s AND LectureID = %s
                            ORDER BY Date DESC
                            LIMIT 1
                        """, (user_id, lecture_id))
                        
                        result = cursor.fetchone()
                        if not result:
                            return None
                            
                        return {
                            "score": float(result["Score"]),
                            "status": result["State"],
                            "date": result["Date"].isoformat()
                        }
                finally:
                    conn.close()
            
            # Use the caching mechanism to get the data
            # Short TTL since quiz results may change frequently
            return await get_cached_data(
                cache_key,
                fetch_quiz_results_from_db,
                ttl=300  # Cache for 5 minutes
            )
                
        except Exception as e:
            print(f"Token decode error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token")
            
    except HTTPException:
        raise
    except Exception as e:
        print(f"Error in get_quiz_results: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


# Get instructor course details
@router.get("/instructor/courses/{course_id}", response_model=Course)
async def get_instructor_course_details(
    request: Request,
    course_id: int,
    auth_token: str = Cookie(None)
):
    try:
        # Get token from header if not in cookie
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")
        
        # Verify token and get user data
        try:
            user_data = decode_token(auth_token)
            username = user_data['username']
            role = user_data['role']
            instructor_id = user_data.get('user_id')
            
            # Verify user is an instructor
            if role != "Instructor":
                raise HTTPException(status_code=403, detail="Only instructors can access this endpoint")
            
            # Connect to database
            conn = connect_db()
            
            with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                # Get instructor ID from token or fallback to database lookup
                if not instructor_id:
                    # Fallback for old tokens without user_id
                    cursor.execute("""
                        SELECT InstructorID 
                        FROM Instructors 
                        WHERE AccountName = %s
                    """, (username,))
                    
                    instructor = cursor.fetchone()
                    if not instructor:
                        raise HTTPException(status_code=404, detail="Instructor not found")
                    
                    instructor_id = instructor['InstructorID']
                
                # Get course details, ensuring it belongs to this instructor
                query = """
                    SELECT 
                        c.CourseID as id, 
                        c.CourseName as name, 
                        CONCAT(i.InstructorName, ' (', i.AccountName, ')') as instructor,
                        c.Descriptions as description,
                        (SELECT COUNT(*) FROM Enrollments WHERE CourseID = c.CourseID) as enrolled,
                        COALESCE(
                            (SELECT AVG(Rating) 
                             FROM Enrollments 
                             WHERE CourseID = c.CourseID AND Rating IS NOT NULL),
                            0
                        ) as rating,
                        c.Skills as skills,
                        c.Difficulty as difficulty,
                        c.EstimatedDuration as duration
                    FROM Courses c
                    JOIN Instructors i ON c.InstructorID = i.InstructorID
                    WHERE c.CourseID = %s AND c.InstructorID = %s
                """
                
                cursor.execute(query, (course_id, instructor_id))
                course = cursor.fetchone()
                
                if not course:
                    raise HTTPException(status_code=404, detail=f"Course with ID {course_id} not found or not owned by this instructor")
                
                # Format the course data
                if course['rating']:
                    course['rating'] = float(course['rating'])
                
                # Convert skills from JSON string if needed
                if isinstance(course.get('skills'), str):
                    try:
                        course['skills'] = json.loads(course['skills'])
                    except:
                        course['skills'] = []
                
                return course
                
        except Exception as e:
            print(f"Database error: {str(e)}")
            raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")
            
    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Error fetching instructor course details: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        if 'conn' in locals():
            conn.close()



# CreateLecture model and create_lecture endpoint to handle lecture creation with video upload and quiz
class CreateLecture(BaseModel):
    title: str
    description: str
    content: str
    quiz: Optional[dict] = None

@router.post("/courses/{course_id}/lectures")
async def create_lecture(
    request: Request,
    course_id: int,
    auth_token: str = Cookie(None),
    title: str = Form(...),
    description: str = Form(...),
    content: str = Form(...),
    video: Optional[UploadFile] = File(None),
    quiz: Optional[str] = Form(None)
):
    try:
        # Get token from header if not in cookie
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")
        
        # Verify token and get user data
        try:
            user_data = decode_token(auth_token)
            username = user_data['username']
            role = user_data['role']
            
            # Verify user is an instructor
            if role != "Instructor":
                raise HTTPException(status_code=403, detail="Only instructors can access this endpoint")
            
            # Connect to database
            conn = connect_db()
            cursor = conn.cursor(pymysql.cursors.DictCursor)
            
            try:
                # Get instructor ID from token or fallback to database lookup
                instructor_id = user_data.get('user_id')
                if not instructor_id:
                    # Fallback for old tokens without user_id
                    cursor.execute("""
                        SELECT InstructorID 
                        FROM Instructors 
                        WHERE AccountName = %s
                    """, (username,))
                    
                    instructor = cursor.fetchone()
                    if not instructor:
                        raise HTTPException(status_code=404, detail="Instructor not found")
                    
                    instructor_id = instructor['InstructorID']
                
                # Verify this instructor owns this course
                cursor.execute("""
                    SELECT CourseID 
                    FROM Courses 
                    WHERE CourseID = %s AND InstructorID = %s
                """, (course_id, instructor_id))
                

                
                if not cursor.fetchone():
                    raise HTTPException(status_code=403, detail="Not authorized to modify this course")
                
                # Create the lecture
                cursor.execute("""
                    INSERT INTO Lectures (CourseID, Title, Description, Content) 
                    VALUES (%s, %s, %s, %s)
                """, (course_id, title, description, content))
                
                # Get the newly created lecture ID
                lecture_id = cursor.lastrowid
                
                # Process quiz data first (faster database operations)
                quiz_id = None
                if quiz:
                    quiz_data = json.loads(quiz)
                    if quiz_data and quiz_data.get('questions'):
                        # Insert quiz
                        cursor.execute("""
                            INSERT INTO Quizzes (LectureID, Title, Description) 
                            VALUES (%s, %s, %s)
                        """, (lecture_id, f"Quiz for {title}", description))
                        
                        quiz_id = cursor.lastrowid
                        
                        # Batch insert questions and options for better performance
                        questions_to_insert = []
                        options_to_insert = []
                        
                        for question in quiz_data['questions']:
                            # Insert question first to get the ID
                            cursor.execute("""
                                INSERT INTO Questions (QuizID, QuestionText) 
                                VALUES (%s, %s)
                            """, (quiz_id, question['question']))
                            
                            question_id = cursor.lastrowid
                            
                            # Prepare batch options for this question
                            for i, option in enumerate(question['options']):
                                options_to_insert.append((
                                    question_id, 
                                    option, 
                                    i == question['correctAnswer']
                                ))
                        
                        # Batch insert all options at once
                        if options_to_insert:
                            cursor.executemany("""
                                INSERT INTO Options (QuestionID, OptionText, IsCorrect)
                                VALUES (%s, %s, %s)
                            """, options_to_insert)
                
                # Commit all database changes at once
                conn.commit()
                
                # Prepare response
                response = {
                    "id": lecture_id,
                    "title": title,
                    "message": "Lecture created successfully"
                }
                
                # Note: Video upload is now handled separately through upload_endpoints.py
                # This separates concerns and allows for better error handling and chunked uploads
                if video:
                    response["note"] = "Lecture created successfully. Please use the dedicated upload endpoints for video upload."
                
                
                # Invalidate cache patterns in background (non-blocking)
                def background_cache_invalidation():
                    try:
                        # Clear course-specific caches
                        invalidate_cache_pattern(f"courses:id:{course_id}:*")
                        invalidate_cache_pattern(f"instructor:courses:*")
                        # Clear lecture cache if it exists
                        invalidate_cache_pattern(f"lectures:id:*")
                        print(f"Cache invalidation completed for course {course_id}")
                    except Exception as cache_error:
                        print(f"Background cache invalidation failed: {str(cache_error)}")
                
                # Start background cache invalidation
                cache_thread = threading.Thread(target=background_cache_invalidation)
                cache_thread.daemon = True
                cache_thread.start()
                
                return response
                
            except HTTPException:
                raise
            except Exception as e:
                print(f"Error in create_lecture: {str(e)}")
                raise HTTPException(status_code=500, detail=f"Failed to create lecture: {str(e)}")
            
        except Exception as e:
            print(f"Token/user verification error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token or user not found")
            
    except HTTPException:
        raise
    except Exception as e:
        print(f"Error in create_lecture: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        if 'conn' in locals():
            conn.close()

# Optimized preview endpoint for CoursePreview.js - combines course + lectures
@router.get("/courses/{course_id}/preview")
async def get_course_preview_data(course_id: int, request: Request, auth_token: str = Cookie(None)):
    try:
        # Authentication
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
        
        if not auth_token:
            raise HTTPException(status_code=401, detail="No authentication token provided")
        
        try:
            user_data = decode_token(auth_token)
            user_id = user_data.get('user_id')
        except Exception as e:
            print(f"Token decode error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token")
        
        # Cache key for combined preview data
        cache_key = f"course:preview:{course_id}:user:{user_id}"
        
        # Fetch all data in one optimized query
        async def fetch_preview_data_from_db():
            conn = connect_db()
            try:
                with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                    # Get course details with enrollment status
                    course_query = """
                    SELECT 
                        c.CourseID as id,
                        c.CourseName as name,
                        c.Descriptions as description,
                        c.EstimatedDuration as duration,
                        c.Skills as skills,
                        c.Difficulty as difficulty,
                        CONCAT(i.InstructorName, ' (', i.AccountName, ')') as instructor,
                        i.InstructorID as instructor_id,
                        COALESCE(enrollment_stats.enrolled, 0) as enrolled,
                        COALESCE(rating_stats.avg_rating, NULL) as rating,
                        CASE WHEN user_enrollment.LearnerID IS NOT NULL THEN TRUE ELSE FALSE END as is_enrolled,
                        user_enrollment.Rating as user_rating
                    FROM Courses c
                    JOIN Instructors i ON c.InstructorID = i.InstructorID
                    LEFT JOIN (
                        SELECT CourseID, COUNT(*) as enrolled
                        FROM Enrollments GROUP BY CourseID
                    ) enrollment_stats ON c.CourseID = enrollment_stats.CourseID
                    LEFT JOIN (
                        SELECT CourseID, AVG(Rating) as avg_rating
                        FROM Enrollments WHERE Rating IS NOT NULL GROUP BY CourseID
                    ) rating_stats ON c.CourseID = rating_stats.CourseID
                    LEFT JOIN (
                        SELECT e2.CourseID, e2.LearnerID, e2.Rating
                        FROM Enrollments e2
                        JOIN Learners l ON e2.LearnerID = l.LearnerID
                        WHERE l.LearnerID = %s
                    ) user_enrollment ON c.CourseID = user_enrollment.CourseID
                    WHERE c.CourseID = %s
                    """
                    
                    cursor.execute(course_query, (user_id, course_id))
                    course = cursor.fetchone()
                    
                    if not course:
                        raise HTTPException(status_code=404, detail="Course not found")
                    
                    # Get lectures for this course
                    lectures_query = """
                    SELECT 
                        LectureID as id,
                        Title as title,
                        Description as description
                    FROM Lectures
                    WHERE CourseID = %s
                    ORDER BY LectureID ASC
                    """
                    
                    cursor.execute(lectures_query, (course_id,))
                    lectures = cursor.fetchall()
                    
                    # Format skills if it's JSON
                    skills = []
                    if course['skills']:
                        try:
                            skills = json.loads(course['skills'])
                        except:
                            skills = []
                    
                    # Format the response
                    return {
                        'course': {
                            'id': course['id'],
                            'name': course['name'],
                            'description': course['description'],
                            'duration': course['duration'],
                            'skills': skills,
                            'difficulty': course['difficulty'],
                            'instructor': course['instructor'],
                            'instructor_id': course['instructor_id'],
                            'enrolled': course['enrolled'],
                            'rating': float(course['rating']) if course['rating'] else None,
                            'is_enrolled': course['is_enrolled'],
                            'user_rating': int(course['user_rating']) if course['user_rating'] else None
                        },
                        'lectures': [
                            {
                                'id': lecture['id'],
                                'title': lecture['title'],
                                'description': lecture['description']
                            }
                            for lecture in lectures
                        ]
                    }
            finally:
                conn.close()
        
        # Use caching with shorter TTL since it includes user-specific data
        return await get_cached_data(
            cache_key,
            fetch_preview_data_from_db,
            ttl=900,  # 15 minutes for user-specific data
            use_compression=True
        )
        
    except HTTPException:
        raise
    except Exception as e:
        print(f"Error in get_course_preview_data: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))

# Debug endpoint for instructor to list their courses - no caching, direct DB access
@router.get("/instructor/debug/my-courses")
async def debug_my_courses(
    request: Request,
    auth_token: str = Cookie(None)
):
    try:
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")
        
        user_data = decode_token(auth_token)
        username = user_data['username']
        role = user_data['role']
        instructor_id = user_data.get('user_id')
        
        if role != "Instructor":
            raise HTTPException(status_code=403, detail="Only instructors can access this endpoint")
        
        conn = connect_db()
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            if not instructor_id:
                cursor.execute("""
                    SELECT InstructorID 
                    FROM Instructors 
                    WHERE AccountName = %s
                """, (username,))
                
                instructor = cursor.fetchone()
                if not instructor:
                    raise HTTPException(status_code=404, detail="Instructor not found")
                
                instructor_id = instructor['InstructorID']
            
            cursor.execute("""
                SELECT CourseID, CourseName, InstructorID
                FROM Courses 
                WHERE InstructorID = %s
                ORDER BY CourseID
            """, (instructor_id,))
            
            courses = cursor.fetchall()
            
            return {
                "instructor_id": instructor_id,
                "username": username,
                "courses": courses,
                "course_count": len(courses)
            }
            
    except Exception as e:
        print(f"Debug error: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))
    finally:
        if 'conn' in locals():
            conn.close()

# Get enrolled learners for a specific course (instructor only)
@router.get("/instructor/courses/{course_id}/enrollments")
async def get_course_enrollments(
    course_id: int,
    request: Request,
    auth_token: str = Cookie(None)
):
    try:
        # Get token from header if not in cookie
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")
        
        # Verify token and get user data
        user_data = decode_token(auth_token)
        username = user_data['username']
        role = user_data['role']
        instructor_id = user_data.get('user_id')
        
        # Verify user is an instructor
        if role != "Instructor":
            raise HTTPException(status_code=403, detail="Only instructors can access this endpoint")
        
        conn = connect_db()
        
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            # Get instructor ID if not in token
            if not instructor_id:
                cursor.execute("""
                    SELECT InstructorID 
                    FROM Instructors 
                    WHERE AccountName = %s
                """, (username,))
                
                instructor = cursor.fetchone()
                if not instructor:
                    raise HTTPException(status_code=404, detail="Instructor not found")
                
                instructor_id = instructor['InstructorID']
            
            # Verify the course belongs to this instructor
            cursor.execute("""
                SELECT CourseID, CourseName
                FROM Courses 
                WHERE CourseID = %s AND InstructorID = %s
            """, (course_id, instructor_id))
            
            course = cursor.fetchone()
            if not course:
                raise HTTPException(status_code=404, detail="Course not found or you don't have permission to access it")
            
            # Get enrolled learners with their enrollment details
            cursor.execute("""
                SELECT 
                    l.LearnerID,
                    l.LearnerName,
                    l.Email,
                    e.EnrollmentDate,
                    COALESCE(e.Percentage, 0) as progress,
                    COALESCE(e.Rating, 0) as rating
                FROM Enrollments e
                JOIN Learners l ON e.LearnerID = l.LearnerID
                WHERE e.CourseID = %s
                ORDER BY e.EnrollmentDate DESC
            """, (course_id,))
            
            enrollments = cursor.fetchall()
            
            # Calculate completion rate
            total_enrollments = len(enrollments)
            completed_enrollments = sum(1 for e in enrollments if e['progress'] == 100)
            completion_rate = (completed_enrollments / total_enrollments * 100) if total_enrollments > 0 else 0
            
            # Format the data for the frontend
            formatted_enrollments = []
            for enrollment in enrollments:
                formatted_enrollments.append({
                    'learner_id': enrollment['LearnerID'],
                    'learner_name': enrollment['LearnerName'],
                    'email': enrollment['Email'],
                    'enrollment_date': enrollment['EnrollmentDate'].strftime('%b %d, %Y') if enrollment['EnrollmentDate'] else 'N/A',
                    'progress': enrollment['progress'],
                    'rating': enrollment['rating']
                })
            
            return {
                'course_id': course_id,
                'course_name': course['CourseName'],
                'total_enrollments': total_enrollments,
                'completion_rate': round(completion_rate, 1),
                'enrollments': formatted_enrollments
            }
            
    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Error fetching course enrollments: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error fetching course enrollments: {str(e)}")
    finally:
        if 'conn' in locals():
            conn.close()

# Rating submission model
class RatingSubmission(BaseModel):
    rating: int = Field(..., ge=1, le=5, description="Rating value between 1 and 5")

# Submit rating for a course
@router.put("/courses/{course_id}/rating")
async def submit_course_rating(
    course_id: int,
    rating_data: RatingSubmission,
    request: Request,
    auth_token: str = Cookie(None)
):
    try:
        # Get token from header if not in cookie
        if not auth_token:
            auth_header = request.headers.get('Authorization')
            if auth_header and auth_header.startswith('Bearer '):
                auth_token = auth_header.split(' ')[1]
            else:
                raise HTTPException(status_code=401, detail="No authentication token provided")
        
        # Verify token and get user data
        try:
            user_data = decode_token(auth_token)
            learner_id = user_data.get('user_id')
            
            if not learner_id:
                # Fallback for old tokens without user_id - do database lookup
                conn = connect_db()
                with conn.cursor(pymysql.cursors.DictCursor) as cursor:
                    cursor.execute("""
                        SELECT LearnerID 
                        FROM Learners 
                        WHERE AccountName = %s
                    """, (user_data['username'],))
                    learner = cursor.fetchone()
                    if not learner:
                        raise HTTPException(status_code=404, detail="Learner not found")
                    learner_id = learner['LearnerID']
            else:
                # Use user_id from token
                conn = connect_db()
        except Exception as e:
            print(f"Token/user verification error: {str(e)}")
            raise HTTPException(status_code=401, detail="Invalid authentication token or user not found")

        # Check if the course exists and user is enrolled
        with conn.cursor(pymysql.cursors.DictCursor) as cursor:
            cursor.execute("""
                SELECT e.EnrollmentID 
                FROM Enrollments e
                JOIN Courses c ON e.CourseID = c.CourseID
                WHERE e.CourseID = %s AND e.LearnerID = %s
            """, (course_id, learner_id))
            enrollment = cursor.fetchone()
            if not enrollment:
                raise HTTPException(status_code=404, detail="Course not found or you are not enrolled")
            
            # Update the rating in the Enrollments table
            try:
                cursor.execute("""
                    UPDATE Enrollments
                    SET Rating = %s
                    WHERE CourseID = %s AND LearnerID = %s
                """, (rating_data.rating, course_id, learner_id))
                
                conn.commit()
                
                # Invalidate cache for course rating data
                redis_client = get_redis_client()
                pattern_course = f"courses:id:{course_id}:*"
                pattern_preview = f"course:preview:{course_id}:*"
                print(f"Invalidating cache patterns: {pattern_course}, {pattern_preview}")
                invalidate_cache_pattern(pattern_course)
                invalidate_cache_pattern(pattern_preview)
                
                return {"message": "Rating submitted successfully", "rating": rating_data.rating}
            except Exception as e:
                conn.rollback()
                print(f"Error updating rating: {str(e)}")
                raise HTTPException(status_code=500, detail=f"Failed to submit rating: {str(e)}")
        
    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Error submitting rating: {str(e)}")
        raise HTTPException(status_code=500, detail=f"Error submitting rating: {str(e)}")
    finally:
        if 'conn' in locals():
            conn.close()