diaryx_core 1.0.0

Core library for Diaryx - a tool to manage markdown files with YAML frontmatter
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
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
//! Event-emitting filesystem decorator.
//!
//! This module provides [`EventEmittingFs`], a decorator that emits
//! [`FileSystemEvent`]s for all filesystem operations. This enables
//! UI updates and other reactive behaviors.
//!
//! # Architecture
//!
//! ```text
//! File Operation → EventEmittingFs → Inner FS → Emit Event
//!//!                                         CallbackRegistry.emit()
//!//!                                         JS/UI Callbacks
//! ```

use std::io::Result;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};

use crate::frontmatter;
use crate::fs::{AsyncFileSystem, BoxFuture};
use crate::link_parser;

use super::callback_registry::{CallbackRegistry, EventCallback, SubscriptionId};
use super::events::FileSystemEvent;

/// A filesystem decorator that emits events for all operations.
///
/// This decorator wraps another filesystem and emits events when operations
/// occur. It supports:
///
/// - Subscribing to events via callback functions
/// - Runtime enable/disable toggle
/// - Automatic event type detection (create vs update, rename vs move)
///
/// # Example
///
/// ```ignore
/// use diaryx_core::fs::{EventEmittingFs, InMemoryFileSystem, SyncToAsyncFs, FileSystemEvent};
/// use std::sync::Arc;
///
/// let inner_fs = SyncToAsyncFs::new(InMemoryFileSystem::new());
/// let event_fs = EventEmittingFs::new(inner_fs);
///
/// // Subscribe to events
/// let id = event_fs.on_event(Arc::new(|event| {
///     println!("Event: {:?}", event);
/// }));
///
/// // Operations now emit events
/// event_fs.write_file(Path::new("test.md"), "content").await?;
///
/// // Unsubscribe
/// event_fs.off_event(id);
/// ```
pub struct EventEmittingFs<FS: AsyncFileSystem> {
    /// The underlying filesystem.
    inner: FS,
    /// Registry of event callbacks.
    registry: Arc<CallbackRegistry>,
    /// Whether event emission is enabled.
    enabled: AtomicBool,
}

impl<FS: AsyncFileSystem> EventEmittingFs<FS> {
    /// Create a new event-emitting filesystem decorator.
    pub fn new(inner: FS) -> Self {
        Self {
            inner,
            registry: Arc::new(CallbackRegistry::new()),
            enabled: AtomicBool::new(true),
        }
    }

    /// Create a new event-emitting filesystem with a shared registry.
    pub fn with_registry(inner: FS, registry: Arc<CallbackRegistry>) -> Self {
        Self {
            inner,
            registry,
            enabled: AtomicBool::new(true),
        }
    }

    /// Check if event emission is enabled.
    pub fn is_enabled(&self) -> bool {
        self.enabled.load(Ordering::SeqCst)
    }

    /// Enable or disable event emission.
    pub fn set_enabled(&self, enabled: bool) {
        self.enabled.store(enabled, Ordering::SeqCst);
    }

    /// Subscribe to filesystem events.
    ///
    /// Returns a subscription ID that can be used to unsubscribe.
    pub fn on_event(&self, callback: EventCallback) -> SubscriptionId {
        self.registry.subscribe(callback)
    }

    /// Unsubscribe from filesystem events.
    ///
    /// Returns `true` if the subscription was found and removed.
    pub fn off_event(&self, id: SubscriptionId) -> bool {
        self.registry.unsubscribe(id)
    }

    /// Get a reference to the callback registry.
    pub fn registry(&self) -> &Arc<CallbackRegistry> {
        &self.registry
    }

    /// Get a reference to the inner filesystem.
    pub fn inner(&self) -> &FS {
        &self.inner
    }

    /// Emit an event if enabled.
    fn emit(&self, event: FileSystemEvent) {
        if self.is_enabled() {
            self.registry.emit(&event);
        }
    }

    /// Extract frontmatter from content as JSON.
    fn extract_frontmatter(&self, content: &str) -> Option<serde_json::Value> {
        frontmatter::parse_or_empty(content)
            .ok()
            .and_then(|parsed| serde_json::to_value(&parsed.frontmatter).ok())
    }

