rustledger-loader 0.12.0

Beancount file loader with include resolution and options parsing
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
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
//! Integration tests for the loader crate.
//!
//! Tests are based on patterns from beancount's test suite.

use rustledger_loader::{LoadError, Loader, load_raw};
use std::path::Path;

fn fixtures_path(name: &str) -> std::path::PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures")
        .join(name)
}

#[test]
fn test_load_simple_file() {
    let path = fixtures_path("simple.beancount");
    let result = load_raw(&path).expect("should load simple file");

    // Check options were parsed
    assert_eq!(result.options.title, Some("Test Ledger".to_string()));
    assert_eq!(result.options.operating_currency, vec!["USD".to_string()]);

    // Check directives were loaded
    assert!(!result.directives.is_empty());

    // Should have 3 open directives, 1 transaction, 1 balance
    let opens = result
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Open(_)))
        .count();
    assert_eq!(opens, 3, "expected 3 open directives");

    let txns = result
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Transaction(_)))
        .count();
    assert_eq!(txns, 1, "expected 1 transaction");

    // No errors
    assert!(result.errors.is_empty(), "expected no errors");
}

#[test]
fn test_load_with_include() {
    let path = fixtures_path("main_with_include.beancount");
    let result = load_raw(&path).expect("should load file with include");

    // Should have directives from both files
    // main_with_include.beancount: 1 transaction
    // accounts.beancount: 3 open directives
    let opens = result
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Open(_)))
        .count();
    assert_eq!(opens, 3, "expected 3 open directives from included file");

    let txns = result
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Transaction(_)))
        .count();
    assert_eq!(txns, 1, "expected 1 transaction from main file");

    // Check source map has both files
    assert_eq!(
        result.source_map.files().len(),
        2,
        "expected 2 files in source map"
    );

    // No errors
    assert!(result.errors.is_empty(), "expected no errors");
}

#[test]
fn test_load_include_cycle_detection() {
    let path = fixtures_path("cycle_a.beancount");
    let result = Loader::new().load(&path);

    match result {
        Err(LoadError::IncludeCycle { cycle }) => {
            // The cycle should include both files
            assert!(cycle.len() >= 2, "cycle should have at least 2 entries");
            let cycle_str = cycle.join(" -> ");
            assert!(
                cycle_str.contains("cycle_a.beancount"),
                "cycle should mention cycle_a.beancount"
            );
            assert!(
                cycle_str.contains("cycle_b.beancount"),
                "cycle should mention cycle_b.beancount"
            );
        }
        Ok(result) => {
            // If we get Ok, check if cycle was caught as an error in result.errors
            let has_cycle_error = result
                .errors
                .iter()
                .any(|e| matches!(e, LoadError::IncludeCycle { .. }));
            assert!(has_cycle_error, "expected include cycle to be detected");
        }
        Err(e) => panic!("expected IncludeCycle error, got: {e}"),
    }
}

/// Regression test for issue #765.
///
/// The pta-standards `include-cycle-detection` conformance test
/// asserts on `error_contains: ["Duplicate filename"]`, matching Python
/// beancount's wording for the same condition. rustledger previously
/// said `"include cycle detected: ..."` which was more informative but
/// didn't match the substring. We now lead with `"Duplicate filename
/// parsed: \"<file>\""` and preserve the cycle path in a trailing
/// parenthetical. This test pins the exact phrasing so a refactor
/// can't silently drop the conformance-required substring.
#[test]
fn test_include_cycle_display_contains_duplicate_filename_issue_765() {
    let path = fixtures_path("cycle_a.beancount");
    let result = Loader::new().load(&path);

    // Find the IncludeCycle error in either the Err path or the
    // load_result.errors collection (the loader supports partial
    // results).
    let err: LoadError = match result {
        Err(e @ LoadError::IncludeCycle { .. }) => e,
        Ok(result) => result
            .errors
            .into_iter()
            .find(|e| matches!(e, LoadError::IncludeCycle { .. }))
            .expect("expected IncludeCycle error in load_result.errors"),
        Err(other) => panic!("expected IncludeCycle error, got: {other}"),
    };

    let rendered = err.to_string();
    assert!(
        rendered.contains("Duplicate filename"),
        "IncludeCycle Display must contain 'Duplicate filename' for \
         beancount conformance (#765). Got: {rendered}"
    );
    assert!(
        rendered.contains("cycle_a.beancount"),
        "IncludeCycle Display must mention the cycle file. Got: {rendered}"
    );
    assert!(
        rendered.contains("include cycle:"),
        "IncludeCycle Display should still preserve the cycle path \
         for debuggability. Got: {rendered}"
    );
}

