File size: 38,680 Bytes
d09f6aa
 
 
 
 
 
100024e
 
 
 
d09f6aa
100024e
d09f6aa
 
 
 
100024e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d09f6aa
100024e
 
d09f6aa
 
 
 
 
 
 
 
 
100024e
 
d09f6aa
 
 
 
 
100024e
 
 
 
 
 
 
d09f6aa
 
 
 
 
 
 
 
 
100024e
d09f6aa
100024e
 
 
 
 
d09f6aa
 
 
 
 
100024e
d09f6aa
100024e
d09f6aa
 
100024e
d09f6aa
100024e
d09f6aa
 
100024e
d09f6aa
100024e
 
 
d09f6aa
 
100024e
 
d09f6aa
 
 
 
100024e
d09f6aa
 
 
 
100024e
d09f6aa
 
 
100024e
d09f6aa
 
 
100024e
d09f6aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100024e
 
d09f6aa
100024e
 
 
d09f6aa
100024e
 
 
d09f6aa
100024e
d09f6aa
100024e
 
 
d09f6aa
 
100024e
 
 
 
 
 
d09f6aa
 
100024e
 
 
 
d09f6aa
 
100024e
 
d09f6aa
100024e
 
d09f6aa
100024e
 
 
 
d09f6aa
 
100024e
 
 
 
 
 
 
d09f6aa
 
100024e
 
 
 
 
d09f6aa
 
100024e
 
 
 
 
 
 
 
 
d09f6aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100024e
 
d09f6aa
 
 
100024e
 
d09f6aa
100024e
 
 
 
 
 
 
 
 
 
d09f6aa
 
 
 
100024e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d09f6aa
100024e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d09f6aa
 
 
 
100024e
d09f6aa
 
100024e
 
 
 
 
 
d09f6aa
 
100024e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d09f6aa
100024e
 
 
d09f6aa
100024e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d09f6aa
 
100024e
 
 
 
 
 
 
 
 
 
 
 
 
d09f6aa
100024e
 
 
 
 
 
 
 
 
 
 
 
 
 
d09f6aa
100024e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d09f6aa
100024e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d09f6aa
 
100024e
 
 
 
 
 
 
 
d09f6aa
 
100024e
d09f6aa
 
100024e
 
 
 
d09f6aa
100024e
 
 
 
 
 
d09f6aa
100024e
 
 
 
 
 
 
 
 
 
 
d09f6aa
100024e
 
 
 
 
 
 
 
 
 
d09f6aa
 
100024e
 
 
 
 
 
 
d09f6aa
100024e
 
 
 
 
d09f6aa
100024e
 
 
 
 
 
 
 
d09f6aa
100024e
d09f6aa
100024e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d09f6aa
100024e
 
d09f6aa
100024e
 
d09f6aa
100024e
 
 
 
d09f6aa
100024e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d09f6aa
100024e
d09f6aa
 
100024e
 
 
 
 
d09f6aa
100024e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Module for CSV and APKG export functions

import gradio as gr
import pandas as pd
import genanki
import random
from typing import List, Dict, Any, Optional
import csv
from datetime import datetime
import os

from ankigen_core.utils import get_logger, strip_html_tags

logger = get_logger()


# --- Helper function for formatting fields ---
def _format_field_as_string(value: Any) -> str:
    if isinstance(value, list) or isinstance(value, tuple):
        return ", ".join(str(item).strip() for item in value if str(item).strip())
    if pd.isna(value) or value is None:
        return ""
    return str(value).strip()


# --- Constants for APKG Generation (Subtask 10) ---
ANKI_BASIC_MODEL_NAME = "AnkiGen Basic"
ANKI_CLOZE_MODEL_NAME = "AnkiGen Cloze"

# It's good practice to generate unique IDs. These are examples.
# Real applications might use a persistent way to store/retrieve these if models are updated.
DEFAULT_BASIC_MODEL_ID = random.randrange(1 << 30, 1 << 31)
DEFAULT_CLOZE_MODEL_ID = random.randrange(1 << 30, 1 << 31)

# --- Full Model Definitions with CSS (Restored) ---