    /// Get parent path from frontmatter part_of field.
    fn get_parent_from_content(&self, file_path: &Path, content: &str) -> Option<PathBuf> {
        frontmatter::parse_or_empty(content)
            .ok()
            .and_then(|parsed| {
                parsed
                    .frontmatter
                    .get("part_of")
                    .and_then(|v| v.as_str())
                    .map(|raw| {
                        let parsed = link_parser::parse_link(raw);
                        PathBuf::from(link_parser::to_canonical(&parsed, file_path))
                    })
            })
    }
}

// Implement Clone if the inner FS is Clone
impl<FS: AsyncFileSystem + Clone> Clone for EventEmittingFs<FS> {
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            registry: Arc::clone(&self.registry),
            enabled: AtomicBool::new(self.enabled.load(Ordering::SeqCst)),
        }
    }
}

// AsyncFileSystem implementation - native
#[cfg(not(target_arch = "wasm32"))]
impl<FS: AsyncFileSystem + Send + Sync> AsyncFileSystem for EventEmittingFs<FS> {
    fn read_to_string<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, Result<String>> {
        self.inner.read_to_string(path)
    }

    fn write_file<'a>(&'a self, path: &'a Path, content: &'a str) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            // Check if file exists and get old frontmatter (for create vs update detection)
            let old_frontmatter = if self.is_enabled() {
                self.inner
                    .read_to_string(path)
                    .await
                    .ok()
                    .and_then(|old_content| self.extract_frontmatter(&old_content))
            } else {
                None
            };
            let existed =
                old_frontmatter.is_some() || (!self.is_enabled() && self.inner.exists(path).await);

            // Write to inner filesystem
            let result = self.inner.write_file(path, content).await;

            // Emit event if write succeeded
            if result.is_ok() {
                let new_frontmatter = self.extract_frontmatter(content);
                let parent_path = self.get_parent_from_content(path, content);

                if existed {
                    // File existed - only emit MetadataChanged if frontmatter actually changed
                    if let Some(new_fm) = new_frontmatter {
                        let changed = match &old_frontmatter {
                            Some(old_fm) => old_fm != &new_fm,
                            None => true, // No old frontmatter means it was added
                        };
                        if changed {
                            self.emit(FileSystemEvent::metadata_changed(
                                path.to_path_buf(),
                                new_fm,
                            ));
                        }
                    }
                    // If new file has no frontmatter but old did, that's also a change
                    // but MetadataChanged expects frontmatter, so we skip this case
                } else {
                    // New file - emit file created
                    self.emit(FileSystemEvent::file_created_with_metadata(
                        path.to_path_buf(),
                        new_frontmatter,
                        parent_path,
                    ));
                }
            }

            result
        })
    }

    fn create_new<'a>(&'a self, path: &'a Path, content: &'a str) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            let result = self.inner.create_new(path, content).await;

            if result.is_ok() {
                let frontmatter = self.extract_frontmatter(content);
                let parent_path = self.get_parent_from_content(path, content);

                self.emit(FileSystemEvent::file_created_with_metadata(
                    path.to_path_buf(),
                    frontmatter,
                    parent_path,
                ));
            }

            result
        })
    }

    fn delete_file<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            // Try to read parent path before deletion
            let parent_path = if self.is_enabled() {
                self.inner
                    .read_to_string(path)
                    .await
                    .ok()
                    .and_then(|content| self.get_parent_from_content(path, &content))
            } else {
                None
            };

            let result = self.inner.delete_file(path).await;

            if result.is_ok() {
                self.emit(FileSystemEvent::file_deleted_with_parent(
                    path.to_path_buf(),
                    parent_path,
                ));
            }

            result
        })
    }

    fn list_md_files<'a>(&'a self, dir: &'a Path) -> BoxFuture<'a, Result<Vec<PathBuf>>> {
        self.inner.list_md_files(dir)
    }

    fn exists<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, bool> {
        self.inner.exists(path)
    }

    fn create_dir_all<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, Result<()>> {
        self.inner.create_dir_all(path)
    }

    fn is_dir<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, bool> {
        self.inner.is_dir(path)
    }

    fn move_file<'a>(&'a self, from: &'a Path, to: &'a Path) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            let result = self.inner.move_file(from, to).await;

            if result.is_ok() {
                // Determine if this is a rename (same parent) or move (different parent)
                let from_parent = from.parent();
                let to_parent = to.parent();

                if from_parent == to_parent {
                    // Same parent - it's a rename
                    self.emit(FileSystemEvent::file_renamed(
                        from.to_path_buf(),
                        to.to_path_buf(),
                    ));
                } else {
                    // Different parent - it's a move
                    self.emit(FileSystemEvent::file_moved(
                        to.to_path_buf(),
                        from_parent.map(PathBuf::from),
                        to_parent.map(PathBuf::from),
                    ));
                }
            }

            result
        })
    }

    fn read_binary<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, Result<Vec<u8>>> {
        self.inner.read_binary(path)
    }

    fn write_binary<'a>(&'a self, path: &'a Path, content: &'a [u8]) -> BoxFuture<'a, Result<()>> {
        // Binary files don't emit events (they're attachments managed differently)
        self.inner.write_binary(path, content)
    }

    fn list_files<'a>(&'a self, dir: &'a Path) -> BoxFuture<'a, Result<Vec<PathBuf>>> {
        self.inner.list_files(dir)
    }

    fn get_modified_time<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, Option<i64>> {
        self.inner.get_modified_time(path)
    }

    fn mark_sync_write_start(&self, path: &Path) {
        self.inner.mark_sync_write_start(path);
    }

    fn mark_sync_write_end(&self, path: &Path) {
        self.inner.mark_sync_write_end(path);
    }
}

