1use 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#[derive(Debug, Clone)]
38pub struct SyncStrategy {
39 pub conflict_resolution: ConflictResolution,
41 pub pull_new_notes: bool,
43 pub push_new_notes: bool,
45 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
84pub enum ConflictResolution {
85 PreferToml,
87 PreferAnki,
89 Fail,
91 #[default]
93 Skip,
94}
95
96#[derive(Debug, Clone, Default, Serialize)]
98pub struct SyncPlan {
99 pub to_push: Vec<SyncNote>,
101 pub to_pull: Vec<SyncNote>,
103 pub conflicts: Vec<SyncConflict>,
105 pub unchanged: usize,
107}
108
109#[derive(Debug, Clone, Serialize)]
111pub struct SyncNote {
112 pub note_id: Option<i64>,
114 pub model: String,
116 pub deck: String,
118 pub first_field: String,
120}
121
122#[derive(Debug, Clone, Serialize)]
124pub struct SyncConflict {
125 pub note_id: i64,
127 pub first_field: String,
129 pub model: String,
131 pub field_changes: Vec<FieldChange>,
133 pub tag_changes: TagChanges,
135}
136
137#[derive(Debug, Clone, Default, Serialize)]
139pub struct SyncResult {
140 pub pushed: Vec<SyncedNote>,
142 pub pulled: Vec<SyncedNote>,
144 pub resolved_conflicts: Vec<ResolvedConflict>,
146 pub skipped_conflicts: Vec<SyncConflict>,
148 pub errors: Vec<SyncError>,
150 pub updated_definition: Option<DeckDefinition>,
152}
153
154#[derive(Debug, Clone, Serialize)]
156pub struct SyncedNote {
157 pub note_id: i64,
159 pub first_field: String,
161 pub was_new: bool,
163}
164
165#[derive(Debug, Clone, Serialize)]
167pub struct ResolvedConflict {
168 pub note_id: i64,
170 pub first_field: String,
172 pub resolution: String,
174}
175
176#[derive(Debug, Clone, Serialize)]
178pub struct SyncError {
179 pub description: String,
181 pub first_field: Option<String>,
183 pub error: String,
185}
186
187pub struct DeckSyncer<'a> {
189 client: &'a AnkiClient,
190 definition: DeckDefinition,
191}
192
193impl<'a> DeckSyncer<'a> {
194 pub fn new(client: &'a AnkiClient, definition: DeckDefinition) -> Self {
196 Self { client, definition }
197 }
198
199 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 fn diff_to_plan(&self, diff: DeckDiff) -> SyncPlan {
209 let mut plan = SyncPlan {
210 unchanged: diff.unchanged,
211 ..Default::default()
212 };
213
214 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 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 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 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 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 self.update_note_id(¬e_diff.first_field, ¬e_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 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, ¬e_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 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 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 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 async fn push_new_note(&self, note_diff: &crate::diff::NoteDiff) -> Result<i64> {
383 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 let markdown_fields = self
408 .definition
409 .get_model(¬e_def.model)
410 .map(|m| m.markdown_fields.clone())
411 .unwrap_or_default();
412
413 let fields = note_def.fields_as_html(&markdown_fields);
415
416 let note =
418 ankit::NoteBuilder::new(¬e_def.deck, ¬e_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 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 let markdown_fields = self
453 .definition
454 .get_model(¬e_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 async fn push_updates(
465 &self,
466 note_id: i64,
467 model_name: &str,
468 field_changes: &[FieldChange],
469 strategy: &SyncStrategy,
470 ) -> Result<()> {
471 let markdown_fields = self
473 .definition
474 .get_model(model_name)
475 .map(|m| m.markdown_fields.clone())
476 .unwrap_or_default();
477
478 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 if strategy.update_tags {
497 }
500
501 Ok(())
502 }
503
504 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 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 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 for fc in field_changes {
545 note.fields.insert(fc.field.clone(), fc.anki_value.clone());
546 }
547
548 for tag in &tag_changes.removed {
550 if !note.tags.contains(tag) {
552 note.tags.push(tag.clone());
553 }
554 }
555 for tag in &tag_changes.added {
556 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}