ankit-builder 0.1.0

TOML-based Anki deck builder with .apkg generation and AnkiConnect import
Documentation
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
//! TOML schema types for deck definitions.
//!
//! # Example TOML
//!
//! ```toml
//! [package]
//! name = "Spanish Vocabulary"
//! version = "1.0.0"
//! author = "Your Name"
//!
//! [[models]]
//! name = "Basic Spanish"
//! fields = ["Spanish", "English", "Example"]
//! # Optional: specify which field to sort by (default: first field)
//! sort_field = "Spanish"
//!
//! [[models.templates]]
//! name = "Spanish -> English"
//! front = "{{Spanish}}"
//! back = "{{FrontSide}}<hr>{{English}}<br><i>{{Example}}</i>"
//!
//! [[models.templates]]
//! name = "English -> Spanish"
//! front = "{{English}}"
//! back = "{{FrontSide}}<hr>{{Spanish}}"
//!
//! [[decks]]
//! name = "Spanish::Vocabulary"
//! description = "Core Spanish vocabulary"
//!
//! [[notes]]
//! deck = "Spanish::Vocabulary"
//! model = "Basic Spanish"
//! tags = ["chapter1", "nouns"]
//!
//! [notes.fields]
//! Spanish = "el gato"
//! English = "the cat"
//! Example = "El gato es negro."
//! ```

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

use crate::error::{Error, Result};

/// Root structure for a deck definition file.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeckDefinition {
    /// Package metadata.
    pub package: PackageInfo,

    /// Model (note type) definitions.
    #[serde(default)]
    pub models: Vec<ModelDef>,

    /// Deck definitions.
    #[serde(default)]
    pub decks: Vec<DeckDef>,

    /// Note definitions.
    #[serde(default)]
    pub notes: Vec<NoteDef>,

    /// Media file definitions.
    #[serde(default)]
    pub media: Vec<MediaDef>,
}

impl DeckDefinition {
    /// Load a deck definition from a TOML file.
    pub fn from_file(path: impl AsRef<Path>) -> Result<Self> {
        let content = std::fs::read_to_string(path)?;
        Self::parse(&content)
    }

    /// Parse a deck definition from a TOML string.
    pub fn parse(content: &str) -> Result<Self> {
        let def: DeckDefinition = toml::from_str(content)?;
        def.validate()?;
        Ok(def)
    }

    /// Validate the deck definition for consistency.
    pub fn validate(&self) -> Result<()> {
        // Check that all notes reference valid models
        let model_names: std::collections::HashSet<_> =
            self.models.iter().map(|m| m.name.as_str()).collect();

        for note in &self.notes {
            if !model_names.contains(note.model.as_str()) {
                return Err(Error::ModelNotFound(note.model.clone()));
            }

            // Check that note fields match model fields
            let model = self.models.iter().find(|m| m.name == note.model).unwrap();
            for field_name in note.fields.keys() {
                if !model.fields.contains(field_name) {
                    return Err(Error::FieldNotFound {
                        model: note.model.clone(),
                        field: field_name.clone(),
                    });
                }
            }
        }

        // Check that all notes reference valid decks
        let deck_names: std::collections::HashSet<_> =
            self.decks.iter().map(|d| d.name.as_str()).collect();

        for note in &self.notes {
            if !deck_names.contains(note.deck.as_str()) {
                return Err(Error::DeckNotFound(note.deck.clone()));
            }
        }

        Ok(())
    }

    /// Get a model by name.
    pub fn get_model(&self, name: &str) -> Option<&ModelDef> {
        self.models.iter().find(|m| m.name == name)
    }

    /// Get a deck by name.
    pub fn get_deck(&self, name: &str) -> Option<&DeckDef> {
        self.decks.iter().find(|d| d.name == name)
    }

    /// Get notes for a specific deck.
    pub fn notes_for_deck(&self, deck_name: &str) -> impl Iterator<Item = &NoteDef> {
        self.notes.iter().filter(move |n| n.deck == deck_name)
    }

