File size: 63,958 Bytes
aee77fd
 
 
 
75775c4
 
 
 
 
a6cf941
 
 
 
 
 
75775c4
 
 
 
 
 
 
d6f5eba
 
aee77fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75775c4
a6cf941
aee77fd
 
 
 
 
 
 
75775c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6cf941
75775c4
 
 
 
a6cf941
75775c4
a6cf941
75775c4
 
 
a6cf941
 
 
75775c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6cf941
75775c4
 
 
 
 
a6cf941
75775c4
 
 
 
a6cf941
75775c4
 
 
 
 
 
 
 
 
 
 
 
a6cf941
75775c4
aee77fd
 
 
75775c4
 
 
a6cf941
75775c4
 
 
 
aee77fd
75775c4
a6cf941
75775c4
 
a6cf941
75775c4
aee77fd
 
 
 
 
75775c4
a6cf941
aee77fd
 
 
75775c4
aee77fd
 
 
 
75775c4
aee77fd
 
75775c4
 
a6cf941
75775c4
 
 
aee77fd
75775c4
 
 
 
 
d6f5eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75775c4
a6cf941
75775c4
a6cf941
 
 
 
 
 
 
 
 
 
 
 
75775c4
 
a6cf941
75775c4
 
 
 
a6cf941
75775c4
a6cf941
75775c4
 
a6cf941
75775c4
 
 
 
 
 
 
 
 
 
a6cf941
75775c4
 
 
 
 
a6cf941
 
 
75775c4
a6cf941
75775c4
 
 
 
 
 
 
 
 
a6cf941
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75775c4
a6cf941
75775c4
 
a6cf941
75775c4
 
 
 
aee77fd
 
a6cf941
 
 
75775c4
 
aee77fd
75775c4
 
 
993126d
 
 
75775c4
 
993126d
 
 
75775c4
 
 
 
 
 
 
a6cf941
75775c4
 
 
 
a6cf941
 
75775c4
aee77fd
a6cf941
aee77fd
 
 
d6f5eba
 
 
 
aee77fd
 
 
a6cf941
aee77fd
d6f5eba
a6cf941
d6f5eba
a6cf941
aee77fd
d6f5eba
aee77fd
75775c4
 
 
 
 
a6cf941
d6f5eba
75775c4
 
 
 
 
 
aee77fd
75775c4
 
 
 
d6f5eba
aee77fd
 
d6f5eba
a6cf941
d6f5eba
 
 
 
 
 
a6cf941
d6f5eba
75775c4
d6f5eba
 
 
75775c4
d6f5eba
 
 
 
 
 
a6cf941
d6f5eba
a6cf941
d6f5eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aee77fd
d6f5eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75775c4
 
 
 
 
aee77fd
a6cf941
75775c4
 
 
 
 
a6cf941
75775c4
 
 
 
 
 
 
a6cf941
 
75775c4
 
aee77fd
75775c4
 
d6f5eba
 
 
 
 
aee77fd
 
75775c4
 
 
a6cf941
75775c4
a6cf941
 
 
 
 
 
 
 
75775c4
a6cf941
 
 
 
75775c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6cf941
 
75775c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6cf941
 
 
 
75775c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6cf941
75775c4
 
a6cf941
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75775c4
 
 
 
 
a6cf941
75775c4
 
2bc1f40
75775c4
 
 
 
 
 
a6cf941
75775c4
 
 
aee77fd
a6cf941
75775c4
 
 
 
a6cf941
75775c4
 
 
 
 
a6cf941
75775c4
 
a6cf941
 
 
 
 
 
 
75775c4
 
a6cf941
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75775c4
a6cf941
75775c4
 
 
 
 
a6cf941
75775c4
 
a6cf941
75775c4
a6cf941
75775c4
 
a6cf941
75775c4
 
 
aee77fd
 
75775c4
 
 
 
 
 
 
 
aee77fd
75775c4
 
 
 
aee77fd
75775c4
 
 
 
 
 
 
 
aee77fd
75775c4
 
 
 
 
 
 
 
 
a6cf941
75775c4
 
a6cf941
75775c4
 
 
 
 
a6cf941
75775c4
 
 
 
 
a6cf941
75775c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6cf941
75775c4
 
a6cf941
75775c4
a6cf941
 
 
 
 
 
 
 
 
 
75775c4
a6cf941
 
 
75775c4
a6cf941
75775c4
a6cf941
75775c4
 
 
aee77fd
a6cf941
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aee77fd
75775c4
 
 
 
a6cf941
d6f5eba
75775c4
 
a6cf941
75775c4
a6cf941
aee77fd
75775c4
 
 
 
 
aee77fd
d6f5eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6cf941
75775c4
d6f5eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75775c4
a6cf941
d6f5eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6cf941
d6f5eba
 
 
 
 
 
 
 
a6cf941
d6f5eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75775c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aee77fd
75775c4
 
 
d6f5eba
 
75775c4
 
d6f5eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75775c4
 
 
 
a6cf941
 
 
75775c4
d6f5eba
75775c4
a6cf941
 
d6f5eba
 
a6cf941
d6f5eba
 
 
 
a6cf941
75775c4
 
 
d6f5eba
 
75775c4
d6f5eba
 
 
 
 
 
 
 
 
75775c4
a6cf941
75775c4
 
 
 
 
 
 
 
d6f5eba
 
75775c4
 
 
 
d6f5eba
 
75775c4
d6f5eba
 
 
75775c4
a6cf941
 
75775c4
a6cf941
75775c4
 
 
a6cf941
75775c4
a6cf941
 
75775c4
a6cf941
 
 
 
 
 
 
 
 
 
 
d6f5eba
 
 
 
 
 
a6cf941
 
75775c4
 
d6f5eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75775c4
 
 
d6f5eba
 
75775c4
d6f5eba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a6cf941
75775c4
aee77fd
75775c4
 
 
 
 
d6f5eba
 
 
a6cf941
75775c4
 
 
a6cf941
75775c4
 
a6cf941
75775c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aee77fd
 
75775c4
aee77fd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
from openai import OpenAI
from pydantic import BaseModel
from typing import List, Optional
import gradio as gr
import os
import logging
from logging.handlers import RotatingFileHandler
import sys
from functools import lru_cache
from tenacity import (
    retry,
    stop_after_attempt,
    wait_exponential,
    retry_if_exception_type,
)
import hashlib
import genanki
import random
import json
import tempfile
from pathlib import Path
import pandas as pd
import requests
from bs4 import BeautifulSoup


class Step(BaseModel):
    explanation: str
    output: str


class Subtopics(BaseModel):
    steps: List[Step]
    result: List[str]


class Topics(BaseModel):
    result: List[Subtopics]


class CardFront(BaseModel):
    question: Optional[str] = None


class CardBack(BaseModel):
    answer: Optional[str] = None
    explanation: str
    example: str


class Card(BaseModel):
    front: CardFront
    back: CardBack
    metadata: Optional[dict] = None
    card_type: str = "basic"  # Add card_type, default to basic