#[test]
fn test_load_missing_include() {
    let path = fixtures_path("missing_include.beancount");
    let result = load_raw(&path).expect("should load file even with missing include");

    // Should have IO error for missing file
    let has_io_error = result
        .errors
        .iter()
        .any(|e| matches!(e, LoadError::Io { .. }));
    assert!(has_io_error, "expected IO error for missing include");

    // Should still have the open directive from the main file
    let opens = result
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Open(_)))
        .count();
    assert_eq!(opens, 1, "expected 1 open directive from main file");
}

#[test]
fn test_load_with_plugins() {
    let path = fixtures_path("with_plugin.beancount");
    let result = load_raw(&path).expect("should load file with plugins");

    // Should have 2 plugin directives
    assert_eq!(result.plugins.len(), 2, "expected 2 plugins");

    // Check first plugin
    assert_eq!(result.plugins[0].name, "beancount.plugins.leafonly");
    assert!(result.plugins[0].config.is_none());

    // Check second plugin with config
    assert_eq!(result.plugins[1].name, "beancount.plugins.check_commodity");
    assert_eq!(result.plugins[1].config, Some("config_string".to_string()));
}

#[test]
fn test_load_with_parse_errors() {
    let path = fixtures_path("parse_error.beancount");
    let result = load_raw(&path).expect("should load file even with parse errors");

    // Should have parse errors
    let has_parse_error = result
        .errors
        .iter()
        .any(|e| matches!(e, LoadError::ParseErrors { .. }));
    assert!(has_parse_error, "expected parse error");

    // Should still have valid directives (error recovery)
    // At minimum: 1 open from before error, 1 open from after error
    let opens = result
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Open(_)))
        .count();
    assert!(
        opens >= 1,
        "expected at least 1 open directive despite errors"
    );
}

#[test]
fn test_load_nonexistent_file() {
    let path = fixtures_path("does_not_exist.beancount");
    let result = Loader::new().load(&path);

    match result {
        Err(LoadError::Io { path: err_path, .. }) => {
            assert!(
                err_path.to_string_lossy().contains("does_not_exist"),
                "error should mention the missing file"
            );
        }
        Ok(_) => panic!("expected IO error for nonexistent file"),
        Err(e) => panic!("expected IO error, got: {e}"),
    }
}

#[test]
fn test_loader_reuse() {
    // Test that a single Loader instance can be used to load multiple files
    let mut loader = Loader::new();

    let path1 = fixtures_path("simple.beancount");
    let result1 = loader.load(&path1).expect("should load first file");
    assert!(!result1.directives.is_empty());

    // Note: Loader tracks loaded files, so loading again might return cached/empty
    // This tests the expected behavior
    let path2 = fixtures_path("accounts.beancount");
    let mut loader2 = Loader::new();
    let result2 = loader2.load(&path2).expect("should load second file");
    assert!(!result2.directives.is_empty());
}

#[test]
fn test_source_map_line_lookup() {
    let path = fixtures_path("simple.beancount");
    let result = load_raw(&path).expect("should load simple file");

    // Source map should have the file
    assert!(!result.source_map.files().is_empty());

    let file = &result.source_map.files()[0];
    assert!(file.path.to_string_lossy().contains("simple.beancount"));

    // Should be able to look up line/column for positions
    // The first directive should have valid span info
    if let Some(first) = result.directives.first() {
        let (line, col) = file.line_col(first.span.start);
        assert!(line >= 1, "line should be >= 1");
        assert!(col >= 1, "col should be >= 1");
    }
}