    /// Convert HTML to Markdown in fields marked as `markdown_fields`.
    ///
    /// Call this after exporting from Anki to get cleaner, more readable TOML.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::DeckDefinition;
    ///
    /// # fn example() -> ankit_builder::Result<()> {
    /// let mut definition = DeckDefinition::from_file("deck.toml")?;
    /// definition.html_to_markdown();
    /// definition.write_toml("deck_markdown.toml")?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn html_to_markdown(&mut self) {
        use crate::markdown::html_to_markdown;

        for note in &mut self.notes {
            if let Some(model) = self.models.iter().find(|m| m.name == note.model) {
                for field_name in &model.markdown_fields {
                    if let Some(value) = note.fields.get_mut(field_name) {
                        *value = html_to_markdown(value);
                    }
                }
            }
        }
    }

    /// Convert Markdown to HTML in fields marked as `markdown_fields`.
    ///
    /// Call this before importing to Anki to convert readable Markdown to HTML.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::DeckDefinition;
    ///
    /// # fn example() -> ankit_builder::Result<()> {
    /// let mut definition = DeckDefinition::from_file("deck.toml")?;
    /// definition.markdown_to_html();
    /// // Now ready to import to Anki
    /// # Ok(())
    /// # }
    /// ```
    pub fn markdown_to_html(&mut self) {
        use crate::markdown::markdown_to_html;

        for note in &mut self.notes {
            if let Some(model) = self.models.iter().find(|m| m.name == note.model) {
                for field_name in &model.markdown_fields {
                    if let Some(value) = note.fields.get_mut(field_name) {
                        *value = markdown_to_html(value);
                    }
                }
            }
        }
    }

    /// Set markdown fields for a model.
    ///
    /// Convenience method to mark which fields should use Markdown format.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use ankit_builder::DeckDefinition;
    ///
    /// # fn example() -> ankit_builder::Result<()> {
    /// let mut definition = DeckDefinition::from_file("deck.toml")?;
    /// definition.set_markdown_fields("Basic", &["Back", "Extra"]);
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_markdown_fields(&mut self, model_name: &str, fields: &[&str]) {
        if let Some(model) = self.models.iter_mut().find(|m| m.name == model_name) {
            model.markdown_fields = fields.iter().map(|s| s.to_string()).collect();
        }
    }
}

/// Package metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PackageInfo {
    /// Package name (used as default deck name if no decks defined).
    pub name: String,

    /// Package version.
    #[serde(default = "default_version")]
    pub version: String,

    /// Package author.
    #[serde(default)]
    pub author: Option<String>,

    /// Package description.
    #[serde(default)]
    pub description: Option<String>,
}

fn default_version() -> String {
    "1.0.0".to_string()
}

/// Model (note type) definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelDef {
    /// Model name (must be unique).
    pub name: String,

    /// Field names in order.
    pub fields: Vec<String>,

    /// Card templates.
    pub templates: Vec<TemplateDef>,

    /// CSS styling for cards.
    #[serde(default)]
    pub css: Option<String>,

    /// Which field to sort by (default: first field).
    #[serde(default)]
    pub sort_field: Option<String>,

    /// Model ID (auto-generated if not specified).
    #[serde(default)]
    pub id: Option<i64>,

    /// Fields that use Markdown format (converted to/from HTML).
    ///
    /// When pushing to Anki, markdown in these fields is converted to HTML.
    /// When pulling from Anki, HTML in these fields is converted to markdown.
    #[serde(default)]
    pub markdown_fields: Vec<String>,

    /// Model type: "standard" (default) or "cloze".
    ///
    /// When set to "cloze", templates are optional and a default cloze template is used.
    #[serde(default)]
    pub model_type: Option<String>,
}

impl ModelDef {
    /// Create a new cloze model with default template.
    ///
    /// # Example
    ///
    /// ```
    /// use ankit_builder::ModelDef;
    ///
    /// let model = ModelDef::cloze("My Cloze Model", vec!["Text", "Extra"]);
    /// assert_eq!(model.name, "My Cloze Model");
    /// assert!(model.is_cloze());
    /// ```
    pub fn cloze(name: impl Into<String>, fields: Vec<impl Into<String>>) -> Self {
        Self {
            name: name.into(),
            fields: fields.into_iter().map(Into::into).collect(),
            templates: vec![TemplateDef {
                name: "Cloze".to_string(),
                front: "{{cloze:Text}}".to_string(),
                back: "{{cloze:Text}}<br>{{Extra}}".to_string(),
            }],
            css: None,
            sort_field: None,
            id: None,
            markdown_fields: vec![],
            model_type: Some("cloze".to_string()),
        }
    }

