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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
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
from collections import defaultdict
import json
import random
import requests
import streamlit as st
from datetime import datetime, timedelta
from youtube_transcript_api import YouTubeTranscriptApi
from utils.helpers import display_progress_bar, create_notification, format_datetime
from file_upload_vectorize import upload_resource, extract_text_from_file, create_vector_store, resources_collection, model, assignment_submit
from db import courses_collection2, chat_history_collection, students_collection, faculty_collection, vectors_collection
from chatbot import give_chat_response
from bson import ObjectId
from live_polls import LivePollFeature
import pandas as pd
import plotly.express as px
from dotenv import load_dotenv
import os
from pymongo import MongoClient
from gen_mcqs import (
    generate_mcqs,
    save_pre_class_quiz,
    save_quiz,
    save_surprise_quiz,
    quizzes_collection,
    surprise_quizzes_collection,
    get_student_quiz_score,
    get_student_surprise_quiz_score,
    submit_quiz_answers,
    submit_surprise_quiz_answers
)
from create_course import courses_collection
# from pre_class_analytics import NovaScholarAnalytics
from pre_class_analytics2 import NovaScholarAnalytics
import openai
from openai import OpenAI
import google.generativeai as genai
from google.generativeai import caching
from goals2 import GoalAnalyzer
from openai import OpenAI
import asyncio
import numpy as np
import re
from analytics import derive_analytics, create_embeddings, cosine_similarity
from bs4 import BeautifulSoup
import streamlit.components.v1 as components
from live_chat_feature import display_live_chat_interface 
from code_playground import display_code_playground
from urllib.parse import urlparse, parse_qs
from bs4 import BeautifulSoup
from rubrics import display_rubrics_tab
from subjective_test_evaluation import evaluate_subjective_answers, display_evaluation_to_faculty

# Load environment variables
load_dotenv()
MONGO_URI = os.getenv('MONGO_URI')
PERPLEXITY_API_KEY = os.getenv('PERPLEXITY_KEY')
OPENAI_API_KEY = os.getenv('OPENAI_KEY')
client = MongoClient(MONGO_URI)
db = client["novascholar_db"]
polls_collection = db["polls"]
subjective_tests_collection = db["subjective_tests"]
subjective_test_evaluation_collection = db["subjective_test_evaluation"]
assignment_evaluation_collection = db["assignment_evaluation"]
subjective_tests_collection = db["subjective_tests"]
synoptic_store_collection = db["synoptic_store"]
assignments_collection = db["assignments"]
pre_subjective_test_evaluation_collection = db["pre_subjective_test_evaluation"]
pre_subjective_tests_collection = db["pre_subjective_tests"]
chat_time_collection = db["chat_time"]

# for implementing Context Caching: 
# PROJECT_ID = "novascholar-446709"
# vertexai.init(project=PROJECT_ID, location="us-west4")

def get_current_user():
    if 'current_user' not in st.session_state:
        return None
    return students_collection.find_one({"_id": st.session_state.user_id})

# def display_preclass_content(session, student_id, course_id):
    """Display pre-class materials for a session"""
    
    # Initialize 'messages' in session_state if it doesn't exist
    if 'messages' not in st.session_state:
        st.session_state.messages = []
        
    # Display pre-class materials
    materials = list(resources_collection.find({"course_id": course_id, "session_id": session['session_id']}))
    st.subheader("Pre-class Materials")
    
    if materials:
        for material in materials:
            with st.expander(f"{material['file_name']} ({material['material_type'].upper()})"):
                file_type = material.get('file_type', 'unknown')
                if file_type == 'application/pdf':
                    st.markdown(f"πŸ“‘ [Open PDF Document]({material['file_name']})")
                    if st.button("View PDF", key=f"view_pdf_{material['file_name']}"):
                        st.text_area("PDF Content", material['text_content'], height=300)
                    if st.button("Download PDF", key=f"download_pdf_{material['file_name']}"):
                        st.download_button(
                            label="Download PDF",
                            data=material['file_content'],
                            file_name=material['file_name'],
                            mime='application/pdf'
                        )
                    if st.button("Mark PDF as Read", key=f"pdf_{material['file_name']}"):
                        create_notification("PDF marked as read!", "success")
    else:
        st.info("No pre-class materials uploaded by the faculty.")
        st.subheader("Upload Pre-class Material")
        
        # File upload section for students
        uploaded_file = st.file_uploader("Upload Material", type=['txt', 'pdf', 'docx'])
        if uploaded_file is not None:
            with st.spinner("Processing document..."):
                file_name = uploaded_file.name
                file_content = extract_text_from_file(uploaded_file)
                if file_content:
                    material_type = st.selectbox("Select Material Type", ["pdf", "docx", "txt"])
                    if st.button("Upload Material"):
                        upload_resource(course_id, session['session_id'], file_name, uploaded_file, material_type)

                        # Search for the newly uploaded resource's _id in resources_collection
                        resource_id = resources_collection.find_one({"file_name": file_name})["_id"]
                        create_vector_store(file_content, resource_id)
                        st.success("Material uploaded successfully!")
        
    st.subheader("Learn the Topic Using Chatbot")
    st.write(f"**Session Title:** {session['title']}")
    st.write(f"**Description:** {session.get('description', 'No description available.')}")
    
    # Chatbot interface
    if prompt := st.chat_input("Ask a question about the session topic"):
        if len(st.session_state.messages) >= 20:
            st.warning("Message limit (20) reached for this session.")
            return

        st.session_state.messages.append({"role": "user", "content": prompt})
        
        # Display User Message
        with st.chat_message("user"):
            st.markdown(prompt)
        
        # Get response from chatbot
        context = ""
        for material in materials:
            if 'text_content' in material:
                context += material['text_content'] + "\n"
        
        response = give_chat_response(student_id, session['session_id'], prompt, session['title'], session.get('description', ''), context)
        st.session_state.messages.append({"role": "assistant", "content": response})
        
        # Display Assistant Response
        with st.chat_message("assistant"):
            st.markdown(response)
    
    # st.subheader("Your Chat History")
    # for message in st.session_state.messages:
    #     content = message.get("content", "")  # Default to an empty string if "content" is not present
    #     role = message.get("role", "user")  # Default to "user" if "role" is not present
    #     with st.chat_message(role):
    #         st.markdown(content)
    # user = get_current_user()
    