#[test]
fn test_duplicate_include_ignored() {
    // Create a scenario where the same file is included multiple times
    // It should only be loaded once
    let path = fixtures_path("main_with_include.beancount");
    let result = load_raw(&path).expect("should load file");

    // Each unique file should only be in source map once
    let file_count = result.source_map.files().len();
    assert_eq!(
        file_count, 2,
        "should have exactly 2 files (main + accounts)"
    );
}

// ============================================================================
// Glob Include Pattern Tests
// ============================================================================

#[test]
fn test_glob_include_pattern() {
    let path = fixtures_path("glob_test/main.beancount");
    let result = load_raw(&path).expect("should load file with glob include");

    // Should have loaded files from the glob pattern
    // main.beancount: 1 open directive
    // transactions/2024.beancount: 1 open, 1 transaction
    // transactions/2025.beancount: 1 open, 1 transaction
    let opens = result
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Open(_)))
        .count();
    assert_eq!(
        opens, 3,
        "expected 3 open directives (1 from main, 2 from transactions)"
    );

    let txns = result
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Transaction(_)))
        .count();
    assert_eq!(txns, 2, "expected 2 transactions from glob-matched files");

    // Source map should have 3 files
    assert_eq!(
        result.source_map.files().len(),
        3,
        "expected 3 files in source map (main + 2 from glob)"
    );

    // No errors expected
    assert!(
        result.errors.is_empty(),
        "expected no errors, got: {:?}",
        result.errors
    );
}

#[test]
fn test_glob_include_no_match() {
    let path = fixtures_path("glob_nomatch.beancount");
    let result = load_raw(&path).expect("should load file even with no-match glob");

    // Should have GlobNoMatch error
    let has_glob_error = result
        .errors
        .iter()
        .any(|e| matches!(e, LoadError::GlobNoMatch { .. }));
    assert!(
        has_glob_error,
        "expected GlobNoMatch error for pattern with no matches"
    );

    // Should still have the open directive from the main file
    let opens = result
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Open(_)))
        .count();
    assert_eq!(opens, 1, "expected 1 open directive from main file");
}

#[test]
fn test_glob_include_deterministic_order() {
    // Load twice and ensure same order
    let path = fixtures_path("glob_test/main.beancount");

    let result1 = load_raw(&path).expect("should load file");
    let result2 = load_raw(&path).expect("should load file again");

    // File order in source map should be deterministic
    let files1: Vec<_> = result1
        .source_map
        .files()
        .iter()
        .map(|f| f.path.clone())
        .collect();
    let files2: Vec<_> = result2
        .source_map
        .files()
        .iter()
        .map(|f| f.path.clone())
        .collect();

    assert_eq!(
        files1, files2,
        "file order should be deterministic across loads"
    );
}

// ============================================================================
// Path Security Tests
// ============================================================================

#[test]
fn test_path_traversal_blocked_with_security_enabled() {
    let path = fixtures_path("path_traversal.beancount");
    let result = Loader::new()
        .with_path_security(true)
        .load(&path)
        .expect("should load file even with blocked include");

    // Should have path traversal error
    let has_traversal_error = result
        .errors
        .iter()
        .any(|e| matches!(e, LoadError::PathTraversal { .. }));
    assert!(
        has_traversal_error,
        "expected PathTraversal error when security is enabled"
    );

    // Should still have the open directive from the main file
    let opens = result
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Open(_)))
        .count();
    assert_eq!(opens, 1, "expected 1 open directive from main file");
}

#[test]
fn test_path_traversal_allowed_without_security() {
    let path = fixtures_path("path_traversal.beancount");
    let result = load_raw(&path).expect("should load file");

    // Without security enabled, should NOT have path traversal error
    // (though may have IO error if include target doesn't exist or parse error if not valid beancount)
    let has_traversal_error = result
        .errors
        .iter()
        .any(|e| matches!(e, LoadError::PathTraversal { .. }));
    assert!(
        !has_traversal_error,
        "should not have PathTraversal error when security is disabled"
    );
}