class CardList(BaseModel):
    topic: str
    cards: List[Card]


class ConceptBreakdown(BaseModel):
    main_concept: str
    prerequisites: List[str]
    learning_outcomes: List[str]
    common_misconceptions: List[str]
    difficulty_level: str  # "beginner", "intermediate", "advanced"


class CardGeneration(BaseModel):
    concept: str
    thought_process: str
    verification_steps: List[str]
    card: Card


class LearningSequence(BaseModel):
    topic: str
    concepts: List[ConceptBreakdown]
    cards: List[CardGeneration]
    suggested_study_order: List[str]
    review_recommendations: List[str]


def setup_logging():
    """Configure logging to both file and console"""
    logger = logging.getLogger("ankigen")
    logger.setLevel(logging.DEBUG)

    # Create formatters
    detailed_formatter = logging.Formatter(
        "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
    )
    simple_formatter = logging.Formatter("%(levelname)s: %(message)s")

    # File handler (detailed logging)
    file_handler = RotatingFileHandler(
        "ankigen.log",
        maxBytes=1024 * 1024,  # 1MB
        backupCount=5,
    )
    file_handler.setLevel(logging.DEBUG)
    file_handler.setFormatter(detailed_formatter)

    # Console handler (info and above)
    console_handler = logging.StreamHandler(sys.stdout)
    console_handler.setLevel(logging.INFO)
    console_handler.setFormatter(simple_formatter)

    # Add handlers to logger
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    return logger


# Initialize logger
logger = setup_logging()


# Replace the caching implementation with a proper cache dictionary
_response_cache = {}  # Global cache dictionary


@lru_cache(maxsize=100)
def get_cached_response(cache_key: str):
    """Get response from cache"""
    return _response_cache.get(cache_key)


def set_cached_response(cache_key: str, response):
    """Set response in cache"""
    _response_cache[cache_key] = response


def create_cache_key(prompt: str, model: str) -> str:
    """Create a unique cache key for the API request"""
    return hashlib.md5(f"{model}:{prompt}".encode()).hexdigest()


# Add retry decorator for API calls
@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=4, max=10),
    retry=retry_if_exception_type(Exception),
    before_sleep=lambda retry_state: logger.warning(
        f"Retrying API call (attempt {retry_state.attempt_number})"
    ),
)
def structured_output_completion(
    client, model, response_format, system_prompt, user_prompt
):
    """Make API call with retry logic and caching"""
    cache_key = create_cache_key(f"{system_prompt}:{user_prompt}", model)
    cached_response = get_cached_response(cache_key)

    if cached_response is not None:
        logger.info("Using cached response")
        return cached_response

    try:
        logger.debug(f"Making API call with model {model}")

        # Add JSON instruction to system prompt
        system_prompt = f"{system_prompt}\nProvide your response as a JSON object matching the specified schema."

        completion = client.chat.completions.create(
            model=model,
            messages=[
                {"role": "system", "content": system_prompt.strip()},
                {"role": "user", "content": user_prompt.strip()},
            ],
            response_format={"type": "json_object"},
            temperature=0.7,
        )

        if not hasattr(completion, "choices") or not completion.choices:
            logger.warning("No choices returned in the completion.")
            return None

        first_choice = completion.choices[0]
        if not hasattr(first_choice, "message"):
            logger.warning("No message found in the first choice.")
            return None

        # Parse the JSON response
        result = json.loads(first_choice.message.content)

        # Cache the successful response
        set_cached_response(cache_key, result)
        return result

    except Exception as e:
        logger.error(f"API call failed: {str(e)}", exc_info=True)
        raise


def fetch_webpage_text(url: str) -> str:
    """Fetches and extracts main text content from a URL."""
    try:
        logger.info(f"Fetching content from URL: {url}")
        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, timeout=15)  # Added timeout
        response.raise_for_status()  # Raise HTTPError for bad responses (4xx or 5xx)

        logger.debug(f"Parsing HTML content for {url}")
        # Use lxml for speed if available, fallback to html.parser
        try:
            soup = BeautifulSoup(response.text, "lxml")
        except ImportError:
            logger.warning("lxml not found, using html.parser instead.")
            soup = BeautifulSoup(response.text, "html.parser")

        # Remove script and style elements
        for script_or_style in soup(["script", "style"]):
            script_or_style.extract()

        # Attempt to find main content tags
        main_content = soup.find("main")
        if not main_content:
            main_content = soup.find("article")

        # If specific tags found, use their text, otherwise fallback to body
        if main_content:
            text = main_content.get_text()
            logger.debug(f"Extracted text from <{main_content.name}> tag.")
        else:
            body = soup.find("body")
            if body:
                text = body.get_text()
                logger.debug("Extracted text from <body> tag (fallback).")
            else:
                text = ""  # No body tag found?
                logger.warning(f"Could not find <body> tag in {url}")

        # Break into lines and remove leading/trailing space on each
        lines = (line.strip() for line in text.splitlines())
        # Break multi-headlines into a line each
        chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
        # Drop blank lines
        text = "\n".join(chunk for chunk in chunks if chunk)

        if not text:
            logger.warning(f"Could not extract meaningful text from {url}")
            raise ValueError("Could not extract text content from the URL.")

        logger.info(
            f"Successfully extracted text from {url} (Length: {len(text)} chars)"
        )
        return text

    except requests.exceptions.RequestException as e:
        logger.error(f"Network error fetching URL {url}: {e}")
        raise ConnectionError(f"Could not fetch URL: {e}")
    except Exception as e:
        logger.error(f"Error processing URL {url}: {e}", exc_info=True)
        # Re-raise specific internal errors or a general one
        if isinstance(e, (ValueError, ConnectionError)):
            raise e
        else:
            raise RuntimeError(
                f"An unexpected error occurred while processing the URL: {e}"
            )