def display_preclass_content(session, student_id, course_id):
    """Display pre-class materials for a session including external resources"""
    st.subheader("Pre-class Materials")
    print("Session ID is: ", session['session_id'])

    # Add session state variables for chat timing
    if "chat_session_start" not in st.session_state:
        st.session_state.chat_session_start = None
    if "chat_session_active" not in st.session_state:
        st.session_state.chat_session_active = False
    
    # Display uploaded materials
    materials = resources_collection.find({"session_id": session['session_id']})
    
    for material in materials:
        file_type = material.get('file_type', 'unknown')
        
        # Handle external resources
        if file_type == 'external' or file_type == 'video':
            with st.expander(f"πŸ“Œ {material['file_name']}"):
                st.markdown(f"Source: [{material['source_url']}]({material['source_url']})")
                
                if material['material_type'].lower() == 'video':
                    # Embed YouTube video if it's a YouTube URL
                    if 'youtube.com' in material['source_url'] or 'youtu.be' in material['source_url']:
                        video_id = extract_youtube_id(material['source_url'])
                        if video_id:
                            st.video(f"https://youtube.com/watch?v={video_id}")
                
                if st.button("View Content", key=f"view_external_{material['_id']}"):
                    st.text_area("Extracted Content", material['text_content'], height=300)
                
                if st.button("Mark as Read", key=f"external_{material['_id']}"):
                    create_notification(f"{material['material_type']} content marked as read!", "success")
        
        # Handle traditional file types
        else:
            with st.expander(f"{material['file_name']} ({material['material_type'].upper()})"):
                if file_type == 'application/pdf':
                    st.markdown(f"πŸ“‘ [Open PDF Document]({material['file_name']})")
                    if st.button("View PDF", key=f"view_pdf_{material['_id']}"):
                        st.text_area("PDF Content", material['text_content'], height=300)
                    if st.button("Download PDF", key=f"download_pdf_{material['_id']}"):
                        st.download_button(
                            label="Download PDF",
                            data=material['file_content'],
                            file_name=material['file_name'],
                            mime='application/pdf'
                        )
                    if st.button("Mark PDF as Read", key=f"pdf_{material['_id']}"):
                        create_notification("PDF marked as read!", "success")
                
                elif file_type == 'text/plain':
                    st.markdown(f"πŸ“„ [Open Text Document]({material['file_name']})")
                    if st.button("View Text", key=f"view_text_{material['_id']}"):
                        st.text_area("Text Content", material['text_content'], height=300)
                    if st.button("Download Text", key=f"download_text_{material['_id']}"):
                        st.download_button(
                            label="Download Text",
                            data=material['file_content'],
                            file_name=material['file_name'],
                            mime='text/plain'
                        )
                    if st.button("Mark Text as Read", key=f"text_{material['_id']}"):
                        create_notification("Text marked as read!", "success")
                
                elif file_type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document':
                    st.markdown(f"πŸ“„ [Open Word Document]({material['file_name']})")
                    if st.button("View Word", key=f"view_word_{material['_id']}"):
                        st.text_area("Word Content", material['text_content'], height=300)
                    if st.button("Download Word", key=f"download_word_{material['_id']}"):
                        st.download_button(
                            label="Download Word",
                            data=material['file_content'],
                            file_name=material['file_name'],
                            mime='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
                        )
                    if st.button("Mark Word as Read", key=f"word_{material['_id']}"):
                        create_notification("Word document marked as read!", "success")
                
                elif file_type == 'application/vnd.openxmlformats-officedocument.presentationml.presentation':
                    st.markdown(f"πŸ“Š [Open PowerPoint Presentation]({material['file_name']})")
                    if st.button("View PowerPoint", key=f"view_pptx_{material['_id']}"):
                        st.text_area("PowerPoint Content", material['text_content'], height=300)
                    if st.button("Download PowerPoint", key=f"download_pptx_{material['_id']}"):
                        st.download_button(
                            label="Download PowerPoint",
                            data=material['file_content'],
                            file_name=material['file_name'],
                            mime='application/vnd.openxmlformats-officedocument.presentationml.presentation'
                        )
                    if st.button("Mark PowerPoint as Read", key=f"pptx_{material['_id']}"):
                        create_notification("PowerPoint presentation marked as read!", "success")
                
                elif file_type == 'web_resource': 
                    # Display resource details
                    st.markdown(f"**Type:** {material['material_type']}")
                    if material.get('description'):
                        st.markdown(f"**Description:** {material['description']}")
                    
                    # Display resource link
                    st.markdown(f"**Resource Link:** [{material['file_name']}]({material['source_url']})")
                    
                    # Add "Open in New Tab" button
                    if st.button("Open in New Tab", key=f"open_{material['_id']}"):
                        # Use JavaScript to open in new tab
                        st.markdown(f"""
                            <script>
                            window.open('{material['source_url']}', '_blank');
                            </script>
                            """, unsafe_allow_html=True)
                    
                    # Add "Mark as Read" functionality
                    if st.button("Mark as Read", key=f"read_{material['_id']}"):
                        create_notification(f"{material['material_type']} marked as read!", "success")


    # Initialize 'messages' in session_state if it doesn't exist
    if 'messages' not in st.session_state:
        st.session_state.messages = []

    if 'chat_session_active' not in st.session_state:
        st.session_state.chat_session_active = False
    if 'chat_session_start' not in st.session_state:
        st.session_state.chat_session_start = None

    # Chat input
    # Add a check, if materials are available, only then show the chat input
    if st.session_state.user_type == "student":
        if materials:
            # Start chat session button
            chat_time = chat_time_collection.find_one(
                {"session_id": session["session_id"], "user_id": student_id, "course_id": course_id}
            )

            # Calculate session status and time remaining
            current_time = datetime.now()
            chat_active = False
            time_remaining = None

            if chat_time and "start_time" in chat_time:
                session_end_time = chat_time["start_time"] + timedelta(minutes=20)
                time_remaining = session_end_time - current_time
                chat_active = time_remaining.total_seconds() > 0

            # Display appropriate interface based on session status
            if not chat_time or "start_time" not in chat_time:
                # New session case
                if st.button("Start Chat Session (20 minutes)"):
                    st.session_state.chat_session_start = current_time
                    st.session_state.chat_session_active = True
                    
                    # Update database
                    chat_time_collection.update_one(
                        {
                            "session_id": session["session_id"],
                            "user_id": student_id,
                            "course_id": course_id
                        },
                        {
                            "$set": {
                                "start_time": current_time,
                                "end_time": current_time + timedelta(minutes=20)
                            }
                        },
                        upsert=True
                    )
                    st.rerun()

            elif chat_active:
                # Active session case
                minutes = int(time_remaining.total_seconds() // 60)
                seconds = int(time_remaining.total_seconds() % 60)
                st.info(f"⏱️ Time remaining: {minutes:02d}:{seconds:02d}")

                # Show chat input
                if prompt := st.chat_input("Ask a question about Pre-class Materials"):
                    st.session_state.messages.append({"role": "user", "content": prompt})

                    # Display User Message
                    with st.chat_message("user"):
                        st.markdown(prompt)
                    
                    try:
                        context = get_chat_context(session['session_id'])
                        try:
                            context_prompt = f"""
                            You are a highly intelligent and resourceful assistant capable of synthesizing information from the provided context and external sources.

                            Context:
                            {context}

                            Instructions:
                            1. Base your answers on the provided context wherever possible.
                            2. If the answer to the user's question is not explicitly in the context:
                            - Use external knowledge or web assistance to provide a clear and accurate response.
                            3. Do not respond negatively. If the answer is not in the context, use web assistance or your knowledge to generate a thoughtful response.
                            4. Clearly state if part of your response relies on web assistance.

                            Question: {prompt}

                            Please provide a clear and comprehensive answer based on the above instructions.
                            """

                            response = model.generate_content(context_prompt)
                            if not response or not response.text:
                                st.error("No response received from the model")
                                return

                            assistant_response = response.text
                            # Display Assistant Response
                            with st.chat_message("assistant"):
                                st.markdown(assistant_response)

                            # Build the message
                            new_message = {
                                "prompt": prompt,
                                "response": assistant_response,
                                "timestamp": datetime.utcnow(),
                            }
                            st.session_state.messages.append(new_message)

                            # Update database
                            try:
                                chat_history_collection.update_one(
                                    {
                                        "user_id": student_id,
                                        "session_id": session["session_id"],
                                    },
                                    {
                                        "$push": {"messages": new_message},
                                        "$setOnInsert": {
                                            "user_id": student_id,
                                            "session_id": session["session_id"],
                                            "timestamp": datetime.utcnow(),
                                        },
                                    },
                                    upsert=True,
                                )
                                chat_time_collection.update_one(
                                    {"session_id": session["session_id"], "user_id": student_id, "course_id": course_id},
                                    {"$set": {"end_time": datetime.now()}},
                                    upsert=True
                                )
                            except Exception as db_error:
                                st.error(f"Error saving chat history: {str(db_error)}")
                        except Exception as e:
                            st.error(f"Error generating response: {str(e)}")
                    except Exception as e:
                        st.error(f"Error processing message: {str(e)}")
            
            else:
                # Expired session case
                st.info("Chat session has ended. Time limit (20 minutes) reached.")


            # start_time = chat_time["start_time"] if chat_time and "start_time" in chat_time else None
            # print("Start Time is: ", start_time)
            # if start_time is None:
            #     if st.button("Start Chat Session (20 minutes)"):
            #         st.session_state.chat_session_start = datetime.now()
            #         chat_time_collection.update_one(
            #             {"session_id": session["session_id"], "user_id": student_id, "course_id": course_id},
            #             {"$set": {"start_time": st.session_state.chat_session_start}},
            #             upsert=True
            #         )
            #         st.session_state.chat_session_active = True
            #         st.rerun()
            # else:
            #     st.info("Chat session is now disabled.")

            # # Check if chat session is active and within time limit
            # chat_time = chat_time_collection.find_one(
            #     {"session_id": session["session_id"], "user_id": student_id, "course_id": course_id}
            # )
            # cond = False
            # if chat_time is None or "start_time" not in chat_time or (chat_time["start_time"] + timedelta(minutes=20)) <= datetime.now():
            #     cond = True

            # if st.session_state.chat_session_active and st.session_state.chat_session_start and not cond:
            #     current_time = datetime.now()
            #     time_elapsed = current_time - chat_time["start_time"]
            #     time_remaining = timedelta(minutes=20) - time_elapsed

            #     if time_remaining.total_seconds() > 0:
            #         # Display remaining time
            #         st.info(f"Time remaining: {int(time_remaining.total_seconds() // 60)} minutes and {int(time_remaining.total_seconds() % 60)} seconds")
                    
            #         # Show chat input
            #         if prompt := st.chat_input("Ask a question about Pre-class Materials"):
            #             st.session_state.messages.append({"role": "user", "content": prompt})

            #             # Display User Message
            #             with st.chat_message("user"):
            #                 st.markdown(prompt)

            #             # Get document context
            #             context = ""
            #             print("Session ID is: ", session["session_id"])
            #             materials = resources_collection.find(
            #                 {"session_id": session["session_id"]}
            #             )
            #             print(materials)
            #             context = ""
            #             vector_data = None

            #             # for material in materials:
            #             #     print(material)
            #             context = ""
            #             for material in materials:
            #                 resource_id = material["_id"]
            #                 print("Supposed Resource ID is: ", resource_id)
            #                 vector_data = vectors_collection.find_one(
            #                     {"resource_id": resource_id}
            #                 )
            #                 # print(vector_data)
            #                 if vector_data and "text" in vector_data:
            #                     context += vector_data["text"] + "\n"

            #             if not vector_data:
            #                 st.error("No Pre-class materials found for this session.")
            #                 return

            #             try:
            #                 # Generate response using Gemini
            #                 # context_prompt = f"""
            #                 # Based on the following context, answer the user's question:

            #                 # Context:
            #                 # {context}

            #                 # Question: {prompt}

            #                 # Please provide a clear and concise answer based only on the information provided in the context.
            #                 # """
            #                 # context_prompt = f"""
            #                 # You are a highly intelligent and resourceful assistant capable of synthesizing information from the provided context.

            #                 # Context:
            #                 # {context}

            #                 # Instructions:
            #                 # 1. Base your answers primarily on the given context.
            #                 # 2. If the answer to the user's question is not explicitly in the context but can be inferred or synthesized from the information provided, do so thoughtfully.
            #                 # 3. Only use external knowledge or web assistance when:
            #                 # - The context lacks sufficient information, and
            #                 # - The question requires knowledge beyond what can be reasonably inferred from the context.
            #                 # 4. Clearly state if you are relying on web assistance for any part of your answer.
            #                 # 5. Do not respond with a negative. If the answer is not in the context, provide a thoughtful response based on the information available on the web about it.

            #                 # Question: {prompt}

            #                 # Please provide a clear and comprehensive answer based on the above instructions.
            #                 # """
            #                 context_prompt = f"""
            #                 You are a highly intelligent and resourceful assistant capable of synthesizing information from the provided context and external sources.

            #                 Context:
            #                 {context}

            #                 Instructions:
            #                 1. Base your answers on the provided context wherever possible.
            #                 2. If the answer to the user's question is not explicitly in the context:
            #                 - Use external knowledge or web assistance to provide a clear and accurate response.
            #                 3. Do not respond negatively. If the answer is not in the context, use web assistance or your knowledge to generate a thoughtful response.
            #                 4. Clearly state if part of your response relies on web assistance.

            #                 Question: {prompt}

            #                 Please provide a clear and comprehensive answer based on the above instructions.
            #                 """

            #                 response = model.generate_content(context_prompt)
            #                 if not response or not response.text:
            #                     st.error("No response received from the model")
            #                     return

            #                 assistant_response = response.text
            #                 # Display Assistant Response
            #                 with st.chat_message("assistant"):
            #                     st.markdown(assistant_response)

            #                 # Build the message
            #                 new_message = {
            #                     "prompt": prompt,
            #                     "response": assistant_response,
            #                     "timestamp": datetime.utcnow(),
            #                 }
            #                 st.session_state.messages.append(new_message)

            #                 # Update database
            #                 try:
            #                     chat_history_collection.update_one(
            #                         {
            #                             "user_id": student_id,
            #                             "session_id": session["session_id"],
            #                         },
            #                         {
            #                             "$push": {"messages": new_message},
            #                             "$setOnInsert": {
            #                                 "user_id": student_id,
            #                                 "session_id": session["session_id"],
            #                                 "timestamp": datetime.utcnow(),
            #                             },
            #                         },
            #                         upsert=True,
            #                     )
            #                     chat_time_collection.update_one(
            #                         {"session_id": session["session_id"], "user_id": student_id, "course_id": course_id},
            #                         {"$set": {"end_time": datetime.now()}},
            #                         upsert=True
            #                     )
            #                 except Exception as db_error:
            #                     st.error(f"Error saving chat history: {str(db_error)}")
            #             except Exception as e:
            #                 st.error(f"Error generating response: {str(e)}")
            #     else:
            #         st.warning("Chat session has expired. The 20-minute time limit has been reached.")
            #         st.session_state.chat_session_active = False
            #         st.session_state.chat_session_start = None

    else:
        st.subheader("Upload Pre-class Material")
        # File upload section for students
        uploaded_file = st.file_uploader("Upload Material", type=['txt', 'pdf', 'docx'])
        if uploaded_file is not None:
            with st.spinner("Processing document..."):
                file_name = uploaded_file.name
                file_content = extract_text_from_file(uploaded_file)
                if file_content:
                    material_type = st.selectbox("Select Material Type", ["pdf", "docx", "txt"])
                    if st.button("Upload Material"):
                        upload_resource(course_id, session['session_id'], file_name, uploaded_file, material_type)
                        # print("Resource ID is: ", resource_id)
                        # Search for the newly uploaded resource's _id in resources_collection
                        # resource_id = resources_collection.find_one({"file_name": file_name})["_id"]
                        st.success("Material uploaded successfully!")
                        # st.experimental_rerun()
    # st.subheader("Your Chat History")
    if st.button("View Chat History"):
        # Initialize chat messages from database
        if 'messages' not in st.session_state or not st.session_state.messages:
            existing_chat = chat_history_collection.find_one({
                "user_id": student_id,
                "session_id": session['session_id']
            })
            if existing_chat and 'messages' in existing_chat:
                st.session_state.messages = existing_chat['messages']
            else:
                st.session_state.messages = []

        # Display existing chat history
        try:
            for message in st.session_state.messages:
                if 'prompt' in message and 'response' in message:
                    with st.chat_message("user"):
                        st.markdown(message["prompt"])
                    with st.chat_message("assistant"):
                        st.markdown(message["response"])
        except Exception as e:
            st.error(f"Error displaying chat history: {str(e)}")
            st.session_state.messages = []
    
    if st.session_state.user_type == 'student':
        
        display_pre_class_quiz_tab(student_id, course_id, session["session_id"])
        display_pre_subjective_test_tab(student_id, course_id, session["session_id"]) 

        st.subheader("Create a Practice Quiz")
        questions = []
        quiz_id = ""
        with st.form("create_quiz_form"):
            num_questions = st.number_input("Number of Questions", min_value=1, max_value=20, value=2)
            submit_quiz = st.form_submit_button("Generate Quiz")
            if submit_quiz:
                # Get pre-class materials from resources_collection
                materials = resources_collection.find({"session_id": session['session_id']})
                context = ""
                for material in materials:
                    if 'text_content' in material:
                        context += material['text_content'] + "\n"

                if not context:
                    st.error("No pre-class materials found for this session.")
                    return

                # Generate MCQs from context
                questions = generate_mcqs(context, num_questions, session['title'], session.get('description', ''))
                if questions:
                    quiz_id = save_quiz(course_id, session['session_id'], "Practice Quiz", questions, student_id)
                    if quiz_id:
                            st.success("Quiz saved successfully!")
                            st.session_state.show_quizzes = True
                    else:
                            st.error("Error saving quiz.")
                else:
                    st.error("Error generating questions.")

        # if st.button("Attempt Practice Quizzes "):
            # quizzes = list(quizzes_collection.find({"course_id": course_id, "session_id": session['session_id'], "user_id": student_id}))
            
            
        if getattr(st.session_state, 'show_quizzes', False):
            # quiz = quizzes_collection.find_one({"course_id": course_id, "session_id": session['session_id'], "user_id": student_id})
            quiz = quizzes_collection.find_one(
                {"course_id": course_id, "session_id": session['session_id'], "user_id": student_id},
                sort=[("created_at", -1)]
            )
            if not quiz:
                st.info("No practice quizzes created.")
            else:
                    with st.expander(f"πŸ“ Practice Quiz", expanded=False):
                        # Check if student has already taken this quiz
                        existing_score = get_student_quiz_score(quiz['_id'], student_id)
                        
                        if existing_score is not None:
                            st.success(f"Quiz completed! Your score: {existing_score:.1f}%")
                            
                            # Display correct answers after submission
                            st.subheader("Quiz Review")
                            for i, question in enumerate(quiz['questions']):
                                st.markdown(f"**Question {i+1}:** {question['question']}")
                                for opt in question['options']:
                                    if opt.startswith(question['correct_option']):
                                        st.markdown(f"βœ… {opt}")
                                    else:
                                        st.markdown(f"- {opt}")
                            
                        else:
                             # Initialize quiz state for this specific quiz
                            quiz_key = f"quiz_{quiz['_id']}_student_{student_id}"
                            if quiz_key not in st.session_state:
                                st.session_state[quiz_key] = {
                                    'submitted': False,
                                    'score': None,
                                    'answers': {}
                                }

                            # If quiz was just submitted, show the results
                            if st.session_state[quiz_key]['submitted']:
                                st.success(f"Quiz submitted successfully! Your score: {st.session_state[quiz_key]['score']:.1f}%")
                                # Reset the quiz state
                                st.session_state[quiz_key]['submitted'] = False


                            # Display quiz questions
                            st.write("Please select your answers:")
                            
                            # Create a form for quiz submission
                            form_key = f"quiz_form_{quiz['_id']}_student_{student_id}"
                            with st.form(key=form_key):
                                student_answers = {}
                                
                                for i, question in enumerate(quiz['questions']):
                                    st.markdown(f"**Question {i+1}:** {question['question']}")
                                    options = [opt for opt in question['options']]
                                    # student_answers[str(i)] = st.radio(
                                    #     f"Select answer for question {i+1}:",
                                    #     options=options,
                                    #     key=f"q_{i}",
                                    #     index=None
                                    # ) 
                                    answer = st.radio(
                                        f"Select answer for question {i+1}:",
                                        options=options,
                                        key=f"{quiz['_id']}_{i}",  # Simplify the radio button key
                                        index=None
                                    )
                                    if answer:  # Only add to answers if a selection was made
                                        student_answers[str(i)] = answer                               

                                # Submit button
                                # submitted =  st.form_submit_button("Submit Quiz")
                                print("Before the submit button")
                                submit_button = st.form_submit_button("Submit Quiz")
                                print("After the submit button")
                            if submit_button and student_answers:
                                print("Clicked the button")
                                print(student_answers)
                                correct_answers = 0
                                for i, question in enumerate(quiz['questions']):
                                    if student_answers[str(i)] == question['correct_option']:
                                        correct_answers += 1
                                score = (correct_answers / len(quiz['questions'])) * 100
                                
                                if score is not None:
                                    st.success(f"Quiz submitted successfully! Your score: {score:.1f}%")
                                    st.session_state[quiz_key]['submitted'] = True
                                    st.session_state[quiz_key]['score'] = score
                                    st.session_state[quiz_key]['answers'] = student_answers
                                    # This will trigger a rerun, but now we'll handle it properly
                                    st.rerun()
                        
                                else:
                                    st.error("Error submitting quiz. Please try again.")
                                # correct_answers = 0
                                # for i, question in enumerate(quiz['questions']):
                                #     if student_answers[str(i)] == question['correct_option']:
                                #         correct_answers += 1
                                # score = (correct_answers / len(quiz['questions'])) * 100
                                # print(score)
                                # try:
                                #     quizzes_collection.update_one(
                                #         {"_id": quiz['_id']},
                                #         {"$push": {"submissions": {"student_id": student_id, "score": score}}}
                                #     )
                                #     st.success(f"Quiz submitted successfully! Your score: {score:.1f}%")
                                # except Exception as db_error:
                                #     st.error(f"Error saving submission: {str(db_error)}")

    # if st.session_state.user_type == "student":
    #     # display_pre_subjective_test_tab(session, course_id, session_id)
    #     display_pre_subjective_test_tab(student_id, course_id, session["session_id"])  # Added this line
    #     pass

def get_chat_context(session_id):
    """Get context from session materials"""
    materials = resources_collection.find({"session_id": session_id})
    context = ""
    for material in materials:
        if 'text_content' in material:
            context += f"{material['text_content']}\n"
    return context

import requests

def get_supported_url_formats():
    """Return a list of supported URL formats for faculty reference"""
    return """
    Supported YouTube URL formats:
    1. Standard watch URL: https://www.youtube.com/watch?v=VIDEO_ID
    2. Short URL: https://youtu.be/VIDEO_ID
    3. Embed URL: https://www.youtube.com/embed/VIDEO_ID
    4. Mobile URL: https://m.youtube.com/watch?v=VIDEO_ID
    5. YouTube Shorts: https://www.youtube.com/shorts/VIDEO_ID
    
    You can copy any of these formats from:
    - YouTube website (Share button)
    - YouTube mobile app (Share button)
    - Browser address bar while watching the video
    """


def display_url_guidance():
    """Display guidance for faculty on how to get the correct URL"""
    st.info("""
    πŸ“ How to get the correct YouTube URL:
    1. Go to the YouTube video you want to share
    2. Click the 'Share' button below the video
    3. Copy the URL provided in the share dialog
    4. Paste it here
    
    The URL should start with either 'youtube.com' or 'youtu.be'
    """)
def fetch_youtube_video_title(video_url):
    """
    Fetch the title of a YouTube video with detailed error handling
    """
    api_key = os.getenv("YOUTUBE_API_KEY")
    if not api_key:
        st.error("⚠️ System Configuration Error: YouTube API key not configured.")
        st.write("Please contact technical support for assistance.")
        return None
        
    video_id = extract_youtube_id(video_url)
    if not video_id:
        return None
    
    url = f"https://www.googleapis.com/youtube/v3/videos?id={video_id}&key={api_key}&part=snippet"
    try:
        response = requests.get(url, timeout=10)
        response.raise_for_status()
        
        data = response.json()
        if not data.get("items"):
            st.error("⚠️ Video not found or might be private.")
            st.write("""
            Please check if:
            1. The video is publicly available
            2. The URL is correct
            3. The video hasn't been deleted
            """)
            return None
            
        return data["items"][0]["snippet"]["title"]
        
    except requests.exceptions.RequestException as e:
        if "quotaExceeded" in str(e):
            st.error("⚠️ YouTube API quota exceeded.")
            st.write("""
            The system has reached its daily limit for video processing.
            Please try:
            1. Waiting a few hours
            2. Trying again tomorrow
            3. Contact support if the issue persists
            """)
        else:
            st.error(f"Error fetching video title: {str(e)}")
            st.write("Please try again or choose a different video.")
        return None

def upload_video_source(course_id, session_id, video_url):
    """
    Upload video source and its transcript with comprehensive error handling
    """
    if not video_url:
        st.error("Please provide a YouTube URL.")
        display_url_guidance()
        return None
        
    # Display processing message
    # with st.spinner("Processing your YouTube video..."):
        # Validate video URL
    video_id = extract_youtube_id(video_url)
    if not video_id:
        return None
        
    # Fetch video title
    video_title = fetch_youtube_video_title(video_url)
    if not video_title:
        return None
        
    # Extract transcript
    transcript = extract_youtube_transcript(video_url)
    if not transcript:
        return None
    
    # Create resource document
    resource_data = {
        "_id": ObjectId(),
        "course_id": course_id,
        "session_id": session_id,
        "file_name": video_title,
        "file_type": "video",
        "text_content": transcript,
        "material_type": "video",
        "source_url": video_url,
        "uploaded_at": datetime.utcnow(),
        "video_id": video_id
    }
    
    # Check if resource already exists
    existing_resource = resources_collection.find_one({
        "session_id": session_id,
        "video_id": video_id
    })
    
    if existing_resource:
        st.warning("⚠️ This video has already been added to this session.")
        st.write("""
        Options:
        1. Choose a different video
        2. Use the existing video resource
        3. Remove the existing video first if you want to re-add it
        """)
        return existing_resource["_id"]
    
    try:
        # Insert new resource
        result = resources_collection.insert_one(resource_data)
        resource_id = result.inserted_id
        
        # Update course document
        update_result = courses_collection.update_one(
            {
                "course_id": course_id,
                "sessions.session_id": session_id
            },
            {
                "$push": {"sessions.$.pre_class.resources": resource_id}
            }
        )
        
        if update_result.modified_count == 0:
            st.error("⚠️ Failed to update course with new resource.")
            st.write("""
            The video was processed but couldn't be added to the course.
            This might be because:
            1. The course or session ID is invalid
            2. You don't have permission to modify this course
            3. There was a system error
            
            Please try again or contact support if the issue persists.
            """)
            # Rollback resource insertion
            resources_collection.delete_one({"_id": resource_id})
            return None
            
        # Create vector store for the transcript
        # create_vector_store(transcript, resource_id)
        # Create vector store for the transcript
        vector_store_result = create_vector_store(transcript, resource_id)
        if not vector_store_result:
            st.error("⚠️ Failed to create vector store for the transcript.")
            # Rollback insertions
            resources_collection.delete_one({"_id": resource_id})
            return None
        
        st.success("βœ… Video successfully added to your course!")
        st.write(f"""
        Added: "{video_title}"
        You can now:
        1. Add more videos
        2. Preview the added video
        3. Continue building your course
        """)
        return resource_id
        
    except Exception as e:
        st.error("⚠️ Error uploading video source.")
        st.write(f"""
        There was an error while saving the video:
        {str(e)}
        
        Please:
        1. Try again
        2. Choose a different video
        3. Contact support if the issue persists
        """)
        return None

def upload_preclass_materials(session_id, course_id, student_id):
    """Upload pre-class materials and manage external resources for a session"""
    st.subheader("Pre-class Materials Management")
    
    # Create tabs for different functionalities
    upload_tab, videos_tab, web_resources ,external_tab, pre_class_tab, pre_class_evaluate, pre_class_quiz = st.tabs(["Upload Materials","Upload Video Sources","Web Resources", "Resources by Perplexity", "Pre-class Questions", "Pre-class Evaluation", "Pre-class Quiz"])
    
    with upload_tab:
        # Original file upload functionality
        uploaded_file = st.file_uploader("Upload Material", type=['txt', 'pdf', 'docx'])
        if uploaded_file is not None:
            with st.spinner("Processing document..."):
                file_name = uploaded_file.name
                file_content = extract_text_from_file(uploaded_file)
                if file_content:
                    material_type = st.selectbox("Select Material Type", ["pdf", "docx", "txt"])
                    if st.button("Upload Material"):
                        upload_resource(course_id, session_id, file_name, uploaded_file, material_type)
                        st.success("Material uploaded successfully!")
        
        # Display pre-class materials
        # Group resources by their types
        grouped_resources = defaultdict(list)
        materials = resources_collection.find({"session_id": session_id})
        for material in materials:
            grouped_resources[material['material_type']].append(material)

        # Display grouped resources
        for material_type, resources in grouped_resources.items():
            st.markdown(f"##### {material_type.capitalize()} Resources")
            for material in resources:
                resource_info = f"- **{material['file_name']}** ({material['file_type']})"
                if 'source_url' in material:
                    resource_info += f" - [URL]({material['source_url']})"
                st.markdown(resource_info)
    
    with videos_tab:
        # Upload video sources
        st.info("Upload video sources for this session.")
        video_url = st.text_input("Enter a Youtube Video URL")
        if st.button("Upload Video"):
            with st.spinner("Processing video source..."):
                video_resource_id = upload_video_source(course_id, session_id, video_url)
                # if video_resource_id:
                #     st.success("Video source uploaded successfully!")
    
    with web_resources:
        st.markdown("##### Upload Web Resource Links")
        st.info("""
        Share online resources with your students. Supported links include:
        - Google Colab notebooks
        - Google Slides   presentations
        - Online documentation
        - Educational websites
        - Any web-based learning resource
        """)

        # Form for adding web resource
        with st.form("web_resource_form"):
            resource_title = st.text_input("Resource Title", 
                placeholder="e.g., Python Basics Notebook, Data Visualization Tutorial")
            resource_url = st.text_input("Resource URL", 
                placeholder="https://colab.research.google.com/... or other web resource")
            resource_type = st.selectbox("Resource Type", 
                ["Jupyter Notebook", "Presentation", "Documentation", "Tutorial", "Other"])
            resource_description = st.text_area("Description (Optional)", 
                placeholder="Brief description of the resource")
            
            submit_resource = st.form_submit_button("Add Resource")

            if submit_resource:
                if not resource_title or not resource_url:
                    st.error("Please provide both a title and URL.")   
                else:
                    try:
                        # Create resource document
                        resource_data = {
                            "_id": ObjectId(),
                            "course_id": course_id,
                            "session_id": session_id,
                            "file_name": resource_title,
                            "file_type": "web_resource",
                            "material_type": resource_type,
                            "source_url": resource_url,
                            "description": resource_description,
                            "uploaded_at": datetime.utcnow()
                        }
                        
                        # Check if resource already exists
                        existing_resource = resources_collection.find_one({
                            "session_id": session_id,
                            "source_url": resource_url
                        })
                        if existing_resource:
                            st.warning("This resource has already been added.")
                        else:
                            # Insert new resource
                            resources_collection.insert_one(resource_data)
                            resource_id = resource_data["_id"]
                            
                            # Update course document
                            courses_collection.update_one(
                                {
                                    "course_id": course_id,
                                    "sessions.session_id": session_id
                                },
                                {
                                    "$push": {"sessions.$.pre_class.resources": resource_id}
                                }
                            )
                            st.success(f"βœ… Resource '{resource_title}' added successfully!")
                            
                    except Exception as e:
                        st.error(f"Error adding resource: {str(e)}")
        


    with external_tab:
        # Fetch and display external resources
        session_data = courses_collection.find_one(
            {"course_id": course_id, "sessions.session_id": session_id},
            {"sessions.$": 1}
        )
        
        if session_data and session_data.get('sessions'):
            session = session_data['sessions'][0]
            external = session.get('external_resources', {})
            
            # Display web articles
            if 'readings' in external:
                st.subheader("Web Articles and Videos")
                for reading in external['readings']:
                    col1, col2 = st.columns([3, 1])
                    with col1:
                        st.markdown(f"**{reading['title']}**")
                        st.markdown(f"Type: {reading['type']} | Est. time: {reading['estimated_read_time']}")
                        st.markdown(f"URL: [{reading['url']}]({reading['url']})")
                    with col2:
                        if st.button("Extract Content", key=f"extract_{reading['url']}"):
                            with st.spinner("Extracting content..."):
                                content = extract_external_content(reading['url'], reading['type'])
                                if content:
                                    resource_id = upload_external_resource(
                                        course_id,
                                        session_id,
                                        reading['title'],
                                        content,
                                        reading['type'].lower(),
                                        reading['url']
                                    )
                                    st.success("Content extracted and stored successfully!")
            
            # Display books
            if 'books' in external:
                st.subheader("Recommended Books")
                for book in external['books']:
                    st.markdown(f"""
                    **{book['title']}** by {book['author']}
                    - ISBN: {book['isbn']}
                    - Chapters: {book['chapters']}
                    """)
            
            # Display additional resources
            if 'additional_resources' in external:
                st.subheader("Additional Resources")
                for resource in external['additional_resources']:
                    st.markdown(f"""
                    **{resource['title']}** ({resource['type']})
                    - {resource['description']}
                    - URL: [{resource['url']}]({resource['url']})
                    """)

    with pre_class_tab:
        if st.session_state.user_type == "faculty":
            faculty_id = st.session_state.user_id
            st.subheader("Create Pre class Subjective Test")

            # Create a form for test generation
            with st.form("pre_create_subjective_test_form"):
                test_title = st.text_input("Test Title")
                num_subjective_questions = st.number_input(
                    "Number of Pre class Subjective Questions", min_value=1, value=5
                )
                generation_method = st.radio(
                    "Question Generation Method", ["Generate from Pre-class Materials"]
                )
                generate_test_btn = st.form_submit_button("Generate Test for Pre Class")

            # Handle test generation outside the form
            if generate_test_btn:
                if not test_title:
                    st.error("Please enter a test title.")
                    return

                context = ""
                if generation_method == "Generate from Pre-class Materials":
                    materials = resources_collection.find(
                        {"session_id": session["session_id"]}
                    )
                    for material in materials:
                        if "text_content" in material:
                            context += material["text_content"] + "\n"

                with st.spinner("Generating questions and synoptic..."):
                    try:
                        # Store generated content in session state to persist between rerenders
                        questions = pre_generate_questions(
                            context if context else None,
                            num_subjective_questions,
                            session["title"],
                            session.get("description", ""),
                        )

                        if questions:
                            synoptic = generate_synoptic(
                                questions,
                                context if context else None,
                                session["title"],
                                num_subjective_questions,
                            )

                            if synoptic:
                                # Store in session state
                                st.session_state.generated_questions = questions
                                st.session_state.generated_synoptic = synoptic
                                st.session_state.test_title = test_title

                                # Display preview
                                st.subheader(
                                    "Preview Subjective Questions and Synoptic"
                                )
                                for i, (q, s) in enumerate(zip(questions, synoptic), 1):
                                    st.markdown(f"**Question {i}:** {q['question']}")
                                    with st.expander(f"View Synoptic {i}"):
                                        st.markdown(s)

                                # Save button outside the form
                                if st.button("Pre Save Test"):
                                    test_id = pre_save_subjective_test(
                                        course_id,
                                        session["session_id"],
                                        test_title,
                                        questions,
                                    )
                                    if test_id:
                                        st.success(
                                            "Subjective test saved successfully!"
                                        )
                                    else:
                                        st.error("Error saving subjective test.")
                            else:
                                st.error(
                                    "Error generating synoptic answers. Please try again."
                                )
                        else:
                            st.error("Error generating questions. Please try again.")
                    except Exception as e:
                        st.error(f"An error occurred: {str(e)}")

            # Display previously generated test if it exists in session state
            elif hasattr(st.session_state, "generated_questions") and hasattr(
                st.session_state, "generated_synoptic"
            ):
                st.subheader("Preview Subjective Questions and Synoptic")
                for i, (q, s) in enumerate(
                    zip(
                        st.session_state.generated_questions,
                        st.session_state.generated_synoptic,
                    ),
                    1,
                ):
                    st.markdown(f"**Question {i}:** {q['question']}")
                    with st.expander(f"View Synoptic {i}"):
                        st.markdown(s)

                if st.button("Pre Save Test"):
                    test_id = pre_save_subjective_test(
                        course_id,
                        session["session_id"],
                        st.session_state.test_title,
                        st.session_state.generated_questions,
                    )
                    if test_id:
                        st.success("Subjective test saved successfully!")
                        # Clear session state after successful save
                        del st.session_state.generated_questions
                        del st.session_state.generated_synoptic
                        del st.session_state.test_title
                    else:
                        st.error("Error saving subjective test.")


    with pre_class_evaluate:
        from subjective_test_evaluation import pre_display_evaluation_to_faculty
        pre_display_evaluation_to_faculty(session["session_id"], student_id, course_id)
    
    with pre_class_quiz:
        if st.session_state.user_type == "faculty":
            st.subheader("Create Pre-class Quiz")
            with st.form("create_pre_class_quiz_form"):
                quiz_title = st.text_input("Quiz Title")
                num_questions = st.number_input(
                    "Number of Questions", 
                    min_value=1, 
                    max_value=20, 
                    value=5
                )
                duration = st.number_input(
                    "Quiz Duration (minutes)", 
                    min_value=5,
                    max_value=60,
                    value=15
                )

                # Generate quiz button
                if st.form_submit_button("Generate Pre-class Quiz"):
                    if not quiz_title:
                        st.error("Please enter a quiz title")
                        return

                    # Get pre-class materials
                    materials = resources_collection.find({"session_id": session_id})
                    context = ""
                    for material in materials:
                        if 'text_content' in material:
                            context += material['text_content'] + "\n"

                    if not context:
                        st.error("No pre-class materials found")
                        return

                    # Generate questions
                    questions = generate_mcqs(
                        context=context,
                        num_questions=num_questions,
                        session_title=session['title'],
                        session_description=session.get('description', '')
                    )

                    if questions:
                        # Preview questions
                        st.subheader("Preview Questions")
                        for i, q in enumerate(questions, 1):
                            st.markdown(f"**Q{i}:** {q['question']}")
                            for opt in q['options']:
                                st.markdown(f"- {opt}")
                            st.markdown(f"*Correct: {q['correct_option']}*")

                        # Save quiz
                        quiz_id = save_pre_class_quiz(
                            course_id=course_id,
                            session_id=session_id,
                            title=quiz_title,
                            questions=questions,
                            user_id=st.session_state.user_id,
                            duration=duration
                        )

                        if quiz_id:
                            st.success("Pre-class quiz created successfully!")
                        else:
                            st.error("Error saving quiz")


def display_pre_class_quiz_tab(student_id, course_id, session_id):
    """Display pre-class quizzes for students"""
    st.markdown("### Pre-class Quizzes")

    # Get available quizzes
    quizzes = quizzes_collection.find({
        "course_id": course_id,
        "session_id": session_id,
        "status": "active"
    })

    quizzes = list(quizzes)
    if not quizzes:
        st.info("No pre-class quizzes available.")
        return

    for quiz in quizzes:
        with st.expander(f"πŸ“ {quiz['title']}", expanded=True):
            # Check if already taken
            existing_score = get_student_quiz_score(quiz["_id"], student_id)

            if existing_score is not None:
                st.success(f"Quiz completed! Score: {existing_score:.1f}%")
                
                # Show review
                st.subheader("Quiz Review")
                for i, question in enumerate(quiz["questions"]):
                    st.markdown(f"**Q{i+1}:** {question['question']}")
                    for opt in question["options"]:
                        if opt.startswith(question["correct_option"]):
                            st.markdown(f"βœ… {opt}")
                        else:
                            st.markdown(f"- {opt}")

            else:
                # Check time remaining
                start_time = quiz.get('start_time')
                if not start_time:
                    if st.button("Start Quiz", key=f"start_{quiz['_id']}"):
                        quizzes_collection.update_one(
                            {"_id": quiz["_id"]},
                            {"$set": {"start_time": datetime.now()}}
                        )
                        st.rerun()
                else:
                    time_remaining = (start_time + timedelta(minutes=quiz['duration_minutes'])) - datetime.now()
                    
                    if time_remaining.total_seconds() > 0:
                        st.info(f"Time remaining: {int(time_remaining.total_seconds() // 60)}:{int(time_remaining.total_seconds() % 60):02d}")
                        
                        # Display quiz form
                        with st.form(f"pre_class_quiz_{quiz['_id']}"):
                            student_answers = {}
                            for i, question in enumerate(quiz["questions"]):
                                st.markdown(f"**Q{i+1}:** {question['question']}")
                                options = [opt for opt in question["options"]]
                                student_answers[str(i)] = st.radio(
                                    f"Select answer:",
                                    options=options,
                                    key=f"q_{quiz['_id']}_{i}"
                                )

                            if st.form_submit_button("Submit Quiz"):
                                score = submit_quiz_answers(
                                    quiz["_id"], 
                                    student_id, 
                                    student_answers
                                )
                                if score is not None:
                                    st.success(f"Quiz submitted! Score: {score:.1f}%")
                                    st.rerun()
                                else:
                                    st.error("Error submitting quiz")
                    else:
                        st.error("Quiz time expired")


def extract_external_content(url, content_type):
    """Extract content from external resources based on their type"""
    try:
        if content_type.lower() == 'video' and 'youtube.com' in url:
            return extract_youtube_transcript(url)
        else:
            return extract_web_article(url)
    except Exception as e:
        st.error(f"Error extracting content: {str(e)}")
        return None

def extract_youtube_transcript(url):
    """
    Extract transcript from YouTube videos with detailed error handling
    """
    try:
        video_id = extract_youtube_id(url)
        if not video_id:
            return None
            
        # Get transcript with retries
        max_retries = 3
        for attempt in range(max_retries):
            try:
                transcript = YouTubeTranscriptApi.get_transcript(video_id)
                # Combine transcript text with proper spacing and punctuation
                full_text = ''
                for entry in transcript:
                    text = entry['text'].strip()
                    if text:
                        if not full_text.endswith(('.', '!', '?', '..."')):
                            full_text += '. '
                        full_text += text + ' '
                return full_text.strip()
            except Exception as e:
                if attempt == max_retries - 1:
                    raise e
                continue
                
    except Exception as e:
        error_message = str(e)
        if "Video unavailable" in error_message:
            st.error("⚠️ This video is unavailable or private. Please check if:")
            st.write("""
            - The video is set to public or unlisted
            - The video hasn't been deleted
            - You have the correct URL
            """)
        elif "Subtitles are disabled" in error_message:
            st.error("⚠️ This video doesn't have subtitles/transcript available.")
            st.write("""
            Unfortunately, this video cannot be used because:
            - It doesn't have closed captions or subtitles
            - The creator hasn't enabled transcript generation
            
            Please choose another video that has subtitles available.
            You can check if a video has subtitles by:
            1. Playing the video on YouTube
            2. Clicking the 'CC' button in the video player
            """)
        else:
            st.error(f"Could not extract YouTube transcript: {error_message}")
            st.write("Please try again or choose a different video.")
        return None

def extract_web_article(url):
    """Extract text content from web articles"""
    try:
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
        }
        response = requests.get(url, headers=headers)
        response.raise_for_status()
        
        soup = BeautifulSoup(response.text, 'html.parser')
        
        # Remove unwanted tags
        for tag in soup(['script', 'style', 'nav', 'footer', 'header']):
            tag.decompose()
        
        # Extract text from paragraphs
        paragraphs = soup.find_all('p')
        text_content = ' '.join([p.get_text().strip() for p in paragraphs])
        
        return text_content
    except Exception as e:
        st.error(f"Could not extract web article content: {str(e)}")
        return None