#[test]
fn test_with_custom_root_dir() {
    let path = fixtures_path("main_with_include.beancount");
    let fixtures_dir = fixtures_path("");

    // With root set to fixtures dir, include should work
    let result = Loader::new()
        .with_root_dir(fixtures_dir)
        .load(&path)
        .expect("should load file");

    // Should not have path traversal errors
    let has_traversal_error = result
        .errors
        .iter()
        .any(|e| matches!(e, LoadError::PathTraversal { .. }));
    assert!(
        !has_traversal_error,
        "should not have PathTraversal error for valid include"
    );

    // Should have loaded the include
    assert_eq!(result.source_map.files().len(), 2, "should have 2 files");
}

// ============================================================================
// Process Pipeline Tests (Coverage improvement for process.rs)
// ============================================================================

use rustledger_loader::{ErrorSeverity, LedgerError, LoadOptions, load, process};

#[test]
fn test_process_pipeline_with_validation() {
    let path = fixtures_path("simple.beancount");
    let options = LoadOptions {
        validate: true,
        ..Default::default()
    };

    let ledger = load(&path, &options).expect("should load and process");

    // Should have processed directives
    assert!(!ledger.directives.is_empty());

    // Options should be preserved
    assert_eq!(ledger.options.title, Some("Test Ledger".to_string()));
}

#[test]
fn test_process_pipeline_without_validation() {
    let path = fixtures_path("simple.beancount");
    let options = LoadOptions {
        validate: false,
        ..Default::default()
    };

    let ledger = load(&path, &options).expect("should load without validation");

    // Should still have directives
    assert!(!ledger.directives.is_empty());
}

#[test]
fn test_process_directives_sorted_by_date() {
    let path = fixtures_path("simple.beancount");
    let options = LoadOptions::default();

    let ledger = load(&path, &options).expect("should load and process");

    // Check that directives are sorted by date
    let mut last_date = None;
    for dir in &ledger.directives {
        let date = dir.value.date();
        if let Some(prev) = last_date {
            assert!(
                date >= prev,
                "directives should be sorted by date: {prev} should come before {date}"
            );
        }
        last_date = Some(date);
    }
}

#[test]
fn test_process_raw_mode() {
    let path = fixtures_path("simple.beancount");
    let options = LoadOptions::raw();

    let ledger = load(&path, &options).expect("should load in raw mode");

    // Raw mode should still have directives but skip plugins/validation
    assert!(!ledger.directives.is_empty());
}

#[test]
fn test_process_with_extra_plugins() {
    let path = fixtures_path("simple.beancount");
    let options = LoadOptions {
        run_plugins: false, // Don't run file plugins
        extra_plugins: vec!["check_commodity".to_string()],
        extra_plugin_configs: vec![None],
        ..Default::default()
    };

    let ledger = load(&path, &options).expect("should load with extra plugins");

    // The check_commodity plugin should have been run
    // It adds warnings for undeclared commodities
    // Just check that we processed without error
    assert!(!ledger.directives.is_empty());
}

#[test]
fn test_process_with_auto_accounts() {
    let path = fixtures_path("simple.beancount");
    let options = LoadOptions {
        auto_accounts: true,
        ..Default::default()
    };

    let ledger = load(&path, &options).expect("should load with auto_accounts");

    // auto_accounts plugin adds Open directives for used accounts
    // Just verify it processed successfully
    assert!(!ledger.directives.is_empty());
}

#[test]
fn test_ledger_error_creation() {
    use rustledger_loader::ErrorLocation;

    // Test error creation
    let err = LedgerError::error("E001", "Test error message");
    assert_eq!(err.code, "E001");
    assert_eq!(err.message, "Test error message");
    assert!(matches!(err.severity, ErrorSeverity::Error));
    assert!(err.location.is_none());

    // Test warning creation
    let warn = LedgerError::warning("W001", "Test warning");
    assert!(matches!(warn.severity, ErrorSeverity::Warning));

    // Test with location
    let err_with_loc = LedgerError::error("E002", "Located error").with_location(ErrorLocation {
        file: std::path::PathBuf::from("test.beancount"),
        line: 10,
        column: 5,
    });
    assert!(err_with_loc.location.is_some());
    let loc = err_with_loc.location.unwrap();
    assert_eq!(loc.line, 10);
    assert_eq!(loc.column, 5);
}