def generate_cards_batch(
    client, model, topic, num_cards, system_prompt, generate_cloze=False, batch_size=3
):
    """Generate a batch of cards for a topic, potentially including cloze deletions"""

    cloze_instruction = ""
    if generate_cloze:
        cloze_instruction = """
        Where appropriate, generate Cloze deletion cards.
        - For Cloze cards, set "card_type" to "cloze".
        - Format the question field using Anki's cloze syntax (e.g., "The capital of France is {{c1::Paris}}.").
        - The "answer" field should contain the full, non-cloze text or specific context for the cloze.
        - For standard question/answer cards, set "card_type" to "basic".
        """

    cards_prompt = f"""
    Generate {num_cards} flashcards for the topic: {topic}
    {cloze_instruction}
    Return your response as a JSON object with the following structure:
    {{
        "cards": [
            {{
                "card_type": "basic or cloze",
                "front": {{
                    "question": "question text (potentially with {{c1::cloze syntax}})"
                }},
                "back": {{
                    "answer": "concise answer or full text for cloze",
                    "explanation": "detailed explanation",
                    "example": "practical example"
                }},
                "metadata": {{
                    "prerequisites": ["list", "of", "prerequisites"],
                    "learning_outcomes": ["list", "of", "outcomes"],
                    "misconceptions": ["list", "of", "misconceptions"],
                    "difficulty": "beginner/intermediate/advanced"
                }}
            }}
            // ... more cards
        ]
    }}
    """

    try:
        logger.info(
            f"Generating card batch for {topic}, Cloze enabled: {generate_cloze}"
        )
        response = structured_output_completion(
            client, model, {"type": "json_object"}, system_prompt, cards_prompt
        )

        if not response or "cards" not in response:
            logger.error("Invalid cards response format")
            raise ValueError("Failed to generate cards. Please try again.")

        # Convert the JSON response into Card objects
        cards = []
        for card_data in response["cards"]:
            # Ensure required fields are present before creating Card object
            if "front" not in card_data or "back" not in card_data:
                logger.warning(
                    f"Skipping card due to missing front/back data: {card_data}"
                )
                continue
            if "question" not in card_data["front"]:
                logger.warning(f"Skipping card due to missing question: {card_data}")
                continue
            if (
                "answer" not in card_data["back"]
                or "explanation" not in card_data["back"]
                or "example" not in card_data["back"]
            ):
                logger.warning(
                    f"Skipping card due to missing answer/explanation/example: {card_data}"
                )
                continue

            card = Card(
                card_type=card_data.get("card_type", "basic"),
                front=CardFront(**card_data["front"]),
                back=CardBack(**card_data["back"]),
                metadata=card_data.get("metadata", {}),
            )
            cards.append(card)

        return cards

    except Exception as e:
        logger.error(
            f"Failed to generate cards batch for {topic}: {str(e)}", exc_info=True
        )
        raise


# Add near the top with other constants
AVAILABLE_MODELS = [
    {
        "value": "gpt-4.1",  # Corrected model name
        "label": "gpt-4.1 (Best Quality)",  # Corrected label
        "description": "Highest quality, slower generation",  # Corrected description
    },
    {
        "value": "gpt-4.1-nano",
        "label": "gpt-4.1 Nano (Fast & Efficient)",
        "description": "Optimized for speed and lower cost",
    },
]

GENERATION_MODES = [
    {
        "value": "subject",
        "label": "Single Subject",
        "description": "Generate cards for a specific topic",
    },
    {
        "value": "path",
        "label": "Learning Path",
        "description": "Break down a job description or learning goal into subjects",
    },
]