def upload_external_resource(course_id, session_id, title, content, content_type, source_url):
    """Upload extracted external resource content to the database"""
    resource_data = {
        "_id": ObjectId(),
        "course_id": course_id,
        "session_id": session_id,
        "file_name": f"{title} ({content_type})",
        "file_type": "external",
        "text_content": content,
        "material_type": content_type,
        "source_url": source_url,
        "uploaded_at": datetime.utcnow()
    }
    
    # Check if resource already exists
    existing_resource = resources_collection.find_one({
        "session_id": session_id,
        "source_url": source_url
    })
    
    if existing_resource:
        return existing_resource["_id"]
    
    # Insert new resource
    resources_collection.insert_one(resource_data)
    resource_id = resource_data["_id"]
    
    # Update course document
    courses_collection.update_one(
        {
            "course_id": course_id,
            "sessions.session_id": session_id
        },
        {
            "$push": {"sessions.$.pre_class.resources": resource_id}
        }
    )
    
    if content:
        create_vector_store(content, resource_id)
    
    return resource_id

def extract_youtube_id(url):
    """
    Extract YouTube video ID from various URL formats
    """
    if not url:
        st.error("Please provide a YouTube URL.")
        display_url_guidance()
        return None
        
    # Clean the URL
    url = url.strip()
    
    # Basic URL validation
    if not ('youtube.com' in url or 'youtu.be' in url):
        st.error("This doesn't appear to be a YouTube URL.")
        st.write(get_supported_url_formats())
        return None
    
    # Try to extract using regex patterns
    patterns = [
        r'(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/v\/|youtube\.com\/e\/|youtube\.com\/shorts\/)([^&\n?#]+)',
        r'(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})'
    ]
    
    for pattern in patterns:
        match = re.search(pattern, url)
        if match:
            video_id = match.group(1)
            if len(video_id) != 11:  # YouTube IDs are always 11 characters
                st.error("Invalid YouTube video ID length. Please check your URL.")
                display_url_guidance()
                return None
            return video_id
    
    # If regex fails, try parsing URL components
    try:
        parsed_url = urlparse(url)
        if 'youtube.com' in parsed_url.netloc:
            query_params = parse_qs(parsed_url.query)
            if 'v' in query_params:
                return query_params['v'][0]
        elif 'youtu.be' in parsed_url.netloc:
            return parsed_url.path.lstrip('/')
    except Exception:
        pass
    
    # If all extraction methods fail
    st.error("Could not extract video ID from the provided URL.")
    st.write(get_supported_url_formats())
    return None