#[test]
fn test_load_options_default() {
    let options = LoadOptions::default();

    assert!(options.validate);
    assert!(options.run_plugins);
    assert!(!options.auto_accounts);
    assert!(options.extra_plugins.is_empty());
    assert!(!options.path_security);
}

#[test]
fn test_load_options_raw() {
    let options = LoadOptions::raw();

    assert!(!options.validate);
    assert!(!options.run_plugins);
    assert!(!options.auto_accounts);
}

#[test]
fn test_process_from_load_result() {
    // Test calling process() directly on a LoadResult
    let path = fixtures_path("simple.beancount");
    let raw = load_raw(&path).expect("should load raw");

    let options = LoadOptions {
        validate: true,
        ..Default::default()
    };

    let ledger = process(raw, &options).expect("should process");
    assert!(!ledger.directives.is_empty());
}

#[test]
fn test_process_preserves_display_context() {
    let path = fixtures_path("simple.beancount");
    let options = LoadOptions::default();

    let ledger = load(&path, &options).expect("should load");

    // Display context should be available for formatting
    // Just check it exists (it's populated from directives)
    let _ctx = &ledger.display_context;
    // If we got here, display context was created successfully
}

// ============================================================================
// Booking Method Default Tests (Issue #775)
// ============================================================================

#[test]
fn test_file_level_booking_method_applied() {
    // The file has `option "booking_method" "FIFO"` and a sell posting
    // that matches 2 lots. Under STRICT this would be an ambiguous lot
    // match error. Under FIFO the oldest lot is selected.
    let path = fixtures_path("booking_method_fifo.beancount");
    let options = LoadOptions::default(); // default = Strict, but file says FIFO

    let ledger = load(&path, &options).expect("should load and process");

    // No booking errors — FIFO resolves the ambiguity.
    let booking_errors: Vec<_> = ledger.errors.iter().filter(|e| e.code == "BOOK").collect();
    assert!(
        booking_errors.is_empty(),
        "expected no BOOK errors under file-level FIFO, got: {booking_errors:?}"
    );
}

#[test]
fn test_api_booking_method_used_when_file_does_not_set_option() {
    // simple.beancount does NOT set `option "booking_method"`. The
    // API-level LoadOptions.booking_method should be used as-is.
    let path = fixtures_path("simple.beancount");
    let options = LoadOptions {
        booking_method: rustledger_core::BookingMethod::Fifo,
        ..Default::default()
    };

    let ledger = load(&path, &options).expect("should load and process");

    // No errors — simple.beancount has no cost-based transactions, so
    // the booking method doesn't matter. But the important thing is
    // that the API-level override is accepted (not overridden by the
    // file's default "STRICT").
    assert!(
        ledger.errors.is_empty(),
        "unexpected errors: {:?}",
        ledger.errors
    );
}

// ============================================================================
// Document Discovery Tests (Issue #466)
// ============================================================================

#[test]
fn test_document_discovery_from_option() {
    // Test that documents are auto-discovered from `option "documents"` directories.
    // See: https://github.com/rustledger/rustledger/issues/466
    let path = fixtures_path("doc_discovery.beancount");
    let options = LoadOptions::default();

    let ledger = load(&path, &options).expect("should load with document discovery");

    // Count document directives
    let documents: Vec<_> = ledger
        .directives
        .iter()
        .filter_map(|d| {
            if let rustledger_core::Directive::Document(doc) = &d.value {
                Some(doc)
            } else {
                None
            }
        })
        .collect();

    // Should have discovered 3 documents:
    // - Assets/Bank/Checking/2024-01-15.statement.pdf
    // - Assets/Bank/Checking/2024-02-15.statement.pdf
    // - Expenses/Food/2024-03-10.receipt.jpg
    assert_eq!(
        documents.len(),
        3,
        "expected 3 discovered documents, got: {documents:?}"
    );

    // Check accounts are correctly constructed from directory paths
    let accounts: Vec<&str> = documents.iter().map(|d| d.account.as_ref()).collect();
    assert!(
        accounts.contains(&"Assets:Bank:Checking"),
        "should have Assets:Bank:Checking document"
    );
    assert!(
        accounts.contains(&"Expenses:Food"),
        "should have Expenses:Food document"
    );

    // Check dates are correctly parsed from filenames
    let dates: Vec<_> = documents.iter().map(|d| d.date.to_string()).collect();
    assert!(
        dates.contains(&"2024-01-15".to_string()),
        "should have document dated 2024-01-15"
    );
    assert!(
        dates.contains(&"2024-02-15".to_string()),
        "should have document dated 2024-02-15"
    );
    assert!(
        dates.contains(&"2024-03-10".to_string()),
        "should have document dated 2024-03-10"
    );
}