def generate_cards(
    api_key_input,
    subject,
    generation_mode,
    source_text,
    url_input,
    model_name="gpt-4.1-nano",
    topic_number=1,
    cards_per_topic=2,
    preference_prompt="assume I'm a beginner",
    generate_cloze=False,
):
    logger.info(f"Starting card generation in {generation_mode} mode")
    logger.debug(
        f"Parameters: mode={generation_mode}, topics={topic_number}, cards_per_topic={cards_per_topic}, cloze={generate_cloze}"
    )

    # --- Common Setup ---
    if not api_key_input:
        logger.warning("No API key provided")
        raise gr.Error("OpenAI API key is required")
    if not api_key_input.startswith("sk-"):
        logger.warning("Invalid API key format")
        raise gr.Error("Invalid API key format. OpenAI keys should start with 'sk-'")

    # Moved client initialization up
    try:
        logger.debug("Initializing OpenAI client")
        client = OpenAI(api_key=api_key_input)
    except Exception as e:
        logger.error(f"Failed to initialize OpenAI client: {str(e)}", exc_info=True)
        raise gr.Error(f"Failed to initialize OpenAI client: {str(e)}")

    model = model_name
    flattened_data = []
    total = 0
    progress_tracker = gr.Progress(track_tqdm=True)
    # ---------------------

    try:
        page_text_for_generation = ""  # Initialize variable to hold text for AI

        # --- Web Mode --- (Fetch text first)
        if generation_mode == "web":
            logger.info("Generation mode: Web")
            if not url_input or not url_input.strip():
                logger.warning("No URL provided for web generation mode.")
                raise gr.Error("URL is required for 'From Web' mode.")

            gr.Info(f"πŸ•ΈοΈ Fetching content from {url_input}...")
            try:
                page_text_for_generation = fetch_webpage_text(url_input)
                gr.Info(
                    f"βœ… Successfully fetched text (approx. {len(page_text_for_generation)} chars). Starting AI generation..."
                )
            except (ConnectionError, ValueError, RuntimeError) as e:
                logger.error(f"Failed to fetch or process URL {url_input}: {e}")
                raise gr.Error(
                    f"Failed to get content from URL: {e}"
                )  # Display fetch error to user
            except Exception as e:  # Catch any other unexpected errors during fetch
                logger.error(
                    f"Unexpected error fetching URL {url_input}: {e}", exc_info=True
                )
                raise gr.Error(f"An unexpected error occurred fetching the URL.")

        # --- Text Mode --- (Use provided text)
        elif generation_mode == "text":
            logger.info("Generation mode: Text Input")
            if not source_text or not source_text.strip():
                logger.warning("No source text provided for text generation mode.")
                raise gr.Error("Source text is required for 'From Text' mode.")
            page_text_for_generation = source_text  # Use the input text directly
            gr.Info("πŸš€ Starting card generation from text...")

        # --- Generation from Text/Web Content ---
        if generation_mode == "text" or generation_mode == "web":
            # Shared logic for generating cards from fetched/provided text
            text_system_prompt = f"""
            You are an expert educator specializing in extracting key information and creating flashcards from provided text.
            Your goal is to generate clear, concise, and accurate flashcards based *only* on the text given by the user.
            Focus on the most important concepts, definitions, facts, or processes mentioned.
            Generate {cards_per_topic} cards.
            Adhere to the user's learning preferences: {preference_prompt}
            Use the specified JSON output format.
            For explanations and examples:
            - Keep explanations in plain text
            - Format code examples with triple backticks (```)
            - Separate conceptual examples from code examples
            - Use clear, concise language
            """
            json_structure_prompt = """
            Return your response as a JSON object with the following structure:
            {
                "cards": [
                    {
                        "card_type": "basic or cloze",
                        "front": {
                            "question": "question text (potentially with {{c1::cloze syntax}})" 
                        },
                        "back": {
                            "answer": "concise answer or full text for cloze",
                            "explanation": "detailed explanation",
                            "example": "practical example"
                        },
                        "metadata": {
                            "prerequisites": ["list", "of", "prerequisites"],
                            "learning_outcomes": ["list", "of", "outcomes"],
                            "misconceptions": ["list", "of", "misconceptions"],
                            "difficulty": "beginner/intermediate/advanced"
                        }
                    }
                    // ... more cards
                ]
            }
            """
            cloze_instruction = ""
            if generate_cloze:
                cloze_instruction = """
                Where appropriate, generate Cloze deletion cards.
                - For Cloze cards, set "card_type" to "cloze".
                - Format the question field using Anki's cloze syntax (e.g., "The capital of France is {{{{c1::Paris}}}}.").
                - The "answer" field should contain the full, non-cloze text or specific context for the cloze.
                - For standard question/answer cards, set "card_type" to "basic".
                """
            text_user_prompt = f"""
            Generate {cards_per_topic} flashcards based *only* on the following text:
            --- TEXT START ---
            {page_text_for_generation} 
            --- TEXT END ---
            {cloze_instruction}
            {json_structure_prompt}
            """
            response = structured_output_completion(
                client,
                model,
                {"type": "json_object"},
                text_system_prompt,
                text_user_prompt,
            )
            if not response or "cards" not in response:
                logger.error("Invalid cards response format from text generation.")
                raise gr.Error("Failed to generate cards from text. Please try again.")

            # Process the cards (similar to generate_cards_batch processing)
            cards_data = response["cards"]
            topic_name = "From Web" if generation_mode == "web" else "From Text"
            for card_index, card_data in enumerate(cards_data, start=1):
                if "front" not in card_data or "back" not in card_data:
                    logger.warning(
                        f"Skipping card due to missing front/back data: {card_data}"
                    )
                    continue
                if "question" not in card_data["front"]:
                    logger.warning(
                        f"Skipping card due to missing question: {card_data}"
                    )
                    continue
                if (
                    "answer" not in card_data["back"]
                    or "explanation" not in card_data["back"]
                    or "example" not in card_data["back"]
                ):
                    logger.warning(
                        f"Skipping card due to missing answer/explanation/example: {card_data}"
                    )
                    continue

                card = Card(
                    card_type=card_data.get("card_type", "basic"),
                    front=CardFront(**card_data["front"]),
                    back=CardBack(**card_data["back"]),
                    metadata=card_data.get("metadata", {}),
                )
                metadata = card.metadata or {}
                row = [
                    f"1.{card_index}",
                    topic_name,  # Use dynamic topic name
                    card.card_type,
                    card.front.question,
                    card.back.answer,
                    card.back.explanation,
                    card.back.example,
                    metadata.get("prerequisites", []),
                    metadata.get("learning_outcomes", []),
                    metadata.get("misconceptions", []),
                    metadata.get("difficulty", "beginner"),
                ]
                flattened_data.append(row)
                total += 1
            gr.Info(f"βœ… Generated {total} cards from the provided content.")

        # --- Subject Mode --- (Existing logic)
        elif generation_mode == "subject":
            logger.info(f"Generating cards for subject: {subject}")
            if not subject or not subject.strip():
                logger.warning("No subject provided for subject generation mode.")
                raise gr.Error("Subject is required for 'Single Subject' mode.")

            gr.Info("πŸš€ Starting card generation for subject...")

            # Note: system_prompt uses subject variable
            system_prompt = f"""
            You are an expert educator in {subject}, creating an optimized learning sequence.
            Your goal is to:
            1. Break down the subject into logical concepts
            2. Identify prerequisites and learning outcomes
            3. Generate cards that build upon each other
            4. Address and correct common misconceptions
            5. Include verification steps to minimize hallucinations
            6. Provide a recommended study order

            For explanations and examples:
            - Keep explanations in plain text
            - Format code examples with triple backticks (```)
            - Separate conceptual examples from code examples
            - Use clear, concise language

            Keep in mind the user's preferences: {preference_prompt}
            """

            topic_prompt = f"""
            Generate the top {topic_number} important subjects to know about {subject} in 
            order of ascending difficulty. Return your response as a JSON object with the following structure:
            {{
                "topics": [
                    {{
                        "name": "topic name",
                        "difficulty": "beginner/intermediate/advanced",
                        "description": "brief description"
                    }}
                ]
            }}
            """

            logger.info("Generating topics...")
            topics_response = structured_output_completion(
                client, model, {"type": "json_object"}, system_prompt, topic_prompt
            )

            if not topics_response or "topics" not in topics_response:
                logger.error("Invalid topics response format")
                raise gr.Error("Failed to generate topics. Please try again.")

            topics = topics_response["topics"]
            gr.Info(f"✨ Generated {len(topics)} topics successfully!")

            # Generate cards for each topic
            for i, topic in enumerate(
                progress_tracker.tqdm(topics, desc="Generating cards")
            ):
                try:
                    # Re-use the system_prompt defined above for topic generation
                    cards = generate_cards_batch(
                        client,
                        model,
                        topic["name"],
                        cards_per_topic,
                        system_prompt,  # Use the same system prompt
                        generate_cloze=generate_cloze,
                        batch_size=3,
                    )

                    if cards:
                        for card_index, card in enumerate(cards, start=1):
                            index = f"{i + 1}.{card_index}"
                            metadata = card.metadata or {}

                            row = [
                                index,
                                topic["name"],
                                card.card_type,
                                card.front.question,
                                card.back.answer,
                                card.back.explanation,
                                card.back.example,
                                metadata.get("prerequisites", []),
                                metadata.get("learning_outcomes", []),
                                metadata.get("misconceptions", []),
                                metadata.get("difficulty", "beginner"),
                            ]
                            flattened_data.append(row)
                            total += 1

                        gr.Info(f"βœ… Generated {len(cards)} cards for {topic['name']}")

                except Exception as e:
                    logger.error(
                        f"Failed to generate cards for topic {topic['name']}: {str(e)}"
                    )
                    gr.Warning(f"Failed to generate cards for '{topic['name']}'")
                    continue
        else:
            # Handle other modes or invalid mode if necessary
            logger.error(f"Invalid generation mode: {generation_mode}")
            raise gr.Error(f"Unsupported generation mode: {generation_mode}")

        # --- Common Completion Logic ---
        final_html = f"""
        <div style="text-align: center">
            <p>βœ… Generation complete!</p>
            <p>Total cards generated: {total}</p>
        </div>
        """

        df = pd.DataFrame(
            flattened_data,
            columns=[
                "Index",
                "Topic",
                "Card_Type",
                "Question",
                "Answer",
                "Explanation",
                "Example",
                "Prerequisites",
                "Learning_Outcomes",
                "Common_Misconceptions",
                "Difficulty",
            ],
        )
        return df, final_html, total

    except Exception as e:
        logger.error(f"Card generation failed: {str(e)}", exc_info=True)
        # Check if e is already a gr.Error
        if isinstance(e, gr.Error):
            raise e
        else:
            raise gr.Error(f"Card generation failed: {str(e)}")