// WASM implementation (without Send + Sync bounds)
#[cfg(target_arch = "wasm32")]
impl<FS: AsyncFileSystem> AsyncFileSystem for EventEmittingFs<FS> {
    fn read_to_string<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, Result<String>> {
        self.inner.read_to_string(path)
    }

    fn write_file<'a>(&'a self, path: &'a Path, content: &'a str) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            // Check if file exists and get old frontmatter (for create vs update detection)
            let old_frontmatter = if self.is_enabled() {
                self.inner
                    .read_to_string(path)
                    .await
                    .ok()
                    .and_then(|old_content| self.extract_frontmatter(&old_content))
            } else {
                None
            };
            let existed =
                old_frontmatter.is_some() || (!self.is_enabled() && self.inner.exists(path).await);

            // Write to inner filesystem
            let result = self.inner.write_file(path, content).await;

            // Emit event if write succeeded
            if result.is_ok() {
                let new_frontmatter = self.extract_frontmatter(content);
                let parent_path = self.get_parent_from_content(path, content);

                if existed {
                    // File existed - only emit MetadataChanged if frontmatter actually changed
                    if let Some(new_fm) = new_frontmatter {
                        let changed = match &old_frontmatter {
                            Some(old_fm) => old_fm != &new_fm,
                            None => true, // No old frontmatter means it was added
                        };
                        if changed {
                            self.emit(FileSystemEvent::metadata_changed(
                                path.to_path_buf(),
                                new_fm,
                            ));
                        }
                    }
                    // If new file has no frontmatter but old did, that's also a change
                    // but MetadataChanged expects frontmatter, so we skip this case
                } else {
                    // New file - emit file created
                    self.emit(FileSystemEvent::file_created_with_metadata(
                        path.to_path_buf(),
                        new_frontmatter,
                        parent_path,
                    ));
                }
            }

            result
        })
    }

    fn create_new<'a>(&'a self, path: &'a Path, content: &'a str) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            let result = self.inner.create_new(path, content).await;

            if result.is_ok() {
                let frontmatter = self.extract_frontmatter(content);
                let parent_path = self.get_parent_from_content(path, content);

                self.emit(FileSystemEvent::file_created_with_metadata(
                    path.to_path_buf(),
                    frontmatter,
                    parent_path,
                ));
            }

            result
        })
    }

    fn delete_file<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            // Try to read parent path before deletion
            let parent_path = if self.is_enabled() {
                self.inner
                    .read_to_string(path)
                    .await
                    .ok()
                    .and_then(|content| self.get_parent_from_content(path, &content))
            } else {
                None
            };

            let result = self.inner.delete_file(path).await;

            if result.is_ok() {
                self.emit(FileSystemEvent::file_deleted_with_parent(
                    path.to_path_buf(),
                    parent_path,
                ));
            }

            result
        })
    }

    fn list_md_files<'a>(&'a self, dir: &'a Path) -> BoxFuture<'a, Result<Vec<PathBuf>>> {
        self.inner.list_md_files(dir)
    }

    fn exists<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, bool> {
        self.inner.exists(path)
    }

    fn create_dir_all<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, Result<()>> {
        self.inner.create_dir_all(path)
    }

    fn is_dir<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, bool> {
        self.inner.is_dir(path)
    }

    fn move_file<'a>(&'a self, from: &'a Path, to: &'a Path) -> BoxFuture<'a, Result<()>> {
        Box::pin(async move {
            let result = self.inner.move_file(from, to).await;

            if result.is_ok() {
                // Determine if this is a rename (same parent) or move (different parent)
                let from_parent = from.parent();
                let to_parent = to.parent();

                if from_parent == to_parent {
                    // Same parent - it's a rename
                    self.emit(FileSystemEvent::file_renamed(
                        from.to_path_buf(),
                        to.to_path_buf(),
                    ));
                } else {
                    // Different parent - it's a move
                    self.emit(FileSystemEvent::file_moved(
                        to.to_path_buf(),
                        from_parent.map(PathBuf::from),
                        to_parent.map(PathBuf::from),
                    ));
                }
            }

            result
        })
    }

    fn read_binary<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, Result<Vec<u8>>> {
        self.inner.read_binary(path)
    }

    fn write_binary<'a>(&'a self, path: &'a Path, content: &'a [u8]) -> BoxFuture<'a, Result<()>> {
        // Binary files don't emit events (they're attachments managed differently)
        self.inner.write_binary(path, content)
    }

    fn list_files<'a>(&'a self, dir: &'a Path) -> BoxFuture<'a, Result<Vec<PathBuf>>> {
        self.inner.list_files(dir)
    }

    fn get_modified_time<'a>(&'a self, path: &'a Path) -> BoxFuture<'a, Option<i64>> {
        self.inner.get_modified_time(path)
    }

    fn mark_sync_write_start(&self, path: &Path) {
        self.inner.mark_sync_write_start(path);
    }

    fn mark_sync_write_end(&self, path: &Path) {
        self.inner.mark_sync_write_end(path);
    }
}