#[test]
fn test_document_discovery_no_option() {
    // Test that document discovery doesn't happen when option "documents" is not set
    let path = fixtures_path("simple.beancount");
    let options = LoadOptions::default();

    // simple.beancount doesn't have option "documents", so no discovery should happen
    let ledger = load(&path, &options).expect("should load");

    // Count document directives (should be 0)
    let doc_count = ledger
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Document(_)))
        .count();

    assert_eq!(doc_count, 0, "should have no documents without option");
}

#[test]
fn test_document_discovery_no_duplicates() {
    // Test that document discovery doesn't create duplicates if a document directive
    // already exists for one of the discoverable files.
    //
    // The `doc_discovery_with_explicit.beancount` fixture:
    //   * Enables document discovery for `documents/` directory
    //   * Contains an explicit `document` directive for one file that would also be discovered
    //
    // If de-duplication is working correctly, the explicitly referenced file must not
    // be added again by discovery.
    let path = fixtures_path("doc_discovery_with_explicit.beancount");
    let options = LoadOptions::default();

    let ledger = load(&path, &options).expect("should load");

    let doc_count = ledger
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Document(_)))
        .count();

    // The fixture has 3 document files in the directory:
    //   - documents/Assets/Bank/Checking/2024-01-15.statement.pdf
    //   - documents/Assets/Bank/Checking/2024-02-15.statement.pdf
    //   - documents/Expenses/Food/2024-03-10.receipt.jpg
    // One of them (2024-01-15.statement.pdf) is explicitly declared in the file.
    // If duplicates were being created, we'd see 4 documents instead of 3.
    assert_eq!(
        doc_count, 3,
        "document discovery should not create duplicate Document directives"
    );
}

// ============================================================================
// Plugin execution through process::process() pipeline (Issue #788)
// ============================================================================

/// Test that plugins declared in a beancount file execute through the
/// process.rs pipeline and their output is visible in the Ledger.
///
/// `auto_accounts` should synthesize Open directives for all implicitly-used
/// accounts. Without the plugin, these accounts would have no opens.
#[test]
fn test_plugin_execution_auto_accounts() {
    use rustledger_loader::{LoadOptions, load};

    let path = fixtures_path("auto_accounts_plugin.beancount");
    let ledger = load(&path, &LoadOptions::default()).expect("should load file with plugin");

    // The file has NO explicit open directives — auto_accounts should
    // generate them for Assets:Bank:Checking, Income:Salary, Expenses:Food.
    let opens: Vec<_> = ledger
        .directives
        .iter()
        .filter_map(|d| {
            if let rustledger_core::Directive::Open(o) = &d.value {
                Some(o.account.to_string())
            } else {
                None
            }
        })
        .collect();

    assert!(
        opens.iter().any(|a| a == "Assets:Bank:Checking"),
        "auto_accounts should generate Open for Assets:Bank:Checking. Opens: {opens:?}"
    );
    assert!(
        opens.iter().any(|a| a == "Income:Salary"),
        "auto_accounts should generate Open for Income:Salary. Opens: {opens:?}"
    );
    assert!(
        opens.iter().any(|a| a == "Expenses:Food"),
        "auto_accounts should generate Open for Expenses:Food. Opens: {opens:?}"
    );

    // Validation should pass (no E1001 errors) since opens are auto-generated.
    let validation_errors: Vec<_> = ledger.errors.iter().filter(|e| e.code == "E1001").collect();
    assert!(
        validation_errors.is_empty(),
        "auto_accounts should prevent E1001 (account not opened). Got: {validation_errors:?}"
    );
}