# Update the BASIC_MODEL definition with enhanced CSS/HTML
BASIC_MODEL = genanki.Model(
    random.randrange(1 << 30, 1 << 31),
    "AnkiGen Enhanced",
    fields=[
        {"name": "Question"},
        {"name": "Answer"},
        {"name": "Explanation"},
        {"name": "Example"},
        {"name": "Prerequisites"},
        {"name": "Learning_Outcomes"},
        {"name": "Common_Misconceptions"},
        {"name": "Difficulty"},
    ],
    templates=[
        {
            "name": "Card 1",
            "qfmt": """
            <div class="card question-side">
                <div class="difficulty-indicator {{Difficulty}}"></div>
                <div class="content">
                    <div class="question">{{Question}}</div>
                    <div class="prerequisites" onclick="event.stopPropagation();">
                        <div class="prerequisites-toggle">Show Prerequisites</div>
                        <div class="prerequisites-content">{{Prerequisites}}</div>
                    </div>
                </div>
            </div>
            <script>
                document.querySelector('.prerequisites-toggle').addEventListener('click', function(e) {
                    e.stopPropagation();
                    this.parentElement.classList.toggle('show');
                });
            </script>
        """,
            "afmt": """
            <div class="card answer-side">
                <div class="content">
                    <div class="question-section">
                        <div class="question">{{Question}}</div>
                        <div class="prerequisites">
                            <strong>Prerequisites:</strong> {{Prerequisites}}
                        </div>
                    </div>
                    <hr>
                    
                    <div class="answer-section">
                        <h3>Answer</h3>
                        <div class="answer">{{Answer}}</div>
                    </div>
                    
                    <div class="explanation-section">
                        <h3>Explanation</h3>
                        <div class="explanation-text">{{Explanation}}</div>
                    </div>
                    
                    <div class="example-section">
                        <h3>Example</h3>
                        <div class="example-text"></div>
                        <pre><code>{{Example}}</code></pre>
                    </div>
                    
                    <div class="metadata-section">
                        <div class="learning-outcomes">
                            <h3>Learning Outcomes</h3>
                            <div>{{Learning_Outcomes}}</div>
                        </div>
                        
                        <div class="misconceptions">
                            <h3>Common Misconceptions - Debunked</h3>
                            <div>{{Common_Misconceptions}}</div>
                        </div>
                        
                        <div class="difficulty">
                            <h3>Difficulty Level</h3>
                            <div>{{Difficulty}}</div>
                        </div>
                    </div>
                </div>
            </div>
        """,
        }
    ],
    css="""
        /* Base styles */
        .card {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            font-size: 16px;
            line-height: 1.6;
            color: #1a1a1a;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #ffffff;
        }
        
        @media (max-width: 768px) {
            .card {
                font-size: 14px;
                padding: 15px;
            }
        }
        
        /* Question side */
        .question-side {
            position: relative;
            min-height: 200px;
        }
        
        .difficulty-indicator {
            position: absolute;
            top: 10px;
            right: 10px;
            width: 10px;
            height: 10px;
            border-radius: 50%;
        }
        
        .difficulty-indicator.beginner { background: #4ade80; }
        .difficulty-indicator.intermediate { background: #fbbf24; }
        .difficulty-indicator.advanced { background: #ef4444; }
        
        .question {
            font-size: 1.3em;
            font-weight: 600;
            color: #2563eb;
            margin-bottom: 1.5em;
        }
        
        .prerequisites {
            margin-top: 1em;
            font-size: 0.9em;
            color: #666;
        }
        
        .prerequisites-toggle {
            color: #2563eb;
            cursor: pointer;
            text-decoration: underline;
        }
        
        .prerequisites-content {
            display: none;
            margin-top: 0.5em;
            padding: 0.5em;
            background: #f8fafc;
            border-radius: 4px;
        }
        
        .prerequisites.show .prerequisites-content {
            display: block;
        }
        
        /* Answer side */
        .answer-section,
        .explanation-section,
        .example-section {
            margin: 1.5em 0;
            padding: 1.2em;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .answer-section {
            background: #f0f9ff;
            border-left: 4px solid #2563eb;
        }
        
        .explanation-section {
            background: #f0fdf4;
            border-left: 4px solid #4ade80;
        }
        
        .example-section {
            background: #fff7ed;
            border-left: 4px solid #f97316;
        }
        
        /* Code blocks */
        pre code {
            display: block;
            padding: 1em;
            background: #1e293b;
            color: #e2e8f0;
            border-radius: 6px;
            overflow-x: auto;
            font-family: 'Fira Code', 'Consolas', monospace;
            font-size: 0.9em;
        }
        
        /* Metadata tabs */
        .metadata-tabs {
            margin-top: 2em;
            border: 1px solid #e5e7eb;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .tab-buttons {
            display: flex;
            background: #f8fafc;
            border-bottom: 1px solid #e5e7eb;
        }
        
        .tab-btn {
            flex: 1;
            padding: 0.8em;
            border: none;
            background: none;
            cursor: pointer;
            font-weight: 500;
            color: #64748b;
            transition: all 0.2s;
        }
        
        .tab-btn:hover {
            background: #f1f5f9;
        }
        
        .tab-btn.active {
            color: #2563eb;
            background: #fff;
            border-bottom: 2px solid #2563eb;
        }
        
        .tab-content {
            display: none;
            padding: 1.2em;
        }
        
        .tab-content.active {
            display: block;
        }
        
        /* Responsive design */
        @media (max-width: 640px) {
            .tab-buttons {
                flex-direction: column;
            }
            
            .tab-btn {
                width: 100%;
                text-align: left;
                padding: 0.6em;
            }
            
            .answer-section,
            .explanation-section,
            .example-section {
                padding: 1em;
                margin: 1em 0;
            }
        }
        
        /* Animations */
        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }
        
        .card {
            animation: fadeIn 0.3s ease-in-out;
        }
        
        .tab-content.active {
            animation: fadeIn 0.2s ease-in-out;
        }
    """,
)


# Define the Cloze Model (based on Anki's default Cloze type)
CLOZE_MODEL = genanki.Model(
    random.randrange(1 << 30, 1 << 31),  # Needs a unique ID
    "AnkiGen Cloze Enhanced",
    model_type=genanki.Model.CLOZE,  # Specify model type as CLOZE
    fields=[
        {"name": "Text"},  # Field for the text containing the cloze deletion
        {"name": "Extra"},  # Field for additional info shown on the back
        {"name": "Difficulty"},  # Keep metadata
        {"name": "SourceTopic"},  # Add topic info
    ],
    templates=[
        {
            "name": "Cloze Card",
            "qfmt": "{{cloze:Text}}",
            "afmt": """
                {{cloze:Text}}
                <hr>
                <div class="extra-info">{{Extra}}</div>
                <div class="metadata-footer">Difficulty: {{Difficulty}} | Topic: {{SourceTopic}}</div>
            """,
        }
    ],
    css="""
        .card {
            font-family: 'Inter', system-ui, -apple-system, sans-serif;
            font-size: 16px; line-height: 1.6; color: #1a1a1a;
            max-width: 800px; margin: 0 auto; padding: 20px;
            background: #ffffff;
        }
        .cloze {
            font-weight: bold; color: #2563eb;
        }
        .extra-info {
            margin-top: 1em; padding-top: 1em;
            border-top: 1px solid #e5e7eb;
            font-size: 0.95em; color: #333;
            background: #f8fafc; padding: 1em; border-radius: 6px;
        }
        .extra-info h3 { margin-top: 0.5em; font-size: 1.1em; color: #1e293b; }
        .extra-info pre code {
            display: block; padding: 1em; background: #1e293b;
            color: #e2e8f0; border-radius: 6px; overflow-x: auto;
            font-family: 'Fira Code', 'Consolas', monospace; font-size: 0.9em;
            margin-top: 0.5em;
        }
        .metadata-footer {
            margin-top: 1.5em; font-size: 0.85em; color: #64748b; text-align: right;
        }
    """,
)