def display_live_presentation(session, user_type, course_id):
    st.markdown("### Live Presentation")
    
    # Get active presentation
    session_data = courses_collection.find_one(
        {"course_id": course_id, "sessions.session_id": session['session_id']},
        {"sessions.$": 1}
    )
    active_presentation = session_data["sessions"][0].get("in_class", {}).get("active_presentation")
    
    # Faculty Interface
    if user_type == 'faculty':
        if not active_presentation:
            st.markdown("""
                <style>
                    .url-container {
                        background-color: #f8f9fa;
                        padding: 20px;
                        border-radius: 10px;
                        margin: 10px 0;
                    }
                    .button-container {
                        display: flex;
                        justify-content: space-between;
                        margin-top: 10px;
                    }
                </style>
            """, unsafe_allow_html=True)
            
            # URL input section
            with st.container():
                ppt_url = st.text_input("πŸ”— Enter Google Slides Presentation URL", 
                                      placeholder="https://docs.google.com/presentation/...")
                
                if ppt_url:
                    if st.button("▢️ Activate Presentation", 
                               use_container_width=True):
                        courses_collection.update_one(
                            {"course_id": course_id, "sessions.session_id": session['session_id']},
                            {"$set": {"sessions.$.in_class.active_presentation": ppt_url}}
                        )
                        st.success("βœ… Presentation activated successfully!")
                        st.rerun()
        else:
            # Display active presentation
            st.markdown("#### 🎯 Active Presentation")
            components.iframe(active_presentation, height=800)
            
            # Deactivate button
            st.markdown("<div style='margin-top: 20px;'></div>", unsafe_allow_html=True)
            if st.button("⏹️ Deactivate Presentation", 
                        type="secondary",
                        use_container_width=True):
                courses_collection.update_one(
                    {"course_id": course_id, "sessions.session_id": session['session_id']},
                    {"$unset": {"sessions.$.in_class.active_presentation": ""}}
                )
                st.success("βœ… Presentation deactivated successfully!")
                st.rerun()
    
    # Student Interface
    else:
        if active_presentation:
            st.markdown("#### 🎯 Active Presentation")
            components.iframe(active_presentation, height=800)
        else:
            st.info("πŸ“ No active presentations at this time.")

def display_in_class_content(session, user_type, course_id, user_id):
    # """Display in-class activities and interactions"""
    """Display in-class activities and interactions"""
    st.header("In-class Activities")
    
    # Initialize Live Polls feature
    live_polls = LivePollFeature()
    
    # Display appropriate interface based on user role
    if user_type == 'faculty':
        live_polls.display_faculty_interface(session['session_id'])
    else:
        live_polls.display_student_interface(session['session_id'])
    
    display_live_chat_interface(session, user_id, course_id=course_id)

    # Live Presentation Feature
    display_live_presentation(session, user_type, course_id)

    if user_type == "faculty":
        faculty_id = st.session_state.user_id

        st.markdown("#### Create Surprise Quiz")

        questions = []
        with st.form("create_surprise_quiz_form"):
            quiz_title = st.text_input("Surprise Quiz Title")
            num_questions = st.number_input(
                "Number of Questions", min_value=1, max_value=20, value=5
            )
            no_minutes = st.number_input( 
                "Duration of Quiz (in minutes)", min_value=1, max_value=60, value=5
            )

            # Option to choose quiz generation method
            generation_method = st.radio(
                "Question Generation Method",
                ["Generate from Pre-class Materials"],
            )

            submit_quiz = st.form_submit_button("Generate Surprise Quiz")
            if submit_quiz:
                if generation_method == "Generate from Pre-class Materials":
                    # Get pre-class materials from resources_collection
                    materials = resources_collection.find(
                        {"session_id": session["session_id"]}
                    )
                    context = ""
                    for material in materials:
                        if "text_content" in material:
                            context += material["text_content"] + "\n"

                    if not context:
                        st.error("No pre-class materials found for this session.")
                        return

                    # Generate MCQs from context
                    questions = generate_mcqs(
                        context,
                        num_questions,
                        session["title"],
                        session.get("description", ""),
                    )
                else:
                    # Generate random MCQs based on session title and description
                    questions = generate_mcqs(
                        None,
                        num_questions,
                        session["title"],
                        session.get("description", ""),
                    )
                    print(questions)

                if questions:
                    # Preview generated questions
                    st.subheader("Preview Generated Questions")
                    for i, q in enumerate(questions, 1):
                        st.markdown(f"**Question {i}:** {q['question']}")
                        for opt in q["options"]:
                            st.markdown(f"- {opt}")
                        st.markdown(f"*Correct Answer: {q['correct_option']}*")

                    # Save quiz
                    quiz_id = save_surprise_quiz(
                        course_id,
                        session["session_id"],
                        quiz_title,
                        questions,
                        faculty_id,
                        no_minutes
                    )
                    if quiz_id:
                        st.success("Quiz saved successfully!")
                    else:
                        st.error("Error saving quiz.")
    else:

        display_surprise_quiz_tab(st.session_state.user_id, course_id=course_id, session_id=session["session_id"])

def generate_random_assignment_id():
    """Generate a random integer ID for assignments"""
    return random.randint(100000, 999999)