impl<FS: AsyncFileSystem> std::fmt::Debug for EventEmittingFs<FS> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EventEmittingFs")
            .field("enabled", &self.is_enabled())
            .field("registry", &self.registry)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fs::{InMemoryFileSystem, SyncToAsyncFs};
    use std::io::ErrorKind;
    use std::sync::atomic::AtomicUsize;

    fn create_test_event_fs() -> EventEmittingFs<SyncToAsyncFs<InMemoryFileSystem>> {
        let inner = SyncToAsyncFs::new(InMemoryFileSystem::new());
        EventEmittingFs::new(inner)
    }

    #[derive(Clone, Default)]
    struct MarkerRecordingFs {
        starts: Arc<AtomicUsize>,
        ends: Arc<AtomicUsize>,
    }

    impl AsyncFileSystem for MarkerRecordingFs {
        fn read_to_string<'a>(&'a self, _path: &'a Path) -> BoxFuture<'a, Result<String>> {
            Box::pin(async move { Ok(String::new()) })
        }

        fn write_file<'a>(
            &'a self,
            _path: &'a Path,
            _content: &'a str,
        ) -> BoxFuture<'a, Result<()>> {
            Box::pin(async move { Ok(()) })
        }

        fn create_new<'a>(
            &'a self,
            _path: &'a Path,
            _content: &'a str,
        ) -> BoxFuture<'a, Result<()>> {
            Box::pin(async move { Ok(()) })
        }

        fn delete_file<'a>(&'a self, _path: &'a Path) -> BoxFuture<'a, Result<()>> {
            Box::pin(async move { Ok(()) })
        }

        fn list_md_files<'a>(&'a self, _dir: &'a Path) -> BoxFuture<'a, Result<Vec<PathBuf>>> {
            Box::pin(async move { Ok(vec![]) })
        }

        fn exists<'a>(&'a self, _path: &'a Path) -> BoxFuture<'a, bool> {
            Box::pin(async move { false })
        }

        fn create_dir_all<'a>(&'a self, _path: &'a Path) -> BoxFuture<'a, Result<()>> {
            Box::pin(async move { Ok(()) })
        }

        fn is_dir<'a>(&'a self, _path: &'a Path) -> BoxFuture<'a, bool> {
            Box::pin(async move { false })
        }

        fn move_file<'a>(&'a self, _from: &'a Path, _to: &'a Path) -> BoxFuture<'a, Result<()>> {
            Box::pin(async move { Err(std::io::Error::from(ErrorKind::NotFound)) })
        }

        fn mark_sync_write_start(&self, _path: &Path) {
            self.starts.fetch_add(1, Ordering::SeqCst);
        }

        fn mark_sync_write_end(&self, _path: &Path) {
            self.ends.fetch_add(1, Ordering::SeqCst);
        }
    }

    #[test]
    fn test_write_emits_file_created() {
        let fs = create_test_event_fs();
        let created_count = Arc::new(AtomicUsize::new(0));

        let counter = Arc::clone(&created_count);
        fs.on_event(Arc::new(move |event| {
            if matches!(event, FileSystemEvent::FileCreated { .. }) {
                counter.fetch_add(1, Ordering::SeqCst);
            }
        }));

        futures_lite::future::block_on(async {
            fs.write_file(Path::new("test.md"), "---\ntitle: Test\n---\nBody")
                .await
                .unwrap();
        });

        assert_eq!(created_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_write_existing_emits_metadata_changed_only_when_frontmatter_changes() {
        let fs = create_test_event_fs();
        let changed_count = Arc::new(AtomicUsize::new(0));

        // Create file first
        futures_lite::future::block_on(async {
            fs.write_file(Path::new("test.md"), "---\ntitle: First\n---\nBody")
                .await
                .unwrap();
        });

        // Now subscribe
        let counter = Arc::clone(&changed_count);
        fs.on_event(Arc::new(move |event| {
            if matches!(event, FileSystemEvent::MetadataChanged { .. }) {
                counter.fetch_add(1, Ordering::SeqCst);
            }
        }));

        // Update frontmatter - should emit MetadataChanged
        futures_lite::future::block_on(async {
            fs.write_file(Path::new("test.md"), "---\ntitle: Updated\n---\nBody")
                .await
                .unwrap();
        });
        assert_eq!(changed_count.load(Ordering::SeqCst), 1);

        // Update body only - should NOT emit MetadataChanged
        futures_lite::future::block_on(async {
            fs.write_file(
                Path::new("test.md"),
                "---\ntitle: Updated\n---\nBody changed!",
            )
            .await
            .unwrap();
        });
        assert_eq!(changed_count.load(Ordering::SeqCst), 1); // Still 1, not 2

        // Update frontmatter again - should emit MetadataChanged
        futures_lite::future::block_on(async {
            fs.write_file(
                Path::new("test.md"),
                "---\ntitle: Final Title\n---\nBody changed!",
            )
            .await
            .unwrap();
        });
        assert_eq!(changed_count.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn test_delete_emits_file_deleted() {
        let fs = create_test_event_fs();
        let deleted_count = Arc::new(AtomicUsize::new(0));

        // Create file first
        futures_lite::future::block_on(async {
            fs.write_file(Path::new("test.md"), "content")
                .await
                .unwrap();
        });

        // Subscribe
        let counter = Arc::clone(&deleted_count);
        fs.on_event(Arc::new(move |event| {
            if matches!(event, FileSystemEvent::FileDeleted { .. }) {
                counter.fetch_add(1, Ordering::SeqCst);
            }
        }));

        // Delete
        futures_lite::future::block_on(async {
            fs.delete_file(Path::new("test.md")).await.unwrap();
        });

        assert_eq!(deleted_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_disabled_skips_events() {
        let fs = create_test_event_fs();
        fs.set_enabled(false);

        let event_count = Arc::new(AtomicUsize::new(0));
        let counter = Arc::clone(&event_count);
        fs.on_event(Arc::new(move |_| {
            counter.fetch_add(1, Ordering::SeqCst);
        }));

        futures_lite::future::block_on(async {
            fs.write_file(Path::new("test.md"), "content")
                .await
                .unwrap();
        });

        assert_eq!(event_count.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn test_unsubscribe() {
        let fs = create_test_event_fs();
        let event_count = Arc::new(AtomicUsize::new(0));

        let counter = Arc::clone(&event_count);
        let id = fs.on_event(Arc::new(move |_| {
            counter.fetch_add(1, Ordering::SeqCst);
        }));

        // First write
        futures_lite::future::block_on(async {
            fs.write_file(Path::new("test1.md"), "content")
                .await
                .unwrap();
        });
        assert_eq!(event_count.load(Ordering::SeqCst), 1);

        // Unsubscribe
        assert!(fs.off_event(id));

        // Second write
        futures_lite::future::block_on(async {
            fs.write_file(Path::new("test2.md"), "content")
                .await
                .unwrap();
        });

        // Count should not have increased
        assert_eq!(event_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_move_same_parent_emits_renamed() {
        let fs = create_test_event_fs();
        let renamed_count = Arc::new(AtomicUsize::new(0));

        // Create file
        futures_lite::future::block_on(async {
            fs.write_file(Path::new("dir/old.md"), "content")
                .await
                .unwrap();
        });

        // Subscribe
        let counter = Arc::clone(&renamed_count);
        fs.on_event(Arc::new(move |event| {
            if matches!(event, FileSystemEvent::FileRenamed { .. }) {
                counter.fetch_add(1, Ordering::SeqCst);
            }
        }));

        // Move within same directory
        futures_lite::future::block_on(async {
            fs.move_file(Path::new("dir/old.md"), Path::new("dir/new.md"))
                .await
                .unwrap();
        });

        assert_eq!(renamed_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_move_different_parent_emits_moved() {
        let fs = create_test_event_fs();
        let moved_count = Arc::new(AtomicUsize::new(0));

        // Create file
        futures_lite::future::block_on(async {
            fs.create_dir_all(Path::new("dir1")).await.unwrap();
            fs.create_dir_all(Path::new("dir2")).await.unwrap();
            fs.write_file(Path::new("dir1/file.md"), "content")
                .await
                .unwrap();
        });

        // Subscribe
        let counter = Arc::clone(&moved_count);
        fs.on_event(Arc::new(move |event| {
            if matches!(event, FileSystemEvent::FileMoved { .. }) {
                counter.fetch_add(1, Ordering::SeqCst);
            }
        }));

        // Move to different directory
        futures_lite::future::block_on(async {
            fs.move_file(Path::new("dir1/file.md"), Path::new("dir2/file.md"))
                .await
                .unwrap();
        });

        assert_eq!(moved_count.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_sync_write_markers_forwarded_to_inner_fs() {
        let inner = MarkerRecordingFs::default();
        let starts = Arc::clone(&inner.starts);
        let ends = Arc::clone(&inner.ends);
        let fs = EventEmittingFs::new(inner);

        fs.mark_sync_write_start(Path::new("a.md"));
        fs.mark_sync_write_end(Path::new("a.md"));

        assert_eq!(starts.load(Ordering::SeqCst), 1);
        assert_eq!(ends.load(Ordering::SeqCst), 1);
    }
}