# Split the export functions
def export_csv(data):
    """Export the generated cards as a CSV file"""
    if data is None:
        raise gr.Error("No data to export. Please generate cards first.")

    if len(data) < 2:  # Minimum 2 cards
        raise gr.Error("Need at least 2 cards to export.")

    try:
        gr.Info("πŸ’Ύ Exporting to CSV...")
        csv_path = "anki_cards.csv"
        data.to_csv(csv_path, index=False)
        gr.Info("βœ… CSV export complete!")
        return gr.File(value=csv_path, visible=True)

    except Exception as e:
        logger.error(f"Failed to export CSV: {str(e)}", exc_info=True)
        raise gr.Error(f"Failed to export CSV: {str(e)}")


def export_deck(data, subject):
    """Export the generated cards as an Anki deck with pedagogical metadata"""
    if data is None:
        raise gr.Error("No data to export. Please generate cards first.")

    if len(data) < 2:  # Minimum 2 cards
        raise gr.Error("Need at least 2 cards to export.")

    try:
        gr.Info("πŸ’Ύ Creating Anki deck...")

        deck_id = random.randrange(1 << 30, 1 << 31)
        deck = genanki.Deck(deck_id, f"AnkiGen - {subject}")

        records = data.to_dict("records")

        # Ensure both models are added to the deck package
        deck.add_model(BASIC_MODEL)
        deck.add_model(CLOZE_MODEL)

        # Add notes to the deck
        for record in records:
            card_type = record.get("Card_Type", "basic").lower()

            if card_type == "cloze":
                # Create Cloze note
                extra_content = f"""
                    <h3>Explanation:</h3>
                    <div>{record["Explanation"]}</div>
                    <h3>Example:</h3>
                    <pre><code>{record["Example"]}</code></pre>
                    <h3>Prerequisites:</h3>
                    <div>{record["Prerequisites"]}</div>
                    <h3>Learning Outcomes:</h3>
                    <div>{record["Learning_Outcomes"]}</div>
                    <h3>Watch out for:</h3>
                    <div>{record["Common_Misconceptions"]}</div>
                """
                note = genanki.Note(
                    model=CLOZE_MODEL,
                    fields=[
                        str(record["Question"]),  # Contains {{c1::...}}
                        extra_content,  # All other info goes here
                        str(record["Difficulty"]),
                        str(record["Topic"]),
                    ],
                )
            else:  # Default to basic card
                # Create Basic note (existing logic)
                note = genanki.Note(
                    model=BASIC_MODEL,
                    fields=[
                        str(record["Question"]),
                        str(record["Answer"]),
                        str(record["Explanation"]),
                        str(record["Example"]),
                        str(record["Prerequisites"]),
                        str(record["Learning_Outcomes"]),
                        str(record["Common_Misconceptions"]),
                        str(record["Difficulty"]),
                    ],
                )

            deck.add_note(note)

        # Create a temporary directory for the package
        with tempfile.TemporaryDirectory() as temp_dir:
            output_path = Path(temp_dir) / "anki_deck.apkg"
            package = genanki.Package(deck)
            package.write_to_file(output_path)

            # Copy to a more permanent location
            final_path = "anki_deck.apkg"
            with open(output_path, "rb") as src, open(final_path, "wb") as dst:
                dst.write(src.read())

        gr.Info("βœ… Anki deck export complete!")
        return gr.File(value=final_path, visible=True)

    except Exception as e:
        logger.error(f"Failed to export Anki deck: {str(e)}", exc_info=True)
        raise gr.Error(f"Failed to export Anki deck: {str(e)}")


# Add this near the top where we define our CSS
js_storage = """
async () => {
    // Load decks from localStorage
    const loadDecks = () => {
        const decks = localStorage.getItem('ankigen_decks');
        return decks ? JSON.parse(decks) : [];
    };

    // Save decks to localStorage
    const saveDecks = (decks) => {
        localStorage.setItem('ankigen_decks', JSON.stringify(decks));
    };

    // Add methods to window for Gradio to access
    window.loadStoredDecks = loadDecks;
    window.saveStoredDecks = saveDecks;
    
    // Initial load
    return loadDecks();
}
"""

# Create a custom theme
custom_theme = gr.themes.Soft().set(
    body_background_fill="*background_fill_secondary",
    block_background_fill="*background_fill_primary",
    block_border_width="0",
    button_primary_background_fill="*primary_500",
    button_primary_text_color="white",
)


def analyze_learning_path(api_key, description, model):
    """Analyze a job description or learning goal to create a structured learning path"""

    try:
        client = OpenAI(api_key=api_key)
    except Exception as e:
        logger.error(f"Failed to initialize OpenAI client: {str(e)}")
        raise gr.Error(f"Failed to initialize OpenAI client: {str(e)}")

    system_prompt = """You are an expert curriculum designer and educational consultant.
    Your task is to analyze learning goals and create structured, achievable learning paths.
    Break down complex topics into manageable subjects, identify prerequisites,
    and suggest practical projects that reinforce learning.
    Focus on creating a logical progression that builds upon previous knowledge."""

    path_prompt = f"""
    Analyze this description and create a structured learning path.
    Return your analysis as a JSON object with the following structure:
    {{
        "subjects": [
            {{
                "Subject": "name of the subject",
                "Prerequisites": "required prior knowledge",
                "Time Estimate": "estimated time to learn"
            }}
        ],
        "learning_order": "recommended sequence of study",
        "projects": "suggested practical projects"
    }}

    Description to analyze:
    {description}
    """

    try:
        response = structured_output_completion(
            client, model, {"type": "json_object"}, system_prompt, path_prompt
        )

        if (
            not response
            or "subjects" not in response
            or "learning_order" not in response
            or "projects" not in response
        ):
            logger.error("Invalid response format from API")
            raise gr.Error("Failed to analyze learning path. Please try again.")

        subjects_df = pd.DataFrame(response["subjects"])
        learning_order_text = (
            f"### Recommended Learning Order\n{response['learning_order']}"
        )
        projects_text = f"### Suggested Projects\n{response['projects']}"

        return subjects_df, learning_order_text, projects_text

    except Exception as e:
        logger.error(f"Failed to analyze learning path: {str(e)}")
        raise gr.Error(f"Failed to analyze learning path: {str(e)}")