def display_post_class_content(session, student_id, course_id):
    """Display post-class assignments and submissions"""
    st.header("Post-class Work")

    if st.session_state.user_type == 'faculty':
        faculty_id = st.session_state.user_id
        st.subheader("Create Subjective Test")
        
        # Create a form for test generation
        with st.form("create_subjective_test_form"):
            test_title = st.text_input("Test Title")
            num_subjective_questions = st.number_input("Number of Subjective Questions", min_value=1, value=5)
            generation_method = st.radio(
                "Question Generation Method",
                ["Generate from Pre-class Materials", "Generate Random Questions"]
            )
            generate_test_btn = st.form_submit_button("Generate Test")

        # Handle test generation outside the form
        if generate_test_btn:
            if not test_title:
                st.error("Please enter a test title.")
                return

            context = ""
            if generation_method == "Generate from Pre-class Materials":
                materials = resources_collection.find({"session_id": session['session_id']})
                for material in materials:
                    if 'text_content' in material:
                        context += material['text_content'] + "\n"

            with st.spinner("Generating questions and synoptic..."):
                try:
                    # Store generated content in session state to persist between rerenders
                    questions = generate_questions(
                        context if context else None,
                        num_subjective_questions,
                        session['title'],
                        session.get('description', '')
                    )
                    
                    if questions:
                        synoptic = generate_synoptic(
                            questions,
                            context if context else None,
                            session['title'],
                            num_subjective_questions
                        )
                        
                        if synoptic:
                            # Store in session state
                            st.session_state.generated_questions = questions
                            st.session_state.generated_synoptic = synoptic
                            st.session_state.test_title = test_title
                            
                            # Display preview
                            st.subheader("Preview Subjective Questions and Synoptic")
                            for i, (q, s) in enumerate(zip(questions, synoptic), 1):
                                st.markdown(f"**Question {i}:** {q['question']}")
                                with st.expander(f"View Synoptic {i}"):
                                    st.markdown(s)
                            
                            # Save button outside the form
                            if st.button("Save Test"):
                                test_id = save_subjective_test(
                                    course_id,
                                    session['session_id'],
                                    test_title,
                                    questions
                                )
                                if test_id:
                                    st.success("Subjective test saved successfully!")
                                else:
                                    st.error("Error saving subjective test.")
                        else:
                            st.error("Error generating synoptic answers. Please try again.")
                    else:
                        st.error("Error generating questions. Please try again.")
                except Exception as e:
                    st.error(f"An error occurred: {str(e)}")

        # Display previously generated test if it exists in session state
        elif hasattr(st.session_state, 'generated_questions') and hasattr(st.session_state, 'generated_synoptic'):
            st.subheader("Preview Subjective Questions and Synoptic")
            for i, (q, s) in enumerate(zip(st.session_state.generated_questions, st.session_state.generated_synoptic), 1):
                st.markdown(f"**Question {i}:** {q['question']}")
                with st.expander(f"View Synoptic {i}"):
                    st.markdown(s)
            
            if st.button("Save Test"):
                test_id = save_subjective_test(
                    course_id,
                    session['session_id'],
                    st.session_state.test_title,
                    st.session_state.generated_questions,
                )
                if test_id:
                    st.success("Subjective test saved successfully!")
                    # Clear session state after successful save
                    del st.session_state.generated_questions
                    del st.session_state.generated_synoptic
                    del st.session_state.test_title
                else:
                    st.error("Error saving subjective test.")

        # st.subheader("Create quiz section UI for faculty")
        st.subheader("Create Quiz")
        
        questions = []
        with st.form("create_quiz_form"):
            quiz_title = st.text_input("Quiz Title")
            num_questions = st.number_input("Number of Questions", min_value=1, max_value=20, value=5)
            
            # Option to choose quiz generation method
            generation_method = st.radio(
                "Question Generation Method",
                ["Generate from Pre-class Materials", "Generate Random Questions"]
            )
            
            submit_quiz = st.form_submit_button("Generate Quiz")
            if submit_quiz:
                if generation_method == "Generate from Pre-class Materials":
                    # Get pre-class materials from resources_collection
                    materials = resources_collection.find({"session_id": session['session_id']})
                    context = ""
                    for material in materials:
                        if 'text_content' in material:
                            context += material['text_content'] + "\n"
                    
                    if not context:
                        st.error("No pre-class materials found for this session.")
                        return
                    
                    # Generate MCQs from context
                    questions = generate_mcqs(context, num_questions, session['title'], session.get('description', ''))
                else:
                    # Generate random MCQs based on session title and description
                    questions = generate_mcqs(None, num_questions, session['title'], session.get('description', ''))
                    print(questions)
                
                if questions:
                    # Preview generated questions
                    st.subheader("Preview Generated Questions")
                    for i, q in enumerate(questions, 1):
                        st.markdown(f"**Question {i}:** {q['question']}")
                        for opt in q['options']:
                            st.markdown(f"- {opt}")
                        st.markdown(f"*Correct Answer: {q['correct_option']}*")
                    
                    # Save quiz 
                    quiz_id = save_quiz(course_id, session['session_id'], quiz_title, questions, faculty_id)
                    if quiz_id:
                        st.success("Quiz saved successfully!")
                    else:
                        st.error("Error saving quiz.")

        st.subheader("Add Assignment")
        with st.form("add_assignment_form"):
            title = st.text_input("Assignment Title")
            description = st.text_area("Assignment Description")
            due_date = st.date_input("Due Date")
            submit = st.form_submit_button("Add Assignment")
            
            if submit:
                if not title or not description:
                    st.error("Please fill in all required fields.")
                    return
                    
                due_date = datetime.combine(due_date, datetime.min.time())
                assignment = {
                    "_id": ObjectId(),
                    "title": title,
                    "description": description,
                    "due_date": due_date,
                    "course_id": course_id,
                    "session_id": session['session_id'],
                    "faculty_id": faculty_id,
                    "created_at": datetime.utcnow(),
                    "status": "active",
                    "submissions": []
                }
                
                assignments_collection.insert_one(assignment)
                st.success("Assignment added successfully!")
                
        st.subheader("Existing Assignments")
        assignments = assignments_collection.find({
            "session_id": session['session_id'],
            "course_id": course_id
        })
        
        for assignment in assignments:
            with st.expander(f"πŸ“ {assignment['title']}", expanded=True):
                st.markdown(f"**Due Date:** {assignment['due_date'].strftime('%Y-%m-%d')}")
                st.markdown(f"**Description:** {assignment['description']}")
                
                total_submissions = len(assignment.get('submissions', []))
                total_students = students_collection.count_documents({
                    "enrolled_courses": {
                        "$elemMatch": {"course_id": course_id}
                    }
                })
                
                col1, col2, col3 = st.columns(3)
                with col1:
                    st.metric("Total Submissions", total_submissions)
                with col2:
                    submission_rate = (total_submissions / total_students * 100) if total_students > 0 else 0
                    st.metric("Submission Rate", f"{submission_rate:.1f}%")
                with col3:
                    st.metric("Pending Submissions", total_students - total_submissions)
                
                # Display evaluation button and status
                evaluation_status = st.empty()
                eval_button = st.button("View/Generate Evaluations", key=f"eval_{assignment['_id']}")
                
                if eval_button:
                    st.session_state.show_evaluations = True
                    st.session_state.current_assignment = assignment['_id']
                    
                    # Show evaluation interface in a new container instead of an expander
                    evaluation_container = st.container()
                    with evaluation_container:
                        from assignment_evaluation import display_evaluation_to_faculty
                        display_evaluation_to_faculty(session['session_id'], student_id, course_id)
                    
    else:  # Student view
        assignments = assignments_collection.find({
            "session_id": session['session_id'],
            "course_id": course_id,
            "status": "active"
        })
        
        for assignment in assignments:
            with st.expander(f"πŸ“ {assignment['title']}", expanded=True):
                st.markdown(f"**Due Date:** {assignment['due_date'].strftime('%Y-%m-%d')}")
                st.markdown(f"**Description:** {assignment['description']}")
                
                existing_submission = next(
                    (sub for sub in assignment.get('submissions', []) 
                     if sub['student_id'] == str(student_id)),
                    None
                )
                
                if existing_submission:
                    st.success("Assignment submitted!")
                    st.markdown(f"**Submitted on:** {existing_submission['submitted_at'].strftime('%Y-%m-%d %H:%M')}")
                    
                    # Show evaluation status and feedback in the same container
                    evaluation = assignment_evaluation_collection.find_one({
                        "assignment_id": assignment['_id'],
                        "student_id": str(student_id)
                    })
                    
                    if evaluation:
                        st.markdown("### Evaluation")
                        st.markdown(evaluation['evaluation'])
                    else:
                        st.info("Evaluation pending. Check back later.")
                else:
                    uploaded_file = st.file_uploader(
                        "Upload your work",
                        type=['pdf', 'doc', 'docx', 'txt', 'py', 'ipynb', 'ppt', 'pptx'],
                        key=f"upload_{assignment['_id']}"
                    )
                    
                    if uploaded_file is not None:
                        if st.button("Submit Assignment", key=f"submit_{assignment['_id']}"):
                            text_content = extract_text_from_file(uploaded_file)
                            
                            submission = {
                                "student_id": str(student_id),
                                "file_name": uploaded_file.name,
                                "file_type": uploaded_file.type,
                                "file_content": uploaded_file.getvalue(),
                                "text_content": text_content,
                                "submitted_at": datetime.utcnow()
                            }
                            
                            assignments_collection.update_one(
                                {"_id": assignment['_id']},
                                {"$push": {"submissions": submission}}
                            )
                            
                            st.success("Assignment submitted successfully!")
                            st.rerun()            

def display_inclass_analytics(session, course_id):
    """Display in-class analytics for faculty"""
    st.subheader("In-class Analytics")
    
    # Get all enrolled students count for participation rate calculation
    total_students = students_collection.count_documents({
        "enrolled_courses": {
            "$elemMatch": {"course_id": course_id}
        }
    })
    
    if total_students == 0:
        st.warning("No students enrolled in this course.")
        return
    
    # Get all polls for this session
    polls = polls_collection.find({
        "session_id": session['session_id']
    })
    
    polls_list = list(polls)
    if not polls_list:
        st.warning("No polls have been conducted in this session yet.")
        return
    
    # Overall Poll Participation Metrics
    st.markdown("### Overall Poll Participation")
    
    # Calculate overall participation metrics
    total_polls = len(polls_list)
    participating_students = set()
    poll_participation_data = []
    
    for poll in polls_list:
        respondents = set(poll.get('respondents', []))
        participating_students.update(respondents)
        poll_participation_data.append({
            'Poll Title': poll.get('question', 'Untitled Poll'),
            'Respondents': len(respondents),
            'Participation Rate': (len(respondents) / total_students * 100)
        })
    
    # Display summary metrics
    col1, col2, col3 = st.columns(3)
    with col1:
        st.metric("Total Polls Conducted", total_polls)
    with col2:
        st.metric("Active Participants", len(participating_students))
    with col3:
        avg_participation = sum(p['Participation Rate'] for p in poll_participation_data) / total_polls
        st.metric("Average Participation Rate", f"{avg_participation:.1f}%")
    
    # Participation Trend Graph
    # st.markdown("### Poll Participation Trends")
    # participation_df = pd.DataFrame(poll_participation_data)
    
    # # Create line chart for participation trends
    # fig = px.line(participation_df, 
    #               x='Poll Title', 
    #               y='Participation Rate',
    #               title='Poll Participation Rates Over Time',
    #               markers=True)
    # fig.update_layout(
    #     xaxis_title="Polls",
    #     yaxis_title="Participation Rate (%)",
    #     yaxis_range=[0, 100]
    # )
    # st.plotly_chart(fig)
    
    # Individual Poll Results
    st.markdown("### Individual Poll Results")
    
    for poll in polls_list:
        with st.expander(f"πŸ“Š {poll.get('question', 'Untitled Poll')}"):
            responses = poll.get('responses', {})
            respondents = poll.get('respondents', [])
            
            # Calculate metrics for this poll
            response_count = len(respondents)
            participation_rate = (response_count / total_students) * 100
            
            # Display poll metrics
            col1, col2 = st.columns(2)
            with col1:
                st.metric("Total Responses", response_count)
            with col2:
                st.metric("Participation Rate", f"{participation_rate:.1f}%")
            
            if responses:
                # Create DataFrame for responses
                response_df = pd.DataFrame(list(responses.items()), 
                                         columns=['Option', 'Votes'])
                response_df['Percentage'] = (response_df['Votes'] / response_df['Votes'].sum() * 100).round(1)
                
                # Display response distribution
                fig = px.bar(response_df, 
                           x='Option', 
                           y='Votes',
                           title='Response Distribution',
                           text='Percentage')
                fig.update_traces(texttemplate='%{text:.1f}%', textposition='outside')
                st.plotly_chart(fig)
                
                # Display detailed response table
                st.markdown("#### Detailed Response Breakdown")
                response_df['Percentage'] = response_df['Percentage'].apply(lambda x: f"{x}%")
                st.table(response_df)
            
            # Non-participating students
            non_participants = list(students_collection.find({
                "courses": course_id,
                "_id": {"$nin": respondents}
            }))

            if non_participants:
                st.markdown("#### Students Who Haven't Participated")
                non_participant_data = [{
                    'Name': student.get('name', 'Unknown'),
                    'SID': student.get('sid', 'Unknown')
                } for student in non_participants]
                st.table(pd.DataFrame(non_participant_data))
    
    # Export functionality for participation data
    st.markdown("### Export Analytics")
    
    if st.button("Download Poll Analytics Report"):
        # Create a more detailed DataFrame for export
        export_data = []
        for poll in polls_list:
            poll_data = {
                'Poll Question': poll.get('question', 'Untitled'),
                'Total Responses': len(poll.get('respondents', [])),
                'Participation Rate': f"{(len(poll.get('respondents', [])) / total_students * 100):.1f}%"
            }
            # Add response distribution
            for option, votes in poll.get('responses', {}).items():
                poll_data[f"Option: {option}"] = votes
            export_data.append(poll_data)
        
        export_df = pd.DataFrame(export_data)
        csv = export_df.to_csv(index=False).encode('utf-8')
        st.download_button(
            "πŸ“₯ Download Complete Report",
            csv,
            "poll_analytics.csv",
            "text/csv",
            key='download-csv'
        )
    
def display_postclass_analytics(session, course_id):
    """Display post-class analytics for faculty"""
    st.subheader("Post-class Analytics")
    
    # Get all assignments for this session
    session_data = courses_collection2.find_one(
        {"sessions.session_id": session['session_id']},
        {"sessions.$": 1}
    )
    
    if not session_data or 'sessions' not in session_data:
        st.warning("No assignments found for this session.")
        return
    
    assignments = session_data['sessions'][0].get('post_class', {}).get('assignments', [])
    
    for assignment in assignments:
        with st.expander(f"πŸ“ Assignment: {assignment.get('title', 'Untitled')}"):
            # Get submission analytics
            submissions = assignment.get('submissions', [])
            # total_students = students_collection.count_documents({"courses": session['course_id']})
            total_students = students_collection.count_documents({
                "enrolled_courses": {
                    "$elemMatch": {"course_id": course_id}
                }
            })
            # Calculate submission metrics
            submitted_count = len(submissions)
            submission_rate = (submitted_count / total_students) * 100 if total_students > 0 else 0
            
            # Display metrics
            col1, col2, col3 = st.columns(3)
            with col1:
                st.metric("Submissions Received", submitted_count)
            with col2:
                st.metric("Submission Rate", f"{submission_rate:.1f}%")
            with col3:
                st.metric("Pending Submissions", total_students - submitted_count)
            
            # Display submission timeline
            if submissions:
                submission_dates = [sub.get('submitted_at') for sub in submissions if 'submitted_at' in sub]
                if submission_dates:
                    df = pd.DataFrame(submission_dates, columns=['Submission Date'])
                    fig = px.histogram(df, x='Submission Date', 
                                     title='Submission Timeline',
                                     labels={'Submission Date': 'Date', 'count': 'Number of Submissions'})
                    st.plotly_chart(fig)
            
            # Display submission status breakdown
            status_counts = {
                'pending': total_students - submitted_count,
                'submitted': submitted_count,
                'late': len([sub for sub in submissions if sub.get('is_late', False)])
            }
            
            st.markdown("### Submission Status Breakdown")
            status_df = pd.DataFrame(list(status_counts.items()), 
                                   columns=['Status', 'Count'])
            st.bar_chart(status_df.set_index('Status'))
            
            # List of students who haven't submitted
            if status_counts['pending'] > 0:
                st.markdown("### Students with Pending Submissions")
                # submitted_ids = [sub.get('student_id') for sub in submissions]
                submitted_ids = [ObjectId(sub.get('student_id')) for sub in submissions]
                print(submitted_ids)
                pending_students = students_collection.find({
                    "enrolled_courses.course_id": course_id,
                    "_id": {"$nin": submitted_ids}
                })
                print(pending_students)
                for student in pending_students:
                    st.markdown(f"- {student.get('full_name', 'Unknown Student')} (SID: {student.get('SID', 'Unknown SID')})")

def get_chat_history(user_id, session_id):
    query = {
        "user_id": ObjectId(user_id),
        "session_id": session_id,
        "timestamp": {"$lte": datetime.utcnow()}
    }
    result = chat_history_collection.find(query)
    return list(result)

def get_response_from_llm(raw_data):
    messages = [
        {
            "role": "system",
            "content": "You are an AI that refines raw analytics data into actionable insights for faculty reports."
        },
        {
            "role": "user",
            "content": f"""
            Based on the following analytics data, refine and summarize the insights:

            Raw Data:
            {raw_data}

            Instructions:
            1. Group similar topics together under appropriate categories.
            2. Remove irrelevant or repetitive entries.
            3. Summarize the findings into actionable insights.
            4. Provide concise recommendations for improvement based on the findings.

            Output:
            Provide a structured response with the following format:
            {{
            "Low Engagement Topics": ["List of Topics"],
            "Frustration Areas": ["List of areas"],
            "Recommendations": ["Actionable recommendations"],
            }}
            """
        }
    ]
    try:
        client = OpenAI(api_key=OPENAI_API_KEY)
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            temperature=0.2
        )
        content = response.choices[0].message.content
        return json.loads(content) 
    
    except Exception as e:
        st.error(f"Error generating response: {str(e)}")
        return None

import typing_extensions as typing 
from typing import Union, List, Dict

# class Topics(typing.TypedDict):
#     overarching_theme: List[Dict[str, Union[str, List[Dict[str, Union[str, List[str]]]]]]]
#     indirect_topics: List[Dict[str, str]]

def extract_topics_from_materials(session):
    """Extract topics from pre-class materials"""
    materials = resources_collection.find({"session_id": session['session_id']})
    texts = ""
    if materials:
        for material in materials:
            if 'text_content' in material:
                text = material['text_content']
                texts += text + "\n"
            else:
                st.warning("No text content found in the material.")
                return
    else:
        st.error("No pre-class materials found for this session.")
        return

    if texts:
        context_prompt = f"""
        Task: Extract Comprehensive Topics in a List Format
        You are tasked with analyzing the provided text content and extracting a detailed, flat list of topics.

        Instructions:
        Identify All Topics: Extract a comprehensive list of all topics, subtopics, and indirect topics present in the provided text content. This list should include:

        Overarching themes
        Main topics
        Subtopics and their sub-subtopics
        Indirectly related topics
        Flat List Format: Provide a flat list where each item is a topic. Ensure topics at all levels (overarching, main, sub, sub-sub, indirect) are represented as individual entries in the list.

        Be Exhaustive: Ensure the response captures every topic, subtopic, and indirectly related concept comprehensively.

        Output Requirements:
        Use this structure:
        {{
            "topics": [
                "Topic 1",
                "Topic 2",
                "Topic 3",
                ...
            ]
        }}
        Do Not Include: Do not include backticks, hierarchical structures, or the word 'json' in your response.

        Content to Analyze:
        {texts}
        """
        try:
            # response = model.generate_content(context_prompt, generation_config=genai.GenerationConfig(response_mime_type="application/json", response_schema=list[Topics]))
            response = model.generate_content(context_prompt, generation_config=genai.GenerationConfig(temperature=0.3))
            if not response or not response.text:
                st.error("Error extracting topics from materials.")
                return
            
            topics = response.text
            return topics
        except Exception as e:
            st.error(f"Error extracting topics: {str(e)}")
            return None
    else:
        st.error("No text content found in the pre-class materials.")
        return None