    /// Check if this is a cloze model.
    pub fn is_cloze(&self) -> bool {
        self.model_type.as_deref() == Some("cloze")
    }
}

impl ModelDef {
    /// Get the sort field index.
    pub fn sort_field_index(&self) -> usize {
        if let Some(ref name) = self.sort_field {
            self.fields.iter().position(|f| f == name).unwrap_or(0)
        } else {
            0
        }
    }
}

/// Card template definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateDef {
    /// Template name.
    pub name: String,

    /// Front template (question side).
    pub front: String,

    /// Back template (answer side).
    pub back: String,
}

/// Deck definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DeckDef {
    /// Deck name (use :: for hierarchy, e.g., "Parent::Child").
    pub name: String,

    /// Deck description.
    #[serde(default)]
    pub description: Option<String>,

    /// Deck ID (auto-generated if not specified).
    #[serde(default)]
    pub id: Option<i64>,
}

/// Note definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NoteDef {
    /// Deck name to add note to.
    pub deck: String,

    /// Model name for this note.
    pub model: String,

    /// Field values.
    pub fields: HashMap<String, String>,

    /// Tags for this note.
    #[serde(default)]
    pub tags: Vec<String>,

    /// Custom GUID (auto-generated if not specified).
    #[serde(default)]
    pub guid: Option<String>,

    /// Anki note ID (assigned after sync, used for tracking).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note_id: Option<i64>,
}

impl NoteDef {
    /// Get field values in model field order.
    pub fn fields_ordered(&self, model: &ModelDef) -> Vec<String> {
        model
            .fields
            .iter()
            .map(|f| self.fields.get(f).cloned().unwrap_or_default())
            .collect()
    }

    /// Get tags as a space-separated string with surrounding spaces.
    pub fn tags_string(&self) -> String {
        if self.tags.is_empty() {
            String::new()
        } else {
            format!(" {} ", self.tags.join(" "))
        }
    }

    /// Get fields with markdown converted to HTML for specified fields.
    ///
    /// Returns a new HashMap with markdown fields converted to HTML.
    pub fn fields_as_html(&self, markdown_fields: &[String]) -> HashMap<String, String> {
        use crate::markdown::markdown_to_html;

        self.fields
            .iter()
            .map(|(name, value)| {
                let converted = if markdown_fields.contains(name) {
                    markdown_to_html(value)
                } else {
                    value.clone()
                };
                (name.clone(), converted)
            })
            .collect()
    }

    /// Convert HTML to markdown in specified fields (mutates in place).
    pub fn convert_html_to_markdown(&mut self, markdown_fields: &[String]) {
        use crate::markdown::html_to_markdown;

        for field_name in markdown_fields {
            if let Some(value) = self.fields.get_mut(field_name) {
                *value = html_to_markdown(value);
            }
        }
    }
}