# --- Example Data for Initialization ---
example_data = pd.DataFrame(
    [
        [
            "1.1",
            "SQL Basics",
            "basic",
            "What is a SELECT statement used for?",
            "Retrieving data from one or more database tables.",
            "The SELECT statement is the most common command in SQL. It allows you to specify which columns and rows you want to retrieve from a table based on certain conditions.",
            "```sql\\nSELECT column1, column2 FROM my_table WHERE condition;\\n```",
            ["Understanding of database tables"],
            ["Retrieve specific data", "Filter results"],
            ["❌ SELECT * is always efficient (Reality: Can be slow for large tables)"],
            "beginner",
        ],
        [
            "2.1",
            "Python Fundamentals",
            "cloze",
            "The primary keyword to define a function in Python is {{c1::def}}.",
            "def",
            "Functions are defined using the `def` keyword, followed by the function name, parentheses for arguments, and a colon. The indented block below defines the function body.",
            # Use a raw triple-quoted string for the code block to avoid escaping issues
            r"""```python
def greet(name):
    print(f"Hello, {name}!")
```""",
            ["Basic programming concepts"],
            ["Define reusable blocks of code"],
            ["❌ Forgetting the colon (:) after the definition"],
            "beginner",
        ],
    ],
    columns=[
        "Index",
        "Topic",
        "Card_Type",
        "Question",
        "Answer",
        "Explanation",
        "Example",
        "Prerequisites",
        "Learning_Outcomes",
        "Common_Misconceptions",
        "Difficulty",
    ],
)
# -------------------------------------