/// Test the interaction between booking and plugins: booking runs first,
/// then plugins see booked transactions.
///
/// With FIFO booking + `auto_accounts`: the sell transaction should match
/// lot 1 (FIFO) without ambiguity, and `auto_accounts` should generate
/// opens for the implicitly-used accounts.
#[test]
fn test_plugin_and_booking_interaction() {
    use rustledger_loader::{LoadOptions, load};

    let path = fixtures_path("fifo_with_plugin.beancount");
    let ledger = load(&path, &LoadOptions::default()).expect("should load FIFO + plugin file");

    // auto_accounts should have generated opens
    let opens: Vec<_> = ledger
        .directives
        .iter()
        .filter_map(|d| {
            if let rustledger_core::Directive::Open(o) = &d.value {
                Some(o.account.to_string())
            } else {
                None
            }
        })
        .collect();

    assert!(
        opens.iter().any(|a| a == "Assets:Stock"),
        "auto_accounts should generate Open for Assets:Stock. Opens: {opens:?}"
    );
    assert!(
        opens.iter().any(|a| a == "Assets:Cash"),
        "auto_accounts should generate Open for Assets:Cash. Opens: {opens:?}"
    );

    // FIFO booking should have resolved the sell without ambiguity error.
    // The sell is -5 CORP {} which should match lot 1 (cost 1 USD) under FIFO.
    let booking_errors: Vec<_> = ledger
        .errors
        .iter()
        .filter(|e| e.message.contains("ambiguous"))
        .collect();
    assert!(
        booking_errors.is_empty(),
        "FIFO booking should resolve sell without ambiguity. Errors: {booking_errors:?}"
    );

    // No validation errors expected (auto_accounts generates opens, FIFO resolves lots)
    assert!(
        ledger.errors.is_empty(),
        "No errors expected with FIFO + auto_accounts. Got: {:?}",
        ledger.errors
    );
}

/// Test that unknown plugin names are gracefully skipped without crashing.
///
/// The loader's `run_plugins()` only executes native plugins. Non-native
/// plugin names (Python modules, unknown names) are silently skipped.
/// This test verifies the pipeline doesn't panic or error on unknown plugins.
#[test]
fn test_unknown_plugin_skipped_gracefully() {
    use rustledger_loader::{LoadOptions, load};

    let path = fixtures_path("unknown_plugin.beancount");
    let ledger =
        load(&path, &LoadOptions::default()).expect("should load file with unknown plugin");

    // The unknown plugin "some.unknown.plugin.module" should NOT crash
    // the pipeline — it should be silently skipped (only native plugins
    // are executed). Verify the ledger loaded successfully.
    //
    // Note: the current run_plugins() implementation silently skips
    // non-native plugins. If/when Python plugin support is added to the
    // loader pipeline, this test should be updated to check for an error
    // like E8001 (plugin not found).
    assert!(
        !ledger.directives.is_empty(),
        "Ledger should still have directives even with unknown plugin"
    );
}

/// Test that plugin-synthesized directives are visible in the `Ledger`.
/// This verifies that the directive conversion round-trip (`Directive` →
/// `DirectiveWrapper` → `Directive`) preserves the synthesized data.
#[test]
fn test_plugin_output_directives_visible_in_ledger() {
    use rustledger_loader::{LoadOptions, load};

    let path = fixtures_path("auto_accounts_plugin.beancount");
    let ledger = load(&path, &LoadOptions::default()).expect("should load");

    // Count directives: the file has 2 transactions. auto_accounts should
    // add 3 open directives (Assets:Bank:Checking, Income:Salary, Expenses:Food).
    // Total should be at least 5.
    let total = ledger.directives.len();
    let txn_count = ledger
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Transaction(_)))
        .count();
    let open_count = ledger
        .directives
        .iter()
        .filter(|d| matches!(d.value, rustledger_core::Directive::Open(_)))
        .count();

    assert_eq!(txn_count, 2, "Should have 2 transactions");
    assert!(
        open_count >= 3,
        "auto_accounts should synthesize at least 3 Open directives. Got {open_count}"
    );
    assert!(
        total >= 5,
        "Total directives should be at least 5 (2 txn + 3 opens). Got {total}"
    );
}