/// Media file definition.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MediaDef {
    /// Filename as referenced in note fields (e.g., "audio.mp3").
    pub name: String,

    /// Path to the source file.
    pub path: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_basic_definition() {
        let toml = r#"
[package]
name = "Test Deck"
version = "1.0.0"

[[models]]
name = "Basic"
fields = ["Front", "Back"]

[[models.templates]]
name = "Card 1"
front = "{{Front}}"
back = "{{FrontSide}}<hr>{{Back}}"

[[decks]]
name = "Test Deck"

[[notes]]
deck = "Test Deck"
model = "Basic"
tags = ["test"]

[notes.fields]
Front = "Question"
Back = "Answer"
"#;

        let def = DeckDefinition::parse(toml).unwrap();
        assert_eq!(def.package.name, "Test Deck");
        assert_eq!(def.models.len(), 1);
        assert_eq!(def.models[0].fields, vec!["Front", "Back"]);
        assert_eq!(def.decks.len(), 1);
        assert_eq!(def.notes.len(), 1);
        assert_eq!(def.notes[0].fields.get("Front").unwrap(), "Question");
    }

    #[test]
    fn test_invalid_model_reference() {
        let toml = r#"
[package]
name = "Test"

[[decks]]
name = "Test Deck"

[[notes]]
deck = "Test Deck"
model = "NonExistent"

[notes.fields]
Front = "Q"
"#;

        let result = DeckDefinition::parse(toml);
        assert!(matches!(result, Err(Error::ModelNotFound(_))));
    }

    #[test]
    fn test_invalid_deck_reference() {
        let toml = r#"
[package]
name = "Test"

[[models]]
name = "Basic"
fields = ["Front"]

[[models.templates]]
name = "Card 1"
front = "{{Front}}"
back = "{{Front}}"

[[notes]]
deck = "NonExistent"
model = "Basic"

[notes.fields]
Front = "Q"
"#;

        let result = DeckDefinition::parse(toml);
        assert!(matches!(result, Err(Error::DeckNotFound(_))));
    }

    #[test]
    fn test_invalid_field_reference() {
        let toml = r#"
[package]
name = "Test"

[[models]]
name = "Basic"
fields = ["Front", "Back"]

[[models.templates]]
name = "Card 1"
front = "{{Front}}"
back = "{{Back}}"

[[decks]]
name = "Test Deck"

[[notes]]
deck = "Test Deck"
model = "Basic"

[notes.fields]
Front = "Q"
InvalidField = "X"
"#;

        let result = DeckDefinition::parse(toml);
        assert!(matches!(result, Err(Error::FieldNotFound { .. })));
    }

    #[test]
    fn test_fields_ordered() {
        let model = ModelDef {
            name: "Test".to_string(),
            fields: vec!["A".to_string(), "B".to_string(), "C".to_string()],
            templates: vec![],
            css: None,
            sort_field: None,
            id: None,
            markdown_fields: vec![],
            model_type: None,
        };

        let mut fields = HashMap::new();
        fields.insert("C".to_string(), "third".to_string());
        fields.insert("A".to_string(), "first".to_string());
        // B is missing, should be empty

        let note = NoteDef {
            deck: "Test".to_string(),
            model: "Test".to_string(),
            fields,
            tags: vec![],
            guid: None,
            note_id: None,
        };

        let ordered = note.fields_ordered(&model);
        assert_eq!(ordered, vec!["first", "", "third"]);
    }

    #[test]
    fn test_cloze_model() {
        let model = ModelDef::cloze("My Cloze", vec!["Text", "Extra"]);

        assert_eq!(model.name, "My Cloze");
        assert_eq!(model.fields, vec!["Text", "Extra"]);
        assert!(model.is_cloze());
        assert_eq!(model.model_type, Some("cloze".to_string()));
        assert_eq!(model.templates.len(), 1);
        assert_eq!(model.templates[0].name, "Cloze");
        assert!(model.templates[0].front.contains("{{cloze:Text}}"));
    }

    #[test]
    fn test_standard_model_is_not_cloze() {
        let model = ModelDef {
            name: "Basic".to_string(),
            fields: vec!["Front".to_string(), "Back".to_string()],
            templates: vec![],
            css: None,
            sort_field: None,
            id: None,
            markdown_fields: vec![],
            model_type: None,
        };

        assert!(!model.is_cloze());
    }

    #[test]
    fn test_parse_cloze_model_from_toml() {
        let toml = r#"
[package]
name = "Cloze Test"

[[models]]
name = "My Cloze"
model_type = "cloze"
fields = ["Text", "Extra"]

[[models.templates]]
name = "Cloze"
front = "{{cloze:Text}}"
back = "{{cloze:Text}}<br>{{Extra}}"

[[decks]]
name = "Cloze Test"
"#;

        let def = DeckDefinition::parse(toml).unwrap();
        assert!(def.models[0].is_cloze());
    }
}