with gr.Blocks(
    theme=custom_theme,
    title="AnkiGen",
    css="""
        #footer {display:none !important}
        .tall-dataframe {min-height: 500px !important}
        .contain {max-width: 100% !important; margin: auto;}
        .output-cards {border-radius: 8px; box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1);}
        .hint-text {font-size: 0.9em; color: #666; margin-top: 4px;}
        .export-group > .gradio-group { margin-bottom: 0 !important; padding-bottom: 5px !important; }
    """,
    js=js_storage,
) as ankigen:
    with gr.Column(elem_classes="contain"):
        gr.Markdown("# πŸ“š AnkiGen - Advanced Anki Card Generator")
        gr.Markdown("""
        #### Generate comprehensive Anki flashcards using AI. 
        """)

        # Configuration Section in an Accordion
        with gr.Accordion("Configuration Settings", open=True):
            # Create a row to hold two columns for settings
            with gr.Row():
                # Column 1: Basic settings
                with gr.Column(scale=1):
                    # Add mode selection
                    generation_mode = gr.Radio(
                        choices=[
                            ("Single Subject", "subject"),
                            ("Learning Path", "path"),
                            ("From Text", "text"),
                            ("From Web", "web"),
                        ],
                        value="subject",
                        label="Generation Mode",
                        info="Choose how you want to generate content",
                    )

                    # Create containers for different modes
                    with gr.Group() as subject_mode:
                        subject = gr.Textbox(
                            label="Subject",
                            placeholder="Enter the subject, e.g., 'Basic SQL Concepts'",
                            info="The topic you want to generate flashcards for",
                        )

                    with gr.Group(visible=False) as path_mode:
                        description = gr.Textbox(
                            label="Learning Goal",
                            placeholder="Paste a job description or describe what you want to learn...",
                            info="We'll break this down into learnable subjects",
                            lines=5,
                        )
                        analyze_button = gr.Button(
                            "Analyze & Break Down", variant="secondary"
                        )

                    # Add group for text input mode
                    with gr.Group(visible=False) as text_mode:
                        source_text = gr.Textbox(
                            label="Source Text",
                            placeholder="Paste the text you want to generate cards from here...",
                            info="The AI will extract key information from this text to create cards.",
                            lines=15,
                        )

                    # Add group for web input mode
                    with gr.Group(visible=False) as web_mode:
                        url_input = gr.Textbox(
                            label="Web Page URL",
                            placeholder="Paste the URL of the page you want to generate cards from...",
                            info="The AI will attempt to extract content from this URL.",
                        )

                    # Common settings moved inside the accordion, in column 1
                    api_key_input = gr.Textbox(
                        label="OpenAI API Key",
                        type="password",
                        placeholder="Enter your OpenAI API key",
                        value=os.getenv("OPENAI_API_KEY", ""),
                        info="Your OpenAI API key starting with 'sk-'",
                    )

                # Column 2: Advanced settings accordion
                with gr.Column(scale=1):
                    # Advanced Settings Accordion moved inside the main accordion, in column 2
                    with gr.Accordion("Advanced Settings", open=False):
                        model_choice = gr.Dropdown(
                            choices=["gpt-4.1", "gpt-4.1-nano"],  # Corrected choices
                            value="gpt-4.1-nano",  # Changed default to nano as it's faster/cheaper
                            label="Model Selection",
                            info="Select the AI model to use for generation",
                        )

                        # Add tooltip/description for models
                        model_info = gr.Markdown(
                            """
                        **Model Information:**
                        - **gpt-4.1**: Highest quality, slower generation
                        - **gpt-4.1-nano**: Optimized for speed and lower cost
                        """  # Corrected descriptions
                        )

                        topic_number = gr.Slider(
                            label="Number of Topics",
                            minimum=2,
                            maximum=20,
                            step=1,
                            value=2,
                            info="How many distinct topics to cover within the subject",
                        )
                        cards_per_topic = gr.Slider(
                            label="Cards per Topic",
                            minimum=2,
                            maximum=30,
                            step=1,
                            value=3,
                            info="How many flashcards to generate for each topic",
                        )
                        preference_prompt = gr.Textbox(
                            label="Learning Preferences",
                            placeholder="e.g., 'Assume I'm a beginner' or 'Focus on practical examples'",
                            info="Customize how the content is presented",
                            lines=3,
                        )
                        generate_cloze_checkbox = gr.Checkbox(
                            label="Generate Cloze Cards (Experimental)",
                            value=False,
                            info="Allow the AI to generate fill-in-the-blank style cards where appropriate.",
                        )
                    # End of Advanced Settings Accordion
            # End of Row containing settings columns
        # End of Configuration Settings Accordion

        # Generation Button moved outside the Accordion
        generate_button = gr.Button("Generate Cards", variant="primary")

        # Output Area remains below the button
        with gr.Group(
            visible=False
        ) as path_results:  # Initial visibility controlled by mode
            gr.Markdown("### Learning Path Analysis")
            subjects_list = gr.Dataframe(
                headers=["Subject", "Prerequisites", "Time Estimate"],
                label="Recommended Subjects",
                interactive=False,
            )
            learning_order = gr.Markdown("### Recommended Learning Order")
            projects = gr.Markdown("### Suggested Projects")

            use_subjects = gr.Button(
                "Use These Subjects ℹ️",
                variant="primary",
            )
            gr.Markdown(
                "*Click to copy subjects to main input for card generation*",
                elem_classes="hint-text",
            )

        with gr.Group() as cards_output:  # Initial visibility controlled by mode
            gr.Markdown("### Generated Cards")

            # Output Format Documentation (can stay here)
            with gr.Accordion("Output Format", open=False):
                gr.Markdown("""
                The generated cards include:
                
                * **Index**: Unique identifier for each card
                * **Topic**: The specific subtopic within your subject
                * **Card_Type**: Type of card (basic or cloze)
                * **Question**: Clear, focused question for the flashcard front
                * **Answer**: Concise core answer
                * **Explanation**: Detailed conceptual explanation
                * **Example**: Practical implementation or code example
                * **Prerequisites**: Required knowledge for this concept
                * **Learning Outcomes**: What you should understand after mastering this card
                * **Common Misconceptions**: Incorrect assumptions debunked with explanations
                * **Difficulty**: Concept complexity level for optimal study sequencing
                
                Export options:
                - **CSV**: Raw data for custom processing
                - **Anki Deck**: Ready-to-use deck with formatted cards and metadata
                """)

                with gr.Accordion("Example Card Format", open=False):
                    gr.Code(
                        label="Example Card",
                        value="""
{
    "front": {
        "question": "What is a PRIMARY KEY constraint in SQL?"
    },
    "back": {
        "answer": "A PRIMARY KEY constraint uniquely identifies each record in a table",
        "explanation": "A primary key serves as a unique identifier for each row in a database table. It enforces data integrity by ensuring that:\n1. Each value is unique\n2. No null values are allowed\n3. The value remains stable over time\n\nThis is fundamental for:\n- Establishing relationships between tables\n- Maintaining data consistency\n- Efficient data retrieval",
        "example": "-- Creating a table with a primary key\nCREATE TABLE Users (\n  user_id INT PRIMARY KEY,\n  username VARCHAR(50) NOT NULL,\n  email VARCHAR(100) UNIQUE\n);"
    },
    "metadata": {
        "prerequisites": ["Basic SQL table concepts", "Understanding of data types"],
        "learning_outcomes": ["Understand the purpose and importance of primary keys", "Know how to create and use primary keys"],
        "common_misconceptions": [
            "❌ Misconception: Primary keys must always be single columns\nβœ“ Reality: Primary keys can be composite (multiple columns)",
            "❌ Misconception: Primary keys must be integers\nβœ“ Reality: Any data type that ensures uniqueness can be used"
        ],
        "difficulty": "beginner"
    }
}
                        """,
                        language="json",
                    )

            output = gr.Dataframe(
                value=example_data,
                headers=[
                    "Index",
                    "Topic",
                    "Card_Type",
                    "Question",
                    "Answer",
                    "Explanation",
                    "Example",
                    "Prerequisites",
                    "Learning_Outcomes",
                    "Common_Misconceptions",
                    "Difficulty",
                ],
                interactive=True,
                elem_classes="tall-dataframe",
                wrap=True,
                column_widths=[
                    50,
                    100,
                    80,
                    200,
                    200,
                    250,
                    200,
                    150,
                    150,
                    150,
                    100,
                ],
            )

            with gr.Group(elem_classes="export-group"):
                gr.Markdown("#### Export Generated Cards")
                with gr.Row():
                    export_csv_button = gr.Button("Export to CSV", variant="secondary")
                    export_anki_button = gr.Button(
                        "Export to Anki Deck (.apkg)", variant="secondary"
                    )
                with gr.Row():  # Row containing File components is now visible
                    download_csv = gr.File(label="Download CSV", interactive=False)
                    download_anki = gr.File(
                        label="Download Anki Deck",
                        interactive=False,
                    )

        # Add near the top of the Blocks
        with gr.Row():
            progress = gr.HTML(visible=False)
            total_cards = gr.Number(
                label="Total Cards Generated", value=0, visible=False
            )

        # Adjust JavaScript handler for mode switching
        def update_mode_visibility(mode):
            is_subject = mode == "subject"
            is_path = mode == "path"
            is_text = mode == "text"
            is_web = mode == "web"

            subject_val = subject.value if is_subject else ""
            description_val = description.value if is_path else ""
            text_val = source_text.value if is_text else ""
            url_val = url_input.value if is_web else ""

            return {
                subject_mode: gr.update(visible=is_subject),
                path_mode: gr.update(visible=is_path),
                text_mode: gr.update(visible=is_text),
                web_mode: gr.update(visible=is_web),
                path_results: gr.update(visible=is_path),
                cards_output: gr.update(visible=is_subject or is_text or is_web),
                subject: gr.update(value=subject_val),
                description: gr.update(value=description_val),
                source_text: gr.update(value=text_val),
                url_input: gr.update(value=url_val),
                output: gr.update(value=None),
                subjects_list: gr.update(value=None),
                learning_order: gr.update(value=""),
                projects: gr.update(value=""),
                progress: gr.update(value="", visible=False),
                total_cards: gr.update(value=0, visible=False),
            }

        generation_mode.change(
            fn=update_mode_visibility,
            inputs=[generation_mode],
            outputs=[
                subject_mode,
                path_mode,
                text_mode,
                web_mode,
                path_results,
                cards_output,
                subject,
                description,
                source_text,
                url_input,
                output,
                subjects_list,
                learning_order,
                projects,
                progress,
                total_cards,
            ],
        )

        analyze_button.click(
            fn=analyze_learning_path,
            inputs=[api_key_input, description, model_choice],
            outputs=[subjects_list, learning_order, projects],
        )

        def use_selected_subjects(subjects_df):
            if subjects_df is None or subjects_df.empty:
                gr.Warning("No subjects available to copy from Learning Path analysis.")
                return (
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                    gr.update(),
                )

            subjects = subjects_df["Subject"].tolist()
            combined_subject = ", ".join(subjects)
            suggested_topics = min(len(subjects) + 1, 20)

            return {
                generation_mode: "subject",
                subject_mode: gr.update(visible=True),
                path_mode: gr.update(visible=False),
                text_mode: gr.update(visible=False),
                web_mode: gr.update(visible=False),
                path_results: gr.update(visible=False),
                cards_output: gr.update(visible=True),
                subject: combined_subject,
                description: "",
                source_text: "",
                url_input: "",
                topic_number: suggested_topics,
                preference_prompt: "Focus on connections between these subjects and their practical applications.",
                output: example_data,
                subjects_list: subjects_df,
                learning_order: gr.update(),
                projects: gr.update(),
                progress: gr.update(visible=False),
                total_cards: gr.update(visible=False),
            }

        use_subjects.click(
            fn=use_selected_subjects,
            inputs=[subjects_list],
            outputs=[
                generation_mode,
                subject_mode,
                path_mode,
                text_mode,
                web_mode,
                path_results,
                cards_output,
                subject,
                description,
                source_text,
                url_input,
                topic_number,
                preference_prompt,
                output,
                subjects_list,
                learning_order,
                projects,
                progress,
                total_cards,
            ],
        )

        generate_button.click(
            fn=generate_cards,
            inputs=[
                api_key_input,
                subject,
                generation_mode,
                source_text,
                url_input,
                model_choice,
                topic_number,
                cards_per_topic,
                preference_prompt,
                generate_cloze_checkbox,
            ],
            outputs=[output, progress, total_cards],
            show_progress="full",
        )

        export_csv_button.click(
            fn=export_csv,
            inputs=[output],
            outputs=download_csv,
            show_progress="full",
        )

        export_anki_button.click(
            fn=export_deck,
            inputs=[output, subject],
            outputs=download_anki,
            show_progress="full",
        )

if __name__ == "__main__":
    logger.info("Starting AnkiGen application")
    ankigen.launch(share=False, favicon_path="./favicon.ico")