def convert_json_to_dict(json_str):
    try:
        return json.loads(json_str)
    except Exception as e:
        st.error(f"Error converting JSON to dictionary. {str(e)}")
        return None

# Load topics from a JSON file
# topics = []
# with open(r'topics.json', 'r') as file:
#     topics = json.load(file)

def get_preclass_analytics(session, course_id):
    # Earlier Code:
    # """Get all user_ids from chat_history collection where session_id matches"""
    # user_ids = chat_history_collection.distinct("user_id", {"session_id": session['session_id']})
    # print(user_ids)
    # session_id = session['session_id']

    # all_chat_histories = []

    # for user_id in user_ids:
    #     result = get_chat_history(user_id, session_id)
    #     if result:
    #         for record in result:
    #             chat_history = {
    #                 "user_id": record["user_id"],
    #                 "session_id": record["session_id"],
    #                 "messages": record["messages"]
    #             }
    #             all_chat_histories.append(chat_history)
    #     else:
    #         st.warning("No chat history found for this session.")
    

    # # Pass the pre-class materials content to the analytics engine
    # topics = extract_topics_from_materials(session)
    # # dict_topics = convert_json_to_dict(topics)
    # print(topics)
    
    # # # Use the 1st analytics engine
    # # analytics_engine = NovaScholarAnalytics(all_topics_list=topics)
    # # # extracted_topics = analytics_engine._extract_topics(None, topics)
    # # # print(extracted_topics)

    # # results = analytics_engine.process_chat_history(all_chat_histories)
    # # faculty_report = analytics_engine.generate_faculty_report(results)
    # # print(faculty_report)
    # # # Pass this Faculty Report to an LLM model for refinements and clarity
    # # refined_report = get_response_from_llm(faculty_report)
    # # return refined_report

    # # Use the 2nd analytice engine (using LLM): 
    fallback_analytics = {
        "topic_insights": [],
            "student_insights": [],
            "recommended_actions": [
                {
                    "action": "Review analytics generation process",
                    "priority": "high",
                    "target_group": "system_administrators",
                    "reasoning": "Analytics generation failed",
                    "expected_impact": "Restore analytics functionality"
                }
            ],
            "course_health": {
                "overall_engagement": 0,
                "critical_topics": [],
                "class_distribution": {
                    "high_performers": 0,
                    "average_performers": 0,
                    "at_risk": 0
                }
            },
            "intervention_metrics": {
                "immediate_attention_needed": [],
                "monitoring_required": []
            }
    }
    # analytics_generator = NovaScholarAnalytics()
    # analytics2 = analytics_generator.generate_analytics(all_chat_histories, topics)
    # # enriched_analytics = analytics_generator._enrich_analytics(analytics2)
    # print("Analytics is: ", analytics2)
    
    # if analytics2 == fallback_analytics:
    #     return None
    # else:
    #     return analytics2
    # # print(json.dumps(analytics, indent=2))


    # New Code:
    # Debug print 1: Check session
    print("Starting get_preclass_analytics with session:", session['session_id'])
    
    user_ids = chat_history_collection.distinct("user_id", {"session_id": session['session_id']})
    # Debug print 2: Check user_ids
    print("Found user_ids:", user_ids)
    
    all_chat_histories = []
    for user_id in user_ids:
        result = get_chat_history(user_id, session['session_id'])
        # Debug print 3: Check each chat history result
        print(f"Chat history for user {user_id}:", "Found" if result else "Not found")
        if result:
            for record in result:
                chat_history = {
                    "user_id": record["user_id"],
                    "session_id": record["session_id"],
                    "messages": record["messages"]
                }
                all_chat_histories.append(chat_history)

    # Debug print 4: Check chat histories
    print("Total chat histories collected:", len(all_chat_histories))

    # Extract topics with debug print
    topics = extract_topics_from_materials(session)
    # Debug print 5: Check topics
    print("Extracted topics:", topics)
    
    if not topics:
        print("Topics extraction failed")  # Debug print 6
        return None

    analytics_generator = NovaScholarAnalytics()
    analytics2 = analytics_generator.generate_analytics(all_chat_histories, topics)
    # Debug print 7: Check analytics
    print("Generated analytics:", analytics2)
    
    if analytics2 == fallback_analytics:
        print("Fallback analytics returned")  # Debug print 8
        return None
    else:
        try:
            courses_collection.update_one(
                {"course_id": course_id, "sessions.session_id": session['session_id']},
                {"$set": {"sessions.$.pre_class.analytics": analytics2}}
            )
        except Exception as e:
            print("Error storing analytics:", str(e)) 
        return analytics2


# Load Analytics from a JSON file
# analytics = []
# with open(r'new_analytics2.json', 'r') as file:
#     analytics = json.load(file)

def display_preclass_analytics2(session, course_id):
    # Earlier Code:
    # Initialize or get analytics data from session state
    # if 'analytics_data' not in st.session_state:
    #     st.session_state.analytics_data = get_preclass_analytics(session)

    # analytics = st.session_state.analytics_data
    
    # print(analytics)


    # New Code:
    # Initialize or get analytics data from session state
    if 'analytics_data' not in st.session_state:
        # Add debug prints
        analytics_data = get_preclass_analytics(session, course_id)
        if analytics_data is None:
            st.info("Fetching new analytics data...")
        if analytics_data is None:
            st.error("Failed to generate analytics. Please check the following:")
            st.write("1. Ensure pre-class materials contain text content")
            st.write("2. Verify chat history exists for this session")
            st.write("3. Check if topic extraction was successful")
            return
        st.session_state.analytics_data = analytics_data

    analytics = st.session_state.analytics_data
    
    # Validate analytics data structure
    if not isinstance(analytics, dict):
        st.error(f"Invalid analytics data type: {type(analytics)}")
        return
        
    required_keys = ["topic_wise_insights", "ai_recommended_actions", "student_analytics"]
    missing_keys = [key for key in required_keys if key not in analytics]
    if missing_keys:
        st.error(f"Missing required keys in analytics data: {missing_keys}")
        return

    # Initialize topic indices only if we have valid data
    if 'topic_indices' not in st.session_state:
        try:
            st.session_state.topic_indices = list(range(len(analytics["topic_wise_insights"])))
        except Exception as e:
            st.error(f"Error creating topic indices: {str(e)}")
            st.write("Analytics data structure:", analytics)
            return

    # Enhanced CSS for better styling and interactivity
    st.markdown("""
        <style>
        /* General styles */
        .section-title {
            color: #1a237e;
            font-size: 1.5rem;
            font-weight: 600;
            margin-top: 1rem 0 1rem 0;
        }
        
        /* Topic list styles */
        .topic-list {
            max-width: 800px;
            margin: 0 auto;
        }
        .topic-header {
            background-color: #ffffff;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 1rem 1.25rem;
            margin: 0.5rem 0;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: space-between;
            transition: all 0.2s ease;
        }
        .topic-header:hover {
            background-color: #f8fafc;
            transform: translateX(5px);
        }
        .topic-header h3 {
            color: #1e3a8a;
            font-size: 1.1rem;
            font-weight: 500;
            margin: 0;
        }
        .topic-struggling-rate {
            background-color: #dbeafe;
            padding: 0.25rem 0.75rem;
            border-radius: 16px;
            font-size: 0.85rem;
            color: #1e40af;
        }
        .topic-content {
            background-color: #ffffff;
            border: 1px solid #e0e0e0;
            border-top: none;
            border-radius: 0 0 8px 8px;
            padding: 1.25rem;
            margin-top: -0.5rem;
            margin-bottom: 1rem;
        }
        .topic-content .section-heading {
            color: #2c5282;
            font-size: 1rem;
            font-weight: 600;
            margin: 1rem 0 0.5rem 0;
        }
        .topic-content ul {
            margin: 0;
            padding-left: 1.25rem;
            font-size: 0.85rem;
            color: #4a5568;
        }
        
        /* Recommendation card styles */
        .recommendation-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 1rem;
            margin: 1rem 0;
        }
        .recommendation-card {
            background-color: #f8fafc;
            border-radius: 8px;
            padding: 1.25rem;
            border-left: 4px solid #3b82f6;
            margin-bottom: 1rem;
        }
        .recommendation-card h4 {
            color: #1e40af;
            font-size: 1rem;
            font-weight: 600;
            margin-bottom: 0;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        .recommendation-card .priority-badge {
            font-size: 0.75rem;
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            background-color: #dbeafe;
            color: #1e40af;
            text-transform: uppercase;
        }
        
        /* Student analytics styles */
        .student-filters {
            background-color: #f8fafc;
            padding: 1rem;
            border-radius: 8px;
            margin-bottom: 1rem;
        }
        .analytics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1rem;
            margin-top: 1rem;
        }
        .student-metrics-card {
            background-color: #ffffff;
            border-radius: 8px;
            padding: 1rem;
            border: 1px solid #e5e7eb;
            margin-bottom: 1rem;
        }
        .student-metrics-card .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.75rem;
        }
        .student-metrics-card .student-id {
            color: #1e40af;
            font-size: 1rem;
            font-weight: 600;
        }
        .student-metrics-card .metrics-grid {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 0.75rem;
        }
        .metric-box {
            background-color: #f8fafc;
            padding: 0.75rem;
            border-radius: 6px;
        }
        .metric-box .label {
            font-size: 0.9rem;
            color: #6b7280;
            margin-bottom: 0.25rem;
            font-weight: 500;
        }
        .metric-box .value {
            font-size: 0.9rem;
            color: #1f2937;
            font-weight: 600;
        }
        .struggling-topics {
            grid-column: span 2;
            margin-top: 0.5rem;
        }
        .struggling-topics .label{
            font-size: 0.9rem;
            font-weight: 600;        
        }
        .struggling-topics .value{
            font-size: 0.9rem;
            font-weight: 500;        
        }
        .recommendation-text {
            grid-column: span 2;
            font-size: 0.95rem;
            color: #4b5563;
            margin-top: 0.75rem;
            padding-top: 0.75rem;
            border-top: 1px solid #e5e7eb;
        }
        .reason{
            font-size: 1rem;
            font-weight: 600;
        }
        </style>
    """, unsafe_allow_html=True)

    # Topic-wise Analytics Section
    st.markdown('<h2 class="section-title">Topic-wise Analytics</h2>', unsafe_allow_html=True)
    
    # Initialize session state for topic expansion
    if 'expanded_topic' not in st.session_state:
        st.session_state.expanded_topic = None
    
    # Store topic indices in session state if not already done
    if 'topic_indices' not in st.session_state:
        st.session_state.topic_indices = list(range(len(analytics["topic_wise_insights"])))

    if st.session_state.topic_indices: 
        st.markdown('<div class="topic-list">', unsafe_allow_html=True)
        for idx in st.session_state.topic_indices:
            topic = analytics["topic_wise_insights"][idx]
            topic_id = f"topic_{idx}"
            
            # Create clickable header
            col1, col2 = st.columns([3, 1])
            with col1:
                if st.button(
                    topic["topic"],
                    key=f"topic_button_{idx}",
                    use_container_width=True,
                    type="secondary"
                ):
                    st.session_state.expanded_topic = topic_id if st.session_state.expanded_topic != topic_id else None
            
            with col2:
                st.markdown(f"""
                    <div style="text-align: right;">
                        <span class="topic-struggling-rate">{topic["struggling_percentage"]*100:.1f}% Struggling</span>
                    </div>
                """, unsafe_allow_html=True)
            
            # Show content if topic is expanded
            if st.session_state.expanded_topic == topic_id:
                st.markdown(f"""
                    <div class="topic-content">
                        <div class="section-heading">Key Issues</div>
                        <ul>
                            {"".join([f"<li>{issue}</li>" for issue in topic["key_issues"]])}
                        </ul>
                        <div class="section-heading">Key Misconceptions</div>
                        <ul>
                            {"".join([f"<li>{misc}</li>" for misc in topic["key_misconceptions"]])}
                        </ul>
                    </div>
                """, unsafe_allow_html=True)
        st.markdown('</div>', unsafe_allow_html=True)

        # AI Recommendations Section
        st.markdown('<h2 class="section-title">AI-Powered Recommendations</h2>', unsafe_allow_html=True)
        st.markdown('<div class="recommendation-grid">', unsafe_allow_html=True)
        for idx, rec in enumerate(analytics["ai_recommended_actions"]):
            st.markdown(f"""
                <div class="recommendation-card">
                    <h4>
                        <span>Recommendation {idx + 1}</span>
                        <span class="priority-badge">{rec["priority"]}</span>
                    </h4>
                    <p>{rec["action"]}</p>
                    <p><span class="reason">Reason:</span>  {rec["reasoning"]}</p>
                    <p><span class="reason">Expected Outcome:</span>  {rec["expected_outcome"]}</p>
                </div>
            """, unsafe_allow_html=True)
        st.markdown('</div>', unsafe_allow_html=True)

        # Student Analytics Section
        st.markdown('<h2 class="section-title">Student Analytics</h2>', unsafe_allow_html=True)
        
        # Filters
        with st.container():
            # st.markdown('<div class="student-filters">', unsafe_allow_html=True)
            col1, col2, col3 = st.columns(3)
            with col1:
                concept_understanding = st.selectbox(
                    "Filter by Understanding",
                    ["All", "Strong", "Moderate", "Needs Improvement"]
                )
            with col2:
                participation_level = st.selectbox(
                    "Filter by Participation",
                    ["All", "High (>80%)", "Medium (50-80%)", "Low (<50%)"]
                )
            with col3:
                struggling_topic = st.selectbox(
                    "Filter by Struggling Topic",
                    ["All"] + list(set([topic for student in analytics["student_analytics"] 
                                    for topic in student["struggling_topics"]]))
                )
            # st.markdown('</div>', unsafe_allow_html=True)

        # Display student metrics in a grid
        st.markdown('<div class="analytics-grid">', unsafe_allow_html=True)

        student_ids = [student["student_id"] for student in analytics["student_analytics"]]
        student_names = {str(student["_id"]): student["full_name"] for student in students_collection.find({"_id": {"$in": [ObjectId(sid) for sid in student_ids]}})}

            # Display student metrics in a grid
        st.markdown('<div class="analytics-grid">', unsafe_allow_html=True)
        for student in analytics["student_analytics"]:
            # Apply filters
            if (concept_understanding != "All" and 
                student["engagement_metrics"]["concept_understanding"].replace("_", " ").title() != concept_understanding):
                continue
                
            participation = student["engagement_metrics"]["participation_level"] * 100
            if participation_level != "All":
                if participation_level == "High (>80%)" and participation <= 80:
                    continue
                elif participation_level == "Medium (50-80%)" and (participation < 50 or participation > 80):
                    continue
                elif participation_level == "Low (<50%)" and participation >= 50:
                    continue
                    
            if struggling_topic != "All" and struggling_topic not in student["struggling_topics"]:
                continue

            student_name = student_names.get(student["student_id"], "Unknown Student")

            st.markdown(f"""
                <div class="student-metrics-card">
                    <div class="header">
                        <span class="student-id">Student: {student_name}</span>
                    </div>
                    <div class="metrics-grid">
                        <div class="metric-box">
                            <div class="label">Participation</div>
                            <div class="value">{student["engagement_metrics"]["participation_level"]*100:.1f}%</div>
                        </div>
                        <div class="metric-box">
                            <div class="label">Understanding</div>
                            <div class="value">{student["engagement_metrics"]["concept_understanding"].replace('_', ' ').title()}</div>
                        </div>
                        <div class="struggling-topics">
                            <div class="label">Struggling Topics: </div>
                            <div class="value">{", ".join(student["struggling_topics"]) if student["struggling_topics"] else "None"}</div>
                        </div>
                        <div class="recommendation-text">
                            {student["personalized_recommendation"]}
                        </div>
                    </div>
                </div>
            """, unsafe_allow_html=True)
        st.markdown('</div>', unsafe_allow_html=True)