BASIC_MODEL = genanki.Model(
    DEFAULT_BASIC_MODEL_ID,  # Use the generated ID
    ANKI_BASIC_MODEL_NAME,  # Use the constant name
    fields=[
        {"name": "Question"},
        {"name": "Answer"},
        {"name": "Explanation"},
        {"name": "Example"},
        {"name": "Prerequisites"},
        {"name": "Learning_Outcomes"},
        {"name": "Common_Misconceptions"},
        {"name": "Difficulty"},
        {"name": "SourceURL"},  # Added for consistency if used by template
        {"name": "TagsStr"},  # Added for consistency if used by template
    ],
    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\">{{Example}}</div> 
                        <!-- Example field might contain pre/code or plain text -->
                        <!-- Handled by how HTML is put into the Example field -->
                    </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>
                        {{#SourceURL}}<div class=\"source-url\"><small>Source: <a href=\"{{SourceURL}}\">{{SourceURL}}</a></small></div>{{/SourceURL}}
                    </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: #fefce8; /* Light yellow */
            border-left: 4px solid #facc15; /* Yellow */
        }
        .example-section pre {
            background-color: #2d2d2d; /* Darker background for code blocks */
            color: #f8f8f2; /* Light text for contrast */
            padding: 1em;
            border-radius: 0.3em;
            overflow-x: auto; /* Horizontal scroll for long lines */
            font-family: 'Consolas', 'Monaco', 'Menlo', monospace;
            font-size: 0.9em;
            line-height: 1.4;
        }

        .example-section code {
             font-family: 'Consolas', 'Monaco', 'Menlo', monospace;
        }
        
        .metadata-section {
            margin-top: 2em;
            padding-top: 1em;
            border-top: 1px solid #e5e7eb; /* Light gray border */
            font-size: 0.9em;
            color: #4b5563; /* Cool gray */
        }
        
        .metadata-section h3 {
            font-size: 1em;
            color: #1f2937; /* Darker gray for headings */
            margin-bottom: 0.5em;
        }
        
        .metadata-section > div {
            margin-bottom: 0.8em;
        }

        .source-url a {
            color: #2563eb;
            text-decoration: none;
        }
        .source-url a:hover {
            text-decoration: underline;
        }
        
        /* Styles for cloze deletion cards */
        .cloze {
            font-weight: bold;
            color: blue;
        }
        .nightMode .cloze {
            color: lightblue;
        }
        
        /* General utility */
        hr {
            border: none;
            border-top: 1px dashed #cbd5e1; /* Light dashed line */
            margin: 1.5em 0;
        }
        
        /* Rich text field styling (if Anki adds classes for these) */
        .field ul, .field ol {
            margin-left: 1.5em;
            padding-left: 0.5em;
        }
        .field li {
            margin-bottom: 0.3em;
        }

        /* Responsive design */
        @media (max-width: 640px) {
            .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;
        }
    """,
    # model_type=genanki.Model.BASIC, # This was still incorrect
    # No model_type needed, defaults to Basic (0)
)

CLOZE_MODEL = genanki.Model(
    DEFAULT_CLOZE_MODEL_ID,  # Use the generated ID
    ANKI_CLOZE_MODEL_NAME,  # Use the constant name
    fields=[
        {"name": "Text"},
        {"name": "Back Extra"},
        {"name": "Explanation"},
        {"name": "Example"},
        {"name": "Prerequisites"},
        {"name": "Learning_Outcomes"},
        {"name": "Common_Misconceptions"},
        {"name": "Difficulty"},
        {"name": "SourceURL"},
        {"name": "TagsStr"},
    ],
    templates=[
        {
            "name": "Cloze Card",
            "qfmt": """
            <div class=\"card question-side\">
                <div class=\"difficulty-indicator {{Difficulty}}\"></div>
                <div class=\"content\">
                    <div class=\"question\">{{cloze:Text}}</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\">{{cloze:Text}}</div>
                        <div class=\"prerequisites\">
                            <strong>Prerequisites:</strong> {{Prerequisites}}
                        </div>
                    </div>
                    <hr>
                    
                    {{#Back Extra}}
                    <div class=\"back-extra-section\">
                        <h3>Additional Information</h3>
                        <div class=\"back-extra-text\">{{Back Extra}}</div>
                    </div>
                    {{/Back Extra}}
                    
                    <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\">{{Example}}</div>
                    </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>
                        {{#SourceURL}}<div class=\"source-url\"><small>Source: <a href=\"{{SourceURL}}\">{{SourceURL}}</a></small></div>{{/SourceURL}}
                    </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 { /* Shared with question for cloze, but can be general */
            background: #f0f9ff;
            border-left: 4px solid #2563eb;
        }

        .back-extra-section {
            background: #eef2ff; /* A slightly different shade for additional info */
            border-left: 4px solid #818cf8; /* Indigo variant */
            margin: 1.5em 0;
            padding: 1.2em;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        
        .explanation-section {
            background: #f0fdf4;
            border-left: 4px solid #4ade80;
        }

        .example-section {
            background: #fefce8; /* Light yellow */
            border-left: 4px solid #facc15; /* Yellow */
        }
        .example-section pre {
            background-color: #2d2d2d; /* Darker background for code blocks */
            color: #f8f8f2; /* Light text for contrast */
            padding: 1em;
            border-radius: 0.3em;
            overflow-x: auto; /* Horizontal scroll for long lines */
            font-family: 'Consolas', 'Monaco', 'Menlo', monospace;
            font-size: 0.9em;
            line-height: 1.4;
        }

        .example-section code {
             font-family: 'Consolas', 'Monaco', 'Menlo', monospace;
        }
        
        .metadata-section {
            margin-top: 2em;
            padding-top: 1em;
            border-top: 1px solid #e5e7eb; /* Light gray border */
            font-size: 0.9em;
            color: #4b5563; /* Cool gray */
        }
        
        .metadata-section h3 {
            font-size: 1em;
            color: #1f2937; /* Darker gray for headings */
            margin-bottom: 0.5em;
        }
        
        .metadata-section > div {
            margin-bottom: 0.8em;
        }

        .source-url a {
            color: #2563eb;
            text-decoration: none;
        }
        .source-url a:hover {
            text-decoration: underline;
        }
        
        /* Styles for cloze deletion cards */
        .cloze {
            font-weight: bold;
            color: blue;
        }
        .nightMode .cloze {
            color: lightblue;
        }
        
        /* General utility */
        hr {
            border: none;
            border-top: 1px dashed #cbd5e1; /* Light dashed line */
            margin: 1.5em 0;
        }
        
        /* Rich text field styling (if Anki adds classes for these) */
        .field ul, .field ol {
            margin-left: 1.5em;
            padding-left: 0.5em;
        }
        .field li {
            margin-bottom: 0.3em;
        }
    """,
    # model_type=genanki.Model.CLOZE, # This was still incorrect
    model_type=1,  # Corrected to use integer 1 for Cloze
)


# --- Helper functions for APKG (Subtask 10) ---
def _get_or_create_model(
    model_id: int,
    name: str,
    fields: List[Dict[str, str]],
    templates: List[Dict[str, str]],
) -> genanki.Model:
    return genanki.Model(model_id, name, fields=fields, templates=templates)


# --- New CSV Exporter for List of Dictionaries ---


def export_cards_to_csv(
    cards: List[Dict[str, Any]], filename: Optional[str] = None
) -> str:
    """Export a list of card dictionaries to a CSV file.

    Args:
        cards: A list of dictionaries, where each dictionary represents a card
               and should contain 'front' and 'back' keys. Other keys like
               'tags' and 'note_type' are optional.
        filename: Optional. The desired filename/path for the CSV.
                  If None, a timestamped filename will be generated.

    Returns:
        The path to the generated CSV file.

    Raises:
        IOError: If there is an issue writing to the file.
        KeyError: If a card dictionary is missing essential keys like 'front' or 'back'.
        ValueError: If the cards list is empty or not provided.
    """
    if not cards:
        logger.warning("export_cards_to_csv called with an empty list of cards.")
        raise ValueError("No cards provided to export.")

    if not filename:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        # Ensure filename is just the name, not a path if not intended
        # For simplicity, this example saves in the current working directory if no path is specified.
        filename = f"ankigen_cards_{timestamp}.csv"
        logger.info(f"No filename provided, generated: {filename}")

    # Define the fieldnames expected in the CSV.
    # 'front' and 'back' are mandatory.
    fieldnames = ["front", "back", "tags", "note_type"]

    try:
        logger.info(f"Attempting to export {len(cards)} cards to {filename}")
        with open(filename, "w", newline="", encoding="utf-8") as csvfile:
            writer = csv.DictWriter(
                csvfile, fieldnames=fieldnames, extrasaction="ignore"
            )
            writer.writeheader()
            for i, card in enumerate(cards):
                try:
                    # Ensure mandatory fields exist, others are optional via card.get in row_to_write
                    if "front" not in card or "back" not in card:
                        raise KeyError(
                            f"Card at index {i} is missing 'front' or 'back' key."
                        )

                    row_to_write = {
                        "front": card["front"],
                        "back": card["back"],
                        "tags": card.get("tags", ""),
                        "note_type": card.get("note_type", "Basic"),
                    }
                    writer.writerow(row_to_write)
                except KeyError as e_inner:
                    logger.error(
                        f"Skipping card due to KeyError: {e_inner}. Card data: {card}"
                    )
                    # Optionally re-raise if one bad card should stop the whole export,
                    # or continue to export valid cards.
                    # For this implementation, we log and continue.
                    continue
        logger.info(f"Successfully exported cards to {filename}")
        return filename
    except IOError as e_io:
        logger.error(f"IOError during CSV export to {filename}: {e_io}", exc_info=True)
        raise  # Re-raise the IOError
    except Exception as e_general:  # Catch any other unexpected errors
        logger.error(
            f"Unexpected error during CSV export to {filename}: {e_general}",
            exc_info=True,
        )
        raise


def export_cards_to_apkg(
    cards: List[Dict[str, Any]],
    filename: Optional[str] = None,
    deck_name: str = "Ankigen Generated Cards",
) -> str:
    """Exports a list of card dictionaries to an Anki .apkg file.

    Args:
        cards: List of dictionaries, where each dictionary represents a card.
               It's expected that these dicts are prepared by export_dataframe_to_apkg
               and contain keys like 'Question', 'Answer', 'Explanation', etc.
        filename: The full path (including filename) for the exported file.
                  If None, a default filename will be generated in the current directory.
        deck_name: The name of the deck if exporting to .apkg format.

    Returns:
        The path to the exported file.
    """
    logger.info(f"Starting APKG export for {len(cards)} cards to deck '{deck_name}'.")
    if not filename:
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        filename = f"ankigen_deck_{timestamp}.apkg"
    elif not filename.lower().endswith(".apkg"):
        filename += ".apkg"

    output_dir = os.path.dirname(filename)
    if output_dir and not os.path.exists(output_dir):
        os.makedirs(output_dir)
        logger.info(f"Created output directory for APKG: {output_dir}")

    anki_basic_model = BASIC_MODEL
    anki_cloze_model = CLOZE_MODEL

    deck_id = random.randrange(1 << 30, 1 << 31)
    anki_deck = genanki.Deck(deck_id, deck_name)

    notes_added_count = 0
    for card_dict in cards:
        note_type = card_dict.get("note_type", "Basic")
        tags_for_note_object = card_dict.get("tags_for_note_object", [])

        # Extract all potential fields, defaulting to empty strings
        question = card_dict.get("Question", "")
        answer = card_dict.get("Answer", "")
        explanation = card_dict.get("Explanation", "")
        example = card_dict.get("Example", "")
        prerequisites = card_dict.get("Prerequisites", "")
        learning_outcomes = card_dict.get("Learning_Outcomes", "")
        common_misconceptions = card_dict.get("Common_Misconceptions", "")
        difficulty = card_dict.get("Difficulty", "")
        source_url = card_dict.get("SourceURL", "")
        tags_str_field = card_dict.get(
            "TagsStr", ""
        )  # This is the string for the model's TagsStr field

        # The 'Question' field from card_dict is used as the main text for both basic and cloze.
        # For cloze, this 'Question' field should contain the cloze-formatted text (e.g., "The capital of {{c1::France}} is Paris.")
        if not question:
            logger.error(
                f"SKIPPING CARD DUE TO EMPTY 'Question' (front/text) field. Card data: {card_dict}"
            )
            continue

        try:
            if note_type.lower() == "cloze":
                # CLOZE_MODEL fields: Text, Back Extra, Explanation, Example, Prerequisites,
                # Learning_Outcomes, Common_Misconceptions, Difficulty, SourceURL, TagsStr
                note_fields = [
                    question,  # Text (this is the card_dict['Question'] which should be cloze-formatted)
                    answer,  # Back Extra (this is card_dict['Answer'])
                    explanation,
                    example,
                    prerequisites,
                    learning_outcomes,
                    common_misconceptions,
                    difficulty,
                    source_url,
                    tags_str_field,
                ]
                note = genanki.Note(
                    model=anki_cloze_model,
                    fields=note_fields,
                    tags=tags_for_note_object,
                )
            else:  # Basic
                # BASIC_MODEL fields: Question, Answer, Explanation, Example, Prerequisites,
                # Learning_Outcomes, Common_Misconceptions, Difficulty, SourceURL, TagsStr
                note_fields = [
                    question,
                    answer,
                    explanation,
                    example,
                    prerequisites,
                    learning_outcomes,
                    common_misconceptions,
                    difficulty,
                    source_url,
                    tags_str_field,
                ]
                note = genanki.Note(
                    model=anki_basic_model,
                    fields=note_fields,
                    tags=tags_for_note_object,
                )
            anki_deck.add_note(note)
            notes_added_count += 1
        except Exception as e:
            logger.error(
                f"Failed to create genanki.Note for card: {card_dict}. Error: {e}",
                exc_info=True,
            )
            logger.warning(f"Skipping card due to error: Question='{question[:50]}...'")

    if notes_added_count == 0 and cards:  # Some cards were provided but none were added
        logger.error(  # Changed to error for more visibility
            "No valid notes could be created from the provided cards. APKG generation aborted."
        )
        # This error should be caught by the calling function in app.py to inform the user
        raise gr.Error("Failed to create any valid Anki notes from the input.")
    elif not cards:  # No cards provided initially
        logger.info("No cards provided to export to APKG. APKG generation skipped.")
        # Depending on desired behavior, could raise or return a specific status/filename
        # For now, let's assume an empty/default filename or None indicates no action if no cards
        # However, the function is typed to return str, so raising is more consistent if no file is made.
        raise gr.Error("No cards were provided to generate an APKG file.")
    else:  # notes_added_count > 0
        logger.info(
            f"Added {notes_added_count} notes to deck '{deck_name}'. Proceeding to package."
        )

    # Only proceed to package and write if notes were successfully added
    package = genanki.Package(anki_deck)
    try:
        package.write_to_file(filename)
        logger.info(f"Successfully exported Anki deck to {filename}")
    except Exception as e:
        logger.error(f"Failed to write .apkg file to {filename}: {e}", exc_info=True)
        raise IOError(f"Could not write .apkg file: {e}")

    return filename


def export_cards_from_crawled_content(
    cards: List[Dict[str, Any]],
    output_path: Optional[
        str
    ] = None,  # Changed from filename to output_path for clarity
    export_format: str = "csv",  # Added export_format parameter
    deck_name: str = "Ankigen Generated Cards",
) -> str:
    """Exports cards (list of dicts) to the specified format (CSV or APKG).

    Args:
        cards: List of dictionaries, where each dictionary represents a card.
               Expected keys: 'front', 'back'. Optional: 'tags' (space-separated string), 'source_url', 'note_type' ('Basic' or 'Cloze').
        output_path: The full path (including filename) for the exported file.
                     If None, a default filename will be generated in the current directory.
        export_format: The desired format, either 'csv' or 'apkg'.
        deck_name: The name of the deck if exporting to .apkg format.

    Returns:
        The path to the exported file.
    """
    if not cards:
        logger.warning("No cards provided to export_cards_from_crawled_content.")
        # MODIFIED: Raise error immediately if no cards, as per test expectation
        raise ValueError("No cards provided to export.")

    logger.info(
        f"Exporting {len(cards)} cards to format '{export_format}' with deck name '{deck_name}'."
    )

    if export_format.lower() == "csv":
        return export_cards_to_csv(cards, filename=output_path)
    elif export_format.lower() == "apkg":
        return export_cards_to_apkg(cards, filename=output_path, deck_name=deck_name)
    else:
        supported_formats = ["csv", "apkg"]
        logger.error(
            f"Unsupported export format: {export_format}. Supported formats: {supported_formats}"
        )
        # MODIFIED: Updated error message to include supported formats
        raise ValueError(
            f"Unsupported export format: {export_format}. Supported formats: {supported_formats}"
        )


# --- New DataFrame CSV Exporter (Subtask 11) ---
def export_dataframe_to_csv(
    data: Optional[pd.DataFrame],
    filename_suggestion: Optional[str] = "ankigen_cards.csv",
) -> Optional[str]:
    """Exports a Pandas DataFrame to a CSV file, designed for Gradio download.

    Args:
        data: The Pandas DataFrame to export.
        filename_suggestion: A suggestion for the base filename (e.g., from subject).

    Returns:
        The path to the temporary CSV file, or None if an error occurs or data is empty.
    """
    logger.info(
        f"Attempting to export DataFrame to CSV. Suggested filename: {filename_suggestion}"
    )
    if data is None or data.empty:
        logger.warning(
            "No data provided to export_dataframe_to_csv. Skipping CSV export."
        )
        raise gr.Error(
            "No card data available"
        )  # Notify user via Gradio with Error instead of Info
        # return None # This line is now unreachable due to the raise

    try:
        # Create a specific filename using both suggestion and timestamp
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        base_name_from_suggestion = "ankigen_cards"  # Default base part

        # Sanitize and use the suggestion (e.g., subject name) if provided
        if filename_suggestion and isinstance(filename_suggestion, str):
            # Remove .csv if present, then sanitize
            processed_suggestion = filename_suggestion.removesuffix(".csv")
            safe_suggestion = (
                processed_suggestion.replace(" ", "_")
                .replace("/", "-")
                .replace("\\\\", "-")
            )
            if (
                safe_suggestion
            ):  # If suggestion wasn't just '.csv' or empty after processing
                base_name_from_suggestion = f"ankigen_{safe_suggestion[:50]}"
            # If suggestion was empty or only '.csv', default base_name_from_suggestion remains 'ankigen_cards'

        final_filename = f"{base_name_from_suggestion}_{timestamp}.csv"

        # Ensure output directory exists if filename contains path
        output_dir = os.path.dirname(final_filename)
        if output_dir and not os.path.exists(output_dir):
            os.makedirs(output_dir)
            logger.info(f"Created output directory for CSV: {output_dir}")

        data.to_csv(final_filename, index=False)  # MODIFIED: Write to final_filename
        logger.info(f"Successfully exported DataFrame to CSV: {final_filename}")
        gr.Info(
            f"CSV ready for download: {os.path.basename(final_filename)}"
        )  # User-friendly message
        return final_filename  # MODIFIED: Return final_filename
    except Exception as e:
        logger.error(f"Error exporting DataFrame to CSV: {e}", exc_info=True)
        gr.Error(f"Error exporting DataFrame to CSV: {e}")
        return None


# --- New DataFrame to APKG Exporter (for Main Generator Tab) ---
def export_dataframe_to_apkg(
    df: pd.DataFrame,
    output_path: Optional[str],
    deck_name: str,
) -> str:
    """Exports a DataFrame of cards to an Anki .apkg file."""
    if df.empty:
        logger.warning("export_dataframe_to_apkg called with an empty DataFrame.")
        raise ValueError("No cards in DataFrame to export.")

    logger.info(
        f"Starting APKG export for DataFrame with {len(df)} rows to deck '{deck_name}'. Output: {output_path}"
    )

    cards_for_apkg: List[Dict[str, Any]] = []
    for _, row in df.iterrows():
        try:
            note_type_val = (
                _format_field_as_string(row.get("Card_Type", "Basic")) or "Basic"
            )
            topic = _format_field_as_string(row.get("Topic", ""))
            difficulty_raw = _format_field_as_string(row.get("Difficulty", ""))
            difficulty_plain_for_tag = strip_html_tags(
                difficulty_raw
            )  # Strip HTML for the tag

            tags_list_for_note_obj = []  # For genanki.Note(tags=...)
            if topic:
                tags_list_for_note_obj.append(topic.replace(" ", "_").replace(",", "_"))
            if difficulty_plain_for_tag:  # Use the plain text version for the tag
                # Further sanitize for Anki tags: replace spaces with underscores, remove other invalid chars if any.
                # Anki tags also often don't like colons or other special chars except underscore/hyphen.
                # For now, just replacing space, as that's the error seen.
                safe_difficulty_tag = difficulty_plain_for_tag.replace(" ", "_")
                tags_list_for_note_obj.append(safe_difficulty_tag)

            tags_str_for_field = " ".join(
                tags_list_for_note_obj
            )  # For the 'TagsStr' model field

            # Prepare a dictionary that contains all possible fields our models might need.
            card_data_for_note = {
                "note_type": note_type_val,
                "tags_for_note_object": tags_list_for_note_obj,
                "TagsStr": tags_str_for_field,
                "Question": _format_field_as_string(row.get("Question", "")),
                "Answer": _format_field_as_string(row.get("Answer", "")),
                "Explanation": _format_field_as_string(row.get("Explanation", "")),
                "Example": _format_field_as_string(row.get("Example", "")),
                "Prerequisites": _format_field_as_string(row.get("Prerequisites", "")),
                "Learning_Outcomes": _format_field_as_string(
                    row.get("Learning_Outcomes", "")
                ),
                "Common_Misconceptions": _format_field_as_string(
                    row.get("Common_Misconceptions", "")
                ),
                "Difficulty": difficulty_raw,  # Keep the original HTML for the 'Difficulty' field itself
                "SourceURL": _format_field_as_string(row.get("Source_URL", "")),
            }
            cards_for_apkg.append(card_data_for_note)
        except Exception as e:
            logger.error(
                f"Error processing DataFrame row for APKG: {row}. Error: {e}",
                exc_info=True,
            )
            continue

    if not cards_for_apkg:
        logger.error("No cards could be processed from DataFrame for APKG export.")
        raise ValueError("No processable cards found in DataFrame for APKG export.")

    return export_cards_to_apkg(
        cards_for_apkg, filename=output_path, deck_name=deck_name
    )


# --- Compatibility Exports for Tests and Legacy Code ---
# These aliases ensure that tests expecting these names will find them.

# Export functions under expected names
export_csv = (
    export_dataframe_to_csv  # Update this to export_dataframe_to_csv for compatibility
)


# MODIFIED: export_deck is now a wrapper to provide a default deck_name
def export_deck(
    df: pd.DataFrame,
    output_path: Optional[str] = None,
    deck_name: str = "Ankigen Generated Cards",
) -> str:
    """Alias for exporting a DataFrame to APKG, providing a default deck name."""
    if df is None or df.empty:
        logger.warning("export_deck called with None or empty DataFrame.")
        # Match the error type and message expected by tests
        raise gr.Error("No card data available")

    # Original logic to call export_dataframe_to_apkg
    # Ensure all necessary parameters for export_dataframe_to_apkg are correctly passed.
    # The export_dataframe_to_apkg function itself will handle its specific error conditions.
    # The 'output_path' for export_dataframe_to_apkg needs to be handled.
    # If 'output_path' is None here, export_cards_to_apkg (called by export_dataframe_to_apkg)
    # will generate a default filename.

    # If output_path is not provided to export_deck, it's None.
    # export_dataframe_to_apkg expects output_path: Optional[str].
    # And export_cards_to_apkg (which it calls) also handles Optional[str] filename.
    # So, passing output_path directly should be fine.

    return export_dataframe_to_apkg(df, output_path=output_path, deck_name=deck_name)


export_dataframe_csv = export_dataframe_to_csv
export_dataframe_apkg = export_dataframe_to_apkg

__all__ = [
    "BASIC_MODEL",
    "CLOZE_MODEL",
    "export_csv",
    "export_deck",
    "export_dataframe_csv",
    "export_dataframe_apkg",
    "export_cards_to_csv",
    "export_cards_to_apkg",
    "export_cards_from_crawled_content",
    "export_dataframe_to_csv",
    "export_dataframe_to_apkg",
]