Skip to main content

ankit_builder/
sync.rs

1//! Bidirectional sync between TOML and Anki.
2//!
3//! This module provides functionality to synchronize a TOML deck definition
4//! with Anki, supporting both push (TOML -> Anki) and pull (Anki -> TOML)
5//! operations with conflict detection and resolution.
6//!
7//! # Example
8//!
9//! ```no_run
10//! use ankit_builder::{DeckBuilder, SyncStrategy};
11//!
12//! # async fn example() -> ankit_builder::Result<()> {
13//! let builder = DeckBuilder::from_file("deck.toml")?;
14//!
15//! // Preview what sync would do
16//! let plan = builder.plan_sync().await?;
17//! println!("{} to push, {} to pull, {} conflicts",
18//!     plan.to_push.len(), plan.to_pull.len(), plan.conflicts.len());
19//!
20//! // Execute sync with default strategy
21//! let result = builder.sync(SyncStrategy::default()).await?;
22//! println!("Pushed: {}, Pulled: {}", result.pushed.len(), result.pulled.len());
23//! # Ok(())
24//! # }
25//! ```
26
27use std::collections::HashMap;
28
29use ankit::AnkiClient;
30use serde::Serialize;
31
32use crate::diff::{DeckDiff, DeckDiffer, FieldChange, TagChanges};
33use crate::error::Result;
34use crate::schema::{DeckDefinition, NoteDef};
35
36/// Strategy for how to handle sync operations.
37#[derive(Debug, Clone)]
38pub struct SyncStrategy {
39    /// How to handle conflicts (note modified in both places).
40    pub conflict_resolution: ConflictResolution,
41    /// Pull notes that exist in Anki but not TOML.
42    pub pull_new_notes: bool,
43    /// Push notes that exist in TOML but not Anki.
44    pub push_new_notes: bool,
45    /// Sync tag changes.
46    pub update_tags: bool,
47}
48
49impl Default for SyncStrategy {
50    fn default() -> Self {
51        Self {
52            conflict_resolution: ConflictResolution::Skip,
53            pull_new_notes: false,
54            push_new_notes: true,
55            update_tags: true,
56        }
57    }
58}
59
60impl SyncStrategy {
61    /// Create a push-only strategy (TOML -> Anki).
62    pub fn push_only() -> Self {
63        Self {
64            conflict_resolution: ConflictResolution::PreferToml,
65            pull_new_notes: false,
66            push_new_notes: true,
67            update_tags: true,
68        }
69    }
70
71    /// Create a pull-only strategy (Anki -> TOML).
72    pub fn pull_only() -> Self {
73        Self {
74            conflict_resolution: ConflictResolution::PreferAnki,
75            pull_new_notes: true,
76            push_new_notes: false,
77            update_tags: true,
78        }
79    }
80}
81
82/// How to resolve conflicts when a note differs between TOML and Anki.
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
84pub enum ConflictResolution {
85    /// TOML wins - overwrite Anki with TOML values.
86    PreferToml,
87    /// Anki wins - update TOML with Anki values.
88    PreferAnki,
89    /// Fail on any conflict.
90    Fail,
91    /// Skip conflicting notes (don't sync them).
92    #[default]
93    Skip,
94}
95
96/// A plan for what sync would do, without executing it.
97#[derive(Debug, Clone, Default, Serialize)]
98pub struct SyncPlan {
99    /// Notes that would be pushed from TOML to Anki.
100    pub to_push: Vec<SyncNote>,
101    /// Notes that would be pulled from Anki to TOML.
102    pub to_pull: Vec<SyncNote>,
103    /// Notes that have conflicts (modified in both places).
104    pub conflicts: Vec<SyncConflict>,
105    /// Number of notes that are identical (no action needed).
106    pub unchanged: usize,
107}
108
109/// A note involved in sync.
110#[derive(Debug, Clone, Serialize)]
111pub struct SyncNote {
112    /// The Anki note ID (if known).
113    pub note_id: Option<i64>,
114    /// Model name.
115    pub model: String,
116    /// Deck name.
117    pub deck: String,
118    /// First field value (identifier).
119    pub first_field: String,
120}
121
122/// A conflict where a note differs between TOML and Anki.
123#[derive(Debug, Clone, Serialize)]
124pub struct SyncConflict {
125    /// The Anki note ID.
126    pub note_id: i64,
127    /// First field value (identifier).
128    pub first_field: String,
129    /// Model name.
130    pub model: String,
131    /// Fields that differ.
132    pub field_changes: Vec<FieldChange>,
133    /// Tag changes.
134    pub tag_changes: TagChanges,
135}
136
137/// Result of a sync operation.
138#[derive(Debug, Clone, Default, Serialize)]
139pub struct SyncResult {
140    /// Notes pushed from TOML to Anki.
141    pub pushed: Vec<SyncedNote>,
142    /// Notes pulled from Anki to TOML.
143    pub pulled: Vec<SyncedNote>,
144    /// Conflicts that were resolved.
145    pub resolved_conflicts: Vec<ResolvedConflict>,
146    /// Conflicts that were skipped.
147    pub skipped_conflicts: Vec<SyncConflict>,
148    /// Errors that occurred during sync.
149    pub errors: Vec<SyncError>,
150    /// Updated TOML definition (if pull_new_notes or conflicts resolved to Anki).
151    pub updated_definition: Option<DeckDefinition>,
152}
153
154/// A note that was synced.
155#[derive(Debug, Clone, Serialize)]
156pub struct SyncedNote {
157    /// The Anki note ID.
158    pub note_id: i64,
159    /// First field value.
160    pub first_field: String,
161    /// Whether this was a new note or an update.
162    pub was_new: bool,
163}
164
165/// A conflict that was resolved.
166#[derive(Debug, Clone, Serialize)]
167pub struct ResolvedConflict {
168    /// The Anki note ID.
169    pub note_id: i64,
170    /// First field value.
171    pub first_field: String,
172    /// How it was resolved.
173    pub resolution: String,
174}
175
176/// An error that occurred during sync.
177#[derive(Debug, Clone, Serialize)]
178pub struct SyncError {
179    /// Description of what failed.
180    pub description: String,
181    /// The first field of the note (if applicable).
182    pub first_field: Option<String>,
183    /// The error message.
184    pub error: String,
185}
186
187/// Synchronizes a TOML definition with Anki.
188pub struct DeckSyncer<'a> {
189    client: &'a AnkiClient,
190    definition: DeckDefinition,
191}
192
193impl<'a> DeckSyncer<'a> {
194    /// Create a new syncer.
195    pub fn new(client: &'a AnkiClient, definition: DeckDefinition) -> Self {
196        Self { client, definition }
197    }
198
199    /// Plan what sync would do without executing it.
200    pub async fn plan(&self) -> Result<SyncPlan> {
201        let differ = DeckDiffer::new(self.client, &self.definition);
202        let diff = differ.diff().await?;
203
204        Ok(self.diff_to_plan(diff))
205    }
206
207    /// Convert a diff to a sync plan.
208    fn diff_to_plan(&self, diff: DeckDiff) -> SyncPlan {
209        let mut plan = SyncPlan {
210            unchanged: diff.unchanged,
211            ..Default::default()
212        };
213
214        // Notes only in TOML -> to_push
215        for note in diff.toml_only {
216            plan.to_push.push(SyncNote {
217                note_id: None,
218                model: note.model,
219                deck: note.deck,
220                first_field: note.first_field,
221            });
222        }
223
224        // Notes only in Anki -> to_pull
225        for note in diff.anki_only {
226            plan.to_pull.push(SyncNote {
227                note_id: note.note_id,
228                model: note.model,
229                deck: note.deck,
230                first_field: note.first_field,
231            });
232        }
233
234        // Modified notes -> conflicts
235        for modified in diff.modified {
236            plan.conflicts.push(SyncConflict {
237                note_id: modified.note_id,
238                first_field: modified.first_field,
239                model: modified.model,
240                field_changes: modified.field_changes,
241                tag_changes: modified.tag_changes,
242            });
243        }
244
245        plan
246    }
247
248    /// Execute sync with the given strategy.
249    pub async fn sync(mut self, strategy: SyncStrategy) -> Result<SyncResult> {
250        let differ = DeckDiffer::new(self.client, &self.definition);
251        let diff = differ.diff().await?;
252
253        let mut result = SyncResult::default();
254        let mut definition_modified = false;
255
256        // Handle notes only in TOML (push to Anki)
257        if strategy.push_new_notes {
258            for note_diff in &diff.toml_only {
259                match self.push_new_note(note_diff).await {
260                    Ok(note_id) => {
261                        // Update the definition with the assigned note ID
262                        self.update_note_id(&note_diff.first_field, &note_diff.model, note_id);
263                        definition_modified = true;
264
265                        result.pushed.push(SyncedNote {
266                            note_id,
267                            first_field: note_diff.first_field.clone(),
268                            was_new: true,
269                        });
270                    }
271                    Err(e) => {
272                        result.errors.push(SyncError {
273                            description: "Failed to push new note".to_string(),
274                            first_field: Some(note_diff.first_field.clone()),
275                            error: e.to_string(),
276                        });
277                    }
278                }
279            }
280        }
281
282        // Handle notes only in Anki (pull to TOML)
283        if strategy.pull_new_notes {
284            for note_diff in &diff.anki_only {
285                if let Some(note_id) = note_diff.note_id {
286                    match self.pull_note(note_id, &note_diff.deck).await {
287                        Ok(note_def) => {
288                            self.definition.notes.push(note_def);
289                            definition_modified = true;
290                            result.pulled.push(SyncedNote {
291                                note_id,
292                                first_field: note_diff.first_field.clone(),
293                                was_new: true,
294                            });
295                        }
296                        Err(e) => {
297                            result.errors.push(SyncError {
298                                description: "Failed to pull note".to_string(),
299                                first_field: Some(note_diff.first_field.clone()),
300                                error: e.to_string(),
301                            });
302                        }
303                    }
304                }
305            }
306        }
307
308        // Handle conflicts (modified in both)
309        for modified in diff.modified {
310            let conflict = SyncConflict {
311                note_id: modified.note_id,
312                first_field: modified.first_field.clone(),
313                model: modified.model.clone(),
314                field_changes: modified.field_changes.clone(),
315                tag_changes: modified.tag_changes.clone(),
316            };
317
318            match strategy.conflict_resolution {
319                ConflictResolution::Fail => {
320                    return Err(crate::error::Error::SyncConflict(format!(
321                        "Conflict on note '{}' - use a different conflict resolution strategy",
322                        modified.first_field
323                    )));
324                }
325                ConflictResolution::Skip => {
326                    result.skipped_conflicts.push(conflict);
327                }
328                ConflictResolution::PreferToml => {
329                    // Push TOML values to Anki
330                    match self
331                        .push_updates(
332                            modified.note_id,
333                            &modified.model,
334                            &modified.field_changes,
335                            &strategy,
336                        )
337                        .await
338                    {
339                        Ok(_) => {
340                            result.resolved_conflicts.push(ResolvedConflict {
341                                note_id: modified.note_id,
342                                first_field: modified.first_field,
343                                resolution: "Pushed TOML values to Anki".to_string(),
344                            });
345                        }
346                        Err(e) => {
347                            result.errors.push(SyncError {
348                                description: "Failed to push conflict resolution".to_string(),
349                                first_field: Some(conflict.first_field.clone()),
350                                error: e.to_string(),
351                            });
352                            result.skipped_conflicts.push(conflict);
353                        }
354                    }
355                }
356                ConflictResolution::PreferAnki => {
357                    // Update TOML with Anki values
358                    self.update_definition_from_anki(
359                        &modified.first_field,
360                        &modified.model,
361                        &modified.field_changes,
362                        &modified.tag_changes,
363                    );
364                    definition_modified = true;
365                    result.resolved_conflicts.push(ResolvedConflict {
366                        note_id: modified.note_id,
367                        first_field: modified.first_field,
368                        resolution: "Updated TOML with Anki values".to_string(),
369                    });
370                }
371            }
372        }
373
374        if definition_modified {
375            result.updated_definition = Some(self.definition);
376        }
377
378        Ok(result)
379    }
380
381    /// Push a new note from TOML to Anki.
382    async fn push_new_note(&self, note_diff: &crate::diff::NoteDiff) -> Result<i64> {
383        // Find the note in our definition
384        let note_def = self
385            .definition
386            .notes
387            .iter()
388            .find(|n| {
389                let model = self.definition.get_model(&n.model);
390                if let Some(model) = model {
391                    if let Some(first_field_name) = model.fields.first() {
392                        let first_field =
393                            n.fields.get(first_field_name).cloned().unwrap_or_default();
394                        return first_field == note_diff.first_field && n.model == note_diff.model;
395                    }
396                }
397                false
398            })
399            .ok_or_else(|| {
400                crate::error::Error::InvalidDefinition(format!(
401                    "Note '{}' not found in definition",
402                    note_diff.first_field
403                ))
404            })?;
405
406        // Get markdown fields for this model
407        let markdown_fields = self
408            .definition
409            .get_model(&note_def.model)
410            .map(|m| m.markdown_fields.clone())
411            .unwrap_or_default();
412
413        // Convert markdown to HTML for markdown fields
414        let fields = note_def.fields_as_html(&markdown_fields);
415
416        // Create the note in Anki
417        let note =
418            ankit::NoteBuilder::new(&note_def.deck, &note_def.model).tags(note_def.tags.clone());
419
420        let mut note = note;
421        for (field, value) in &fields {
422            note = note.field(field, value);
423        }
424
425        let note_id = self.client.notes().add(note.build()).await?;
426        Ok(note_id)
427    }
428
429    /// Pull a note from Anki to TOML definition.
430    async fn pull_note(&self, note_id: i64, deck: &str) -> Result<NoteDef> {
431        let note_infos = self.client.notes().info(&[note_id]).await?;
432        let note_info = note_infos.into_iter().next().ok_or_else(|| {
433            crate::error::Error::InvalidDefinition(format!("Note {} not found in Anki", note_id))
434        })?;
435
436        let fields: HashMap<String, String> = note_info
437            .fields
438            .into_iter()
439            .map(|(name, field)| (name, field.value))
440            .collect();
441
442        let mut note_def = NoteDef {
443            deck: deck.to_string(),
444            model: note_info.model_name.clone(),
445            fields,
446            tags: note_info.tags,
447            guid: None,
448            note_id: Some(note_id),
449        };
450
451        // Convert HTML to markdown for markdown fields
452        let markdown_fields = self
453            .definition
454            .get_model(&note_info.model_name)
455            .map(|m| m.markdown_fields.clone())
456            .unwrap_or_default();
457
458        note_def.convert_html_to_markdown(&markdown_fields);
459
460        Ok(note_def)
461    }
462
463    /// Push field updates to Anki for conflict resolution.
464    async fn push_updates(
465        &self,
466        note_id: i64,
467        model_name: &str,
468        field_changes: &[FieldChange],
469        strategy: &SyncStrategy,
470    ) -> Result<()> {
471        // Get markdown fields for this model
472        let markdown_fields = self
473            .definition
474            .get_model(model_name)
475            .map(|m| m.markdown_fields.clone())
476            .unwrap_or_default();
477
478        // Build the fields to update (use TOML values, converting markdown if needed)
479        let fields: HashMap<String, String> = field_changes
480            .iter()
481            .map(|fc| {
482                let value = if markdown_fields.contains(&fc.field) {
483                    crate::markdown::markdown_to_html(&fc.toml_value)
484                } else {
485                    fc.toml_value.clone()
486                };
487                (fc.field.clone(), value)
488            })
489            .collect();
490
491        if !fields.is_empty() {
492            self.client.notes().update_fields(note_id, &fields).await?;
493        }
494
495        // Update tags if enabled
496        if strategy.update_tags {
497            // We'd need the full tag lists to do this properly
498            // For now, skip tag sync on conflicts
499        }
500
501        Ok(())
502    }
503
504    /// Update the note_id field for a note in the definition.
505    fn update_note_id(&mut self, first_field: &str, model_name: &str, note_id: i64) {
506        for note in &mut self.definition.notes {
507            let model = self.definition.models.iter().find(|m| m.name == note.model);
508            if let Some(model) = model {
509                if let Some(first_field_name) = model.fields.first() {
510                    let note_first_field = note
511                        .fields
512                        .get(first_field_name)
513                        .cloned()
514                        .unwrap_or_default();
515                    if note_first_field == first_field && note.model == model_name {
516                        note.note_id = Some(note_id);
517                        return;
518                    }
519                }
520            }
521        }
522    }
523
524    /// Update the TOML definition with Anki values for a note.
525    fn update_definition_from_anki(
526        &mut self,
527        first_field: &str,
528        model_name: &str,
529        field_changes: &[FieldChange],
530        tag_changes: &TagChanges,
531    ) {
532        // Find the note in our definition
533        for note in &mut self.definition.notes {
534            let model = self.definition.models.iter().find(|m| m.name == note.model);
535            if let Some(model) = model {
536                if let Some(first_field_name) = model.fields.first() {
537                    let note_first_field = note
538                        .fields
539                        .get(first_field_name)
540                        .cloned()
541                        .unwrap_or_default();
542                    if note_first_field == first_field && note.model == model_name {
543                        // Update fields with Anki values
544                        for fc in field_changes {
545                            note.fields.insert(fc.field.clone(), fc.anki_value.clone());
546                        }
547
548                        // Update tags
549                        for tag in &tag_changes.removed {
550                            // Tags in Anki but not TOML - add to TOML
551                            if !note.tags.contains(tag) {
552                                note.tags.push(tag.clone());
553                            }
554                        }
555                        for tag in &tag_changes.added {
556                            // Tags in TOML but not Anki - remove from TOML
557                            note.tags.retain(|t| t != tag);
558                        }
559
560                        return;
561                    }
562                }
563            }
564        }
565    }
566}
567
568#[cfg(test)]
569mod tests {
570    use super::*;
571
572    #[test]
573    fn test_sync_strategy_default() {
574        let strategy = SyncStrategy::default();
575        assert_eq!(strategy.conflict_resolution, ConflictResolution::Skip);
576        assert!(!strategy.pull_new_notes);
577        assert!(strategy.push_new_notes);
578        assert!(strategy.update_tags);
579    }
580
581    #[test]
582    fn test_sync_strategy_push_only() {
583        let strategy = SyncStrategy::push_only();
584        assert_eq!(strategy.conflict_resolution, ConflictResolution::PreferToml);
585        assert!(!strategy.pull_new_notes);
586        assert!(strategy.push_new_notes);
587    }
588
589    #[test]
590    fn test_sync_strategy_pull_only() {
591        let strategy = SyncStrategy::pull_only();
592        assert_eq!(strategy.conflict_resolution, ConflictResolution::PreferAnki);
593        assert!(strategy.pull_new_notes);
594        assert!(!strategy.push_new_notes);
595    }
596}