def reset_analytics_state():
    """
    Helper function to reset the analytics state when needed
    (e.g., when loading a new session or when data needs to be refreshed)
    """
    if 'analytics_data' in st.session_state:
        del st.session_state.analytics_data
    if 'expanded_topic' in st.session_state:
        del st.session_state.expanded_topic
    if 'topic_indices' in st.session_state:
        del st.session_state.topic_indice

def display_session_analytics(session, course_id):
    """Display session analytics for faculty"""
    st.header("Session Analytics")

    # Display Pre-class Analytics
    display_preclass_analytics2(session, course_id)

    # Display In-class Analytics
    display_inclass_analytics(session, course_id)

    # Display Post-class Analytics
    display_postclass_analytics(session, course_id)
    
# def upload_preclass_materials(session_id, course_id):
#     """Upload pre-class materials for a session"""
#     st.subheader("Upload Pre-class Materials")
    
#     # File upload section
#     uploaded_file = st.file_uploader("Upload Material", type=['txt', 'pdf', 'docx'])
#     if uploaded_file is not None:
#         with st.spinner("Processing document..."):
#             file_name = uploaded_file.name
#             file_content = extract_text_from_file(uploaded_file)
#             if file_content:
#                 material_type = st.selectbox("Select Material Type", ["pdf", "docx", "txt"])
#                 if st.button("Upload Material"):
#                     upload_resource(course_id, session_id, file_name, uploaded_file, material_type)

#                     # Search for the newly uploaded resource's _id in resources_collection
#                     resource_id = resources_collection.find_one({"file_name": file_name})["_id"]
#                     create_vector_store(file_content, resource_id)
#                     st.success("Material uploaded successfully!")
                    
#     # Display existing materials
#     materials = resources_collection.find({"course_id": course_id, "session_id": session_id})
#     for material in materials:
#         st.markdown(f"""
#         * **{material['file_name']}** ({material['material_type']})  
#             Uploaded on: {material['uploaded_at'].strftime('%Y-%m-%d %H:%M')}
#         """)

def display_quiz_tab(student_id, course_id, session_id):
    """Display quizzes for students"""
    st.header("Course Quizzes")
    
    # Get available quizzes for this session
    quizzes = quizzes_collection.find({
        "course_id": course_id,
        "session_id": session_id,
        "status": "active"
    })
    
    quizzes = list(quizzes)
    if not quizzes:
        st.info("No quizzes available for this session.")
        return
    
    for quiz in quizzes:
        with st.expander(f"πŸ“ {quiz['title']}", expanded=True):
            # Check if student has already taken this quiz
            existing_score = get_student_quiz_score(quiz['_id'], student_id)
            
            if existing_score is not None:
                st.success(f"Quiz completed! Your score: {existing_score:.1f}%")
                
                # Display correct answers after submission
                st.subheader("Quiz Review")
                for i, question in enumerate(quiz['questions']):
                    st.markdown(f"**Question {i+1}:** {question['question']}")
                    for opt in question['options']:
                        if opt.startswith(question['correct_option']):
                            st.markdown(f"βœ… {opt}")
                        else:
                            st.markdown(f"- {opt}")
                
            else:
                # Display quiz questions
                st.write("Please select your answers:")
                
                # Create a form for quiz submission
                with st.form(f"quiz_form_{quiz['_id']}"):
                    student_answers = {}
                    
                    for i, question in enumerate(quiz['questions']):
                        st.markdown(f"**Question {i+1}:** {question['question']}")
                        options = [opt for opt in question['options']]
                        student_answers[str(i)] = st.radio(
                            f"Select answer for question {i+1}:",
                            options=options,
                            key=f"q_{quiz['_id']}_{i}"
                        )
                    
                    # Submit button
                    if st.form_submit_button("Submit Quiz"):
                        print(student_answers)
                        score = submit_quiz_answers(quiz['_id'], student_id, student_answers)
                        if score is not None:
                            st.success(f"Quiz submitted successfully! Your score: {score:.1f}%")
                            st.rerun()  # Refresh to show results
                        else:
                            st.error("Error submitting quiz. Please try again.")

def display_surprise_quiz_tab(student_id, course_id, session_id):
    """Display quizzes for students"""
    st.header("Surprise Quizzes")

    # Get available quizzes for this session
    quizzes = surprise_quizzes_collection.find(
        {"course_id": course_id, "session_id": session_id, "status": "active"}
    )

    quizzes = list(quizzes)
    if not quizzes:
        st.info("No surprise quizzes available for this session.")
        return

    for quiz in quizzes:
        with st.expander(f"πŸ“ {quiz['title']}", expanded=True):
            # Check if student has already taken this quiz
            existing_score = get_student_surprise_quiz_score(quiz["_id"], student_id)
            st.info("Deadline for this quiz is " + str(quiz['created_at'] + timedelta(minutes=quiz['no_minutes'])))

            if existing_score is not None:
                st.success(f"Quiz completed! Your score: {existing_score:.1f}%")

                # Display correct answers after submission
                st.subheader("Quiz Review")
                for i, question in enumerate(quiz["questions"]):
                    st.markdown(f"**Question {i+1}:** {question['question']}")
                    for opt in question["options"]:
                        if opt.startswith(question["correct_option"]):
                            st.markdown(f"βœ… {opt}")
                        else:
                            st.markdown(f"- {opt}")
                # if quiz["created_at"] + timedelta(minutes=quiz["no_minutes"]) < datetime.now():
                #     print(quiz["created_at"])
                #     print(datetime.now())
                #     print(quiz["created_at"] + timedelta(minutes=quiz["no_minutes"]))
                #     print(type(quiz["created_at"]))
                #     st.error("You didn't submit the quiz on time")

            else:
                # Display quiz questions
                st.write("Please select your answers:")

                # Create a form for quiz submission
                with st.form(f"surprize_quiz_form_{quiz['_id']}"):
                    student_answers = {}

                    for i, question in enumerate(quiz["questions"]):
                        st.markdown(f"**Question {i+1}:** {question['question']}")
                        options = [opt for opt in question["options"]]
                        student_answers[str(i)] = st.radio(
                            f"Select answer for question {i+1}:",
                            options=options,
                            key=f"q_{quiz['_id']}_{i}",
                        )

                    # Submit button
                    if st.form_submit_button("Submit Surprise Quiz"):
                        print(student_answers)
                        if quiz["created_at"] + timedelta(minutes=quiz["no_minutes"]) >= datetime.now():
                            score = submit_surprise_quiz_answers(
                                quiz["_id"], student_id, student_answers
                            )
                            if score is not None:
                                st.success(
                                    f"Quiz submitted successfully! Your score: {score:.1f}%"
                                )
                                st.rerun()  # Refresh to show results
                            else:
                                st.error("Error submitting quiz. Please try again.")
                        else:
                            st.error("You didn't submit the quiz on time")



def display_session_content(student_id, course_id, session, username, user_type):
    st.title(f"{session['title']}")

    # Check if the date is a string or a datetime object
    if isinstance(session['date'], str):
        # Convert date string to datetime object
        session_date = datetime.fromisoformat(session['date'])
    else:
        session_date = session['date']

    course_name = courses_collection.find_one({"course_id": course_id})['title']
    
    st.markdown(f"**Date:** {format_datetime(session_date)}")
    st.markdown(f"**Course Name:** {course_name}")

    # Find the course_id of the session in 

    if user_type == 'student':
        # Create all tabs at once for students
        tabs = st.tabs([
            "Pre-class Work",
            "In-class Work", 
            "Post-class Work",
            "Quizzes",
            "Subjective Tests",
            "Group Work",
            "End Terms",
            "Code Playground"
        ])
        if len(tabs) <= 8:
            with tabs[0]:
                display_preclass_content(session, student_id, course_id)
            with tabs[1]:
                display_in_class_content(session, user_type, course_id, user_type)
            with tabs[2]:
                display_post_class_content(session, student_id, course_id)
            with tabs[3]:
                display_quiz_tab(student_id, course_id, session['session_id'])
            with tabs[4]:
                display_subjective_test_tab(student_id, course_id, session['session_id'])
            with tabs[5]:
                st.subheader("Group Work")
                st.info("Group work content will be available soon.")
            with tabs[6]:
                st.subheader("End Terms")
                st.info("End term content will be available soon.")
            with tabs[7]:
                # st.subheader("Code Playground")
                display_code_playground(session, student_id, course_id)
        else:
            st.error("Error creating tabs. Please try again.")
    
    else:  # faculty user
        # Create all tabs at once for faculty
        tabs = st.tabs([
            "Pre-class Work",
            "In-class Work",
            "Post-class Work",
            "Pre-class Analytics",
            "In-class Analytics",
            "Post-class Analytics",
            "Rubrics",
            "End Terms",
            "Evaluate Subjective Tests"
        ])
        with tabs[0]:
            upload_preclass_materials(session['session_id'], course_id, student_id)
        with tabs[1]:
            display_in_class_content(session, user_type, course_id, user_type)
        with tabs[2]:
            display_post_class_content(session, student_id, course_id)
        with tabs[3]:
            display_preclass_analytics2(session, course_id)
        with tabs[4]:
            display_inclass_analytics(session, course_id)
        with tabs[5]:
            display_postclass_analytics(session, course_id)
        with tabs[6]:
            display_rubrics_tab(session, course_id)
        with tabs[7]:
            st.subheader("End Terms")
            st.info("End term content will be available soon.")
        with tabs[8]:  # New tab for evaluation
            display_evaluation_to_faculty(session['session_id'], student_id, course_id)

def parse_model_response(response_text):
    """Enhanced parser for model responses with better error handling.
    
    Args:
        response_text (str): Raw response text from the model
        
    Returns:
        dict or list: Parsed response object
        
    Raises:
        ValueError: If parsing fails
    """
    import json
    import ast
    import re
    
    # Remove markdown formatting and whitespace
    cleaned_text = re.sub(r'```[a-zA-Z]*\n', '', response_text)
    cleaned_text = cleaned_text.replace('```', '').strip()
    
    # Try multiple parsing methods
    parsing_methods = [
        # Method 1: Direct JSON parsing
        lambda x: json.loads(x),
        
        # Method 2: AST literal evaluation
        lambda x: ast.literal_eval(x),
        
        # Method 3: Extract and parse content between curly braces
        lambda x: json.loads(re.search(r'\{.*\}', x, re.DOTALL).group()),
        
        # Method 4: Extract and parse content between square brackets
        lambda x: json.loads(re.search(r'\[.*\]', x, re.DOTALL).group()),
        
        # Method 5: Try to fix common JSON formatting issues and parse
        lambda x: json.loads(x.replace("'", '"').replace('\n', '\\n'))
    ]
    
    last_error = None
    for parse_method in parsing_methods:
        try:
            result = parse_method(cleaned_text)
            if result:  # Ensure we have actual content
                return result
        except Exception as e:
            last_error = e
            continue
            
    raise ValueError(f"Could not parse the model's response: {last_error}")

def generate_questions(context, num_questions, session_title, session_description):
    """Generate subjective questions based on context or session details"""
    try:
        # Construct the prompt
        prompt = f"""You are a professional educator creating {num_questions} subjective questions.
        
        Topic: {session_title}
        Description: {session_description}
        {'Context: ' + context if context else ''}
        
        Generate exactly {num_questions} questions in this specific format:
        [
            {{"question": "Write your first question here?"}},
            {{"question": "Write your second question here?"}}
        ]
        
        Requirements:
        1. Questions must require detailed explanations
        2. Focus on critical thinking and analysis
        3. Ask for specific examples or case studies
        4. Questions should test deep understanding
        
        IMPORTANT: Return ONLY the JSON array. Do not include any additional text or explanations.
        """

        # Generate response
        response = model.generate_content(prompt)
        questions = parse_model_response(response.text)
        
        # Validate response
        if not isinstance(questions, list):
            raise ValueError("Generated content is not a list")
        
        if len(questions) != num_questions:
            raise ValueError(f"Generated {len(questions)} questions instead of {num_questions}")
            
        # Validate each question
        for q in questions:
            if not isinstance(q, dict) or 'question' not in q:
                raise ValueError("Invalid question format")
        
        return questions

    except Exception as e:
        print(f"Error generating questions: {str(e)}")
        return None

def pre_generate_questions(context, num_questions, session_title, session_description):
    """Generate subjective questions based on context or session details"""
    try:
        # Construct the prompt
        prompt = f"""You are a professional educator creating {num_questions} subjective questions for asking before the class.
        
        Topic: {session_title}
        Description: {session_description}
        {'Context: ' + context if context else ''}
        
        Generate exactly {num_questions} questions in this specific format:
        [
            {{"question": "Write your first question here?"}},
            {{"question": "Write your second question here?"}}
        ]
        
        Requirements:
        1. Questions should ask something about prerequisites or prior knowledge
        2. Focus on critical thinking and analysis
        3. Ask for specific examples or case studies
        4. Questions should test deep understanding
        
        IMPORTANT: Return ONLY the JSON array. Do not include any additional text or explanations.
        """

        # Generate response
        response = model.generate_content(prompt)
        questions = parse_model_response(response.text)

        # Validate response
        if not isinstance(questions, list):
            raise ValueError("Generated content is not a list")

        if len(questions) != num_questions:
            raise ValueError(
                f"Generated {len(questions)} questions instead of {num_questions}"
            )

        # Validate each question
        for q in questions:
            if not isinstance(q, dict) or "question" not in q:
                raise ValueError("Invalid question format")

        return questions

    except Exception as e:
        print(f"Error generating questions: {str(e)}")
        return None



def generate_synoptic(questions, context, session_title, num_questions):
    """Generate synoptic answers for the questions with improved error handling and response validation.
    
    Args:
        questions (list): List of question dictionaries
        context (str): Additional context for answer generation
        session_title (str): Title of the session
        num_questions (int): Expected number of questions
        
    Returns:
        list: List of synoptic answers or None if generation fails
    """
    try:
        # First, let's validate our input
        if not questions or not isinstance(questions, list):
            raise ValueError("Questions must be provided as a non-empty list")
            
        # Format questions for better prompt clarity
        formatted_questions = "\n".join(
            f"{i+1}. {q['question']}" 
            for i, q in enumerate(questions)
        )
        
        # Construct a more structured prompt
        prompt = f"""You are a subject matter expert creating detailed model answers for {num_questions} questions about {session_title}.

        Here are the questions:
        {formatted_questions}
        {f'Additional context: {context}' if context else ''}

        Please provide {num_questions} comprehensive answers following this JSON format:
        {{
            "answers": [
                {{
                    "answer": "Your detailed answer for question 1...",
                    "key_points": ["Point 1", "Point 2", "Point 3"]
                }},
                {{
                    "answer": "Your detailed answer for question 2...",
                    "key_points": ["Point 1", "Point 2", "Point 3"]
                }}
            ]
        }}

        Requirements for each answer:
        1. Minimum 150 words
        2. Include specific examples and evidence
        3. Reference key concepts and terminology
        4. Demonstrate critical analysis
        5. Structure with clear introduction, body, and conclusion

        IMPORTANT: Return ONLY the JSON object with the answers array. No additional text.
        """

        # Generate response
        response = model.generate_content(prompt)
        
        # Parse and validate the response
        parsed_response = parse_model_response(response.text)
        
        # Additional validation of parsed response
        if not isinstance(parsed_response, (dict, list)):
            raise ValueError("Response must be a dictionary or list")
            
        # Handle both possible valid response formats
        if isinstance(parsed_response, dict):
            answers = parsed_response.get('answers', [])
        else:  # If it's a list
            answers = parsed_response
        
        # Validate answer count
        if len(answers) != num_questions:
            raise ValueError(f"Expected {num_questions} answers, got {len(answers)}")
        
        # Extract just the answer texts for consistency with existing code
        final_answers = []
        for ans in answers:
            if isinstance(ans, dict):
                answer_text = ans.get('answer', '')
                key_points = ans.get('key_points', [])
                formatted_answer = f"{answer_text}\n\nKey Points:\n" + "\n".join(f"β€’ {point}" for point in key_points)
                final_answers.append(formatted_answer)
            else:
                final_answers.append(str(ans))
        
        # Final validation of the answers
        for i, answer in enumerate(final_answers):
            if not answer or len(answer.split()) < 50:  # Basic length check
                raise ValueError(f"Answer {i+1} is too short or empty")
        
        # Save the synoptic to the synoptic_store collection
        synoptic_data = {
            "session_title": session_title,
            "questions": questions,
            "synoptic": final_answers,
            "created_at": datetime.utcnow()
        }
        synoptic_store_collection.insert_one(synoptic_data)
        
        return final_answers

    except Exception as e:
        # Log the error for debugging
        print(f"Error in generate_synoptic: {str(e)}")
        print(f"Response text: {response.text if 'response' in locals() else 'No response generated'}")
        return None

def save_subjective_test(course_id, session_id, title, questions):
    """Save subjective test to database with proper ID handling"""
    try:
        # Ensure proper string format for IDs
        course_id = str(course_id)
        session_id = str(session_id)
        
        # Format questions
        formatted_questions = []
        for q in questions:
            formatted_question = {
                "question": q["question"],
                "expected_points": [],
                "difficulty_level": "medium",
                "suggested_time": "5 minutes"
            }
            formatted_questions.append(formatted_question)

        test_data = {
            "course_id": course_id,
            "session_id": session_id,
            "title": title,
            "questions": formatted_questions,
            "created_at": datetime.utcnow(),
            "status": "active",
            "submissions": []
        }
        
        result = subjective_tests_collection.insert_one(test_data)
        return str(result.inserted_id)
    except Exception as e:
        print(f"Error saving test: {e}")
        return None


def pre_save_subjective_test(course_id, session_id, title, questions):
    """Save subjective test to database with proper ID handling"""
    try:
        # Ensure proper string format for IDs
        course_id = str(course_id)
        session_id = str(session_id)

        # Format questions
        formatted_questions = []
        for q in questions:
            formatted_question = {
                "question": q["question"],
                "expected_points": [],
                "difficulty_level": "medium",
                "suggested_time": "5 minutes",
            }
            formatted_questions.append(formatted_question)

        test_data = {
            "course_id": course_id,
            "session_id": session_id,
            "title": title,
            "questions": formatted_questions,
            "created_at": datetime.utcnow(),
            "status": "active",
            "submissions": [],
        }

        result = pre_subjective_tests_collection.insert_one(test_data)
        return str(result.inserted_id)
    except Exception as e:
        print(f"Error saving test: {e}")
        return None


def submit_subjective_test(test_id, student_id, answers):
    """Submit test answers with proper ID handling"""
    try:
        # Ensure IDs are strings
        test_id = str(test_id)
        student_id = str(student_id)
        
        # Create submission document
        submission = {
            "student_id": student_id,
            "answers": answers,
            "submitted_at": datetime.utcnow(),
            "status": "submitted"
        }
        
        # Update test document with new submission
        result = subjective_tests_collection.update_one(
            {"_id": ObjectId(test_id)},
            {"$push": {"submissions": submission}}
        )
        
        return result.modified_count > 0
    except Exception as e:
        print(f"Error submitting test: {e}")
        return False

    
def submit_pre_subjective_test(test_id, student_id, answers):
    """Submit test answers with proper ID handling"""
    try:
        # Ensure IDs are strings
        test_id = str(test_id)
        student_id = str(student_id)

        # Create submission document
        submission = {
            "student_id": student_id,
            "answers": answers,
            "submitted_at": datetime.utcnow(),
            "status": "submitted",
        }

        # Update test document with new submission
        result = pre_subjective_tests_collection.update_one(
            {"_id": ObjectId(test_id)}, {"$push": {"submissions": submission}}
        )

        return result.modified_count > 0
    except Exception as e:
        print(f"Error submitting test: {e}")
        return False


def display_subjective_test_tab(student_id, course_id, session_id):
    """Display subjective tests and results for students"""
    st.header("Subjective Tests")
    
    try:
        subjective_tests = list(subjective_tests_collection.find({
            "course_id": course_id,
            "session_id": session_id,
            "status": "active"
        }))

        if not subjective_tests:
            st.info("No subjective tests available for this session.")
            return

        # Create tabs for Tests and Results
        test_tab, results_tab = st.tabs(["Available Tests", "Test Results"])
        
        with test_tab:
            for test in subjective_tests:
                with st.expander(f"πŸ“ {test['title']}", expanded=True):
                    # Check for existing submission
                    existing_submission = next(
                        (sub for sub in test.get('submissions', []) 
                         if sub['student_id'] == str(student_id)), 
                        None
                    )
                    
                    if existing_submission:
                        st.success("Test completed! Your answers have been submitted.")
                        st.subheader("Your Answers")
                        for i, ans in enumerate(existing_submission['answers']):
                            st.markdown(f"**Question {i+1}:** {test['questions'][i]['question']}")
                            st.markdown(f"**Your Answer:** {ans}")
                            st.markdown("---")
                    else:
                        st.write("Please write your answers:")
                        with st.form(key=f"subjective_test_form_{test['_id']}"):
                            student_answers = []
                            for i, question in enumerate(test['questions']):
                                st.markdown(f"**Question {i+1}:** {question['question']}")
                                answer = st.text_area(
                                    "Your answer:",
                                    key=f"q_{test['_id']}_{i}",
                                    height=200
                                )
                                student_answers.append(answer)

                            if st.form_submit_button("Submit Test"):
                                if all(answer.strip() for answer in student_answers):
                                    success = submit_subjective_test(
                                        test['_id'],
                                        str(student_id),
                                        student_answers
                                    )
                                    if success:
                                        st.success("Test submitted successfully!")
                                        st.rerun()
                                    else:
                                        st.error("Error submitting test. Please try again.")
                                else:
                                    st.error("Please answer all questions before submitting.")
        
        with results_tab:
            # Display results for completed tests
            completed_tests = [
                test for test in subjective_tests
                if any(sub['student_id'] == str(student_id) for sub in test.get('submissions', []))
            ]
            
            if not completed_tests:
                st.info("You haven't completed any tests yet.")
                return
                
            # Create a selectbox for choosing which test results to view
            test_options = {
                f"{test['title']} (Submitted: {next(sub['submitted_at'].strftime('%Y-%m-%d') for sub in test['submissions'] if sub['student_id'] == str(student_id))})"
                : test['_id']
                for test in completed_tests
            }
            
            selected_test = st.selectbox(
                "Select a test to view results:",
                options=list(test_options.keys())
            )
            
            if selected_test:
                test_id = test_options[selected_test]
                display_test_results(test_id, student_id)
                
    except Exception as e:
        st.error("An error occurred while loading the tests. Please try again later.")
        print(f"Error in display_subjective_test_tab: {str(e)}")


def display_pre_subjective_test_tab(student_id, course_id, session_id):
    """Display subjective tests and results for students"""
    st.markdown("### Pre-class Subjective Questions ")

    try:
        print("course_id", course_id, "session_id", session_id, "student_id", student_id)
        subjective_tests = list(
            pre_subjective_tests_collection.find(
                {"course_id": course_id,"session_id" : str(session_id),  "status": "active"}
            )
        )
        print("subjective_tests", subjective_tests)

        if not subjective_tests:
            print("bruh")
            st.info("No pre subjective questions available for this session.")
            return

        # Create tabs for Tests and Results
        test_tab, results_tab = st.tabs(["Available Tests", "Test Results"])

        with test_tab:
            for test in subjective_tests:
                with st.expander(f"πŸ“ {test['title']}", expanded=True):
                    # Check for existing submission
                    existing_submission = next(
                        (
                            sub
                            for sub in test.get("submissions", [])
                            if sub["student_id"] == str(student_id)
                        ),
                        None,
                    )

                    if existing_submission:
                        st.success("Test completed! Your answers have been submitted.")
                        st.subheader("Your Answers")
                        for i, ans in enumerate(existing_submission["answers"]):
                            st.markdown(
                                f"**Question {i+1}:** {test['questions'][i]['question']}"
                            )
                            st.markdown(f"**Your Answer:** {ans}")
                            st.markdown("---")
                    else:
                        st.write("Please write your answers:")
                        with st.form(key=f"pre_subjective_test_form_{test['_id']}"):
                            student_answers = []
                            for i, question in enumerate(test["questions"]):
                                st.markdown(
                                    f"**Question {i+1}:** {question['question']}"
                                )
                                answer = st.text_area(
                                    "Your answer:",
                                    key=f"q_{test['_id']}_{i}",
                                    height=200,
                                )
                                student_answers.append(answer)

                            if st.form_submit_button("Submit Pre Test"):
                                if all(answer.strip() for answer in student_answers):
                                    success = submit_pre_subjective_test(
                                        test["_id"], str(student_id), student_answers
                                    )
                                    if success:
                                        st.success("Test submitted successfully!")
                                        st.rerun()
                                    else:
                                        st.error(
                                            "Error submitting test. Please try again."
                                        )
                                else:
                                    st.error(
                                        "Please answer all questions before submitting."
                                    )

        with results_tab:
            # Display results for completed tests
            completed_tests = [
                test
                for test in subjective_tests
                if any(
                    sub["student_id"] == str(student_id)
                    for sub in test.get("submissions", [])
                )
            ]

            if not completed_tests:
                st.info("You haven't completed any tests yet.")
                return

            # Create a selectbox for choosing which test results to view
            test_options = {
                f"{test['title']} (Submitted: {next(sub['submitted_at'].strftime('%Y-%m-%d') for sub in test['submissions'] if sub['student_id'] == str(student_id))})": test[
                    "_id"
                ]
                for test in completed_tests
            }

            selected_test = st.selectbox(
                "Select a test to view results:", options=list(test_options.keys())
            )

            if selected_test:
                test_id = test_options[selected_test]
                display_pre_test_results(test_id, student_id)

    except Exception as e:
        st.error("An error occurred while loading the tests. Please try again later.")
        print(f"Error in display_subjective_test_tab: {str(e)}")



def display_test_results(test_id, student_id):
    """
    Display test results and analysis for a student
    
    Args:
        test_id: ObjectId or str of the test
        student_id: str of the student ID
    """
    try:
        # Fetch analysis from evaluation collection
        analysis = subjective_test_evaluation_collection.find_one({
            "test_id": test_id,
            "student_id": str(student_id)
        })
        
        if not analysis:
            st.info("Analysis will be available soon. Please check back later.")
            return
            
        st.header("Test Analysis")
        
        # Display overall evaluation summary if available
        if "overall_summary" in analysis:
            with st.expander("Overall Performance Summary", expanded=True):
                st.markdown(analysis["overall_summary"])
                
        # Display individual question evaluations
        st.subheader("Question-wise Analysis")
        for eval_item in analysis.get('evaluations', []):
            with st.expander(f"Question {eval_item['question_number']}", expanded=True):
                st.markdown("**Question:**")
                st.markdown(eval_item['question'])
                
                st.markdown("**Your Answer:**")
                st.markdown(eval_item['answer'])
                
                st.markdown("**Evaluation:**")
                st.markdown(eval_item['evaluation'])
                
                # Extract and display score if available
                if "Score:" in eval_item['evaluation']:
                    score_line = next((line for line in eval_item['evaluation'].split('\n') if "Score:" in line), None)
                    if score_line:
                        score = score_line.split("Score:")[1].strip()
                        st.metric("Score", score)
                
                # Display improvement points if available
                if "Key Areas for Improvement" in eval_item['evaluation']:
                    st.markdown("**Areas for Improvement:**")
                    improvement_section = eval_item['evaluation'].split("Key Areas for Improvement")[1]
                    points = [point.strip('- ').strip() for point in improvement_section.split('\n') if point.strip().startswith('-')]
                    for point in points:
                        if point:  # Only display non-empty points
                            st.markdown(f"β€’ {point}")
                
        # Display evaluation timestamp
        if "evaluated_at" in analysis:
            st.caption(f"Analysis generated on: {analysis['evaluated_at'].strftime('%Y-%m-%d %H:%M:%S UTC')}")
            
    except Exception as e:
        st.error("An error occurred while loading the analysis. Please try again later.")
        print(f"Error in display_test_results: {str(e)}")


def display_pre_test_results(test_id, student_id):
    """
    Display test results and analysis for a student

    Args:
        test_id: ObjectId or str of the test
        student_id: str of the student ID
    """
    try:
        # Fetch analysis from evaluation collection
        analysis = pre_subjective_test_evaluation_collection.find_one(
            {"test_id": test_id, "student_id": str(student_id)}
        )

        if not analysis:
            st.info("Analysis will be available soon. Please check back later.")
            return

        st.header("Test Analysis")

        # Display overall evaluation summary if available
        if "overall_summary" in analysis:
            with st.expander("Overall Performance Summary", expanded=True):
                st.markdown(analysis["overall_summary"])

        # Display individual question evaluations
        st.subheader("Question-wise Analysis")
        for eval_item in analysis.get("evaluations", []):
            with st.expander(f"Question {eval_item['question_number']}", expanded=True):
                st.markdown("**Question:**")
                st.markdown(eval_item["question"])

                st.markdown("**Your Answer:**")
                st.markdown(eval_item["answer"])

                st.markdown("**Evaluation:**")
                st.markdown(eval_item["evaluation"])

                # Extract and display score if available
                if "Score:" in eval_item["evaluation"]:
                    score_line = next(
                        (
                            line
                            for line in eval_item["evaluation"].split("\n")
                            if "Score:" in line
                        ),
                        None,
                    )
                    if score_line:
                        score = score_line.split("Score:")[1].strip()
                        st.metric("Score", score)

                # Display improvement points if available
                if "Key Areas for Improvement" in eval_item["evaluation"]:
                    st.markdown("**Areas for Improvement:**")
                    improvement_section = eval_item["evaluation"].split(
                        "Key Areas for Improvement"
                    )[1]
                    points = [
                        point.strip("- ").strip()
                        for point in improvement_section.split("\n")
                        if point.strip().startswith("-")
                    ]
                    for point in points:
                        if point:  # Only display non-empty points
                            st.markdown(f"β€’ {point}")

        # Display evaluation timestamp
        if "evaluated_at" in analysis:
            st.caption(
                f"Analysis generated on: {analysis['evaluated_at'].strftime('%Y-%m-%d %H:%M:%S UTC')}"
            )

    except Exception as e:
        st.error(
            "An error occurred while loading the analysis. Please try again later."
        )
        print(f"Error in display_test_results: {str(e)}")