arf-console 0.3.1

A cross-platform R console written in Rust
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
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
//! Configuration management following XDG Base Directory specification.

mod colors;
mod completion;
mod editor;
mod experimental;
mod history;
mod mode;
pub(crate) mod prompt;
mod r;
mod startup;

pub use colors::{ColorsConfig, MetaColorConfig, RColorConfig, StatusColorConfig, ViColorConfig};
pub use completion::CompletionConfig;
pub use editor::{AutoSuggestions, EditorConfig, EditorMode};
pub use experimental::{
    ExperimentalConfig, HistoryForgetConfig, PromptDurationConfig, SpinnerConfig,
};
pub use history::HistoryConfig;
pub use mode::ModeConfig;
#[allow(unused_imports)]
// StatusSymbol is part of public API for programmatic StatusConfig construction
pub use prompt::{
    Indicators, ModeIndicatorPosition, PromptConfig, StatusConfig, StatusSymbol, ViConfig,
};
pub use r::RConfig;
pub use startup::{RSource, RSourceMode, RSourceStatus, StartupConfig};

use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;

/// Status of config file loading, for display in `:info`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfigStatus {
    /// Config loaded successfully (or no config file exists).
    Ok,
    /// Config file could not be read (e.g., permission denied).
    ReadError,
    /// Config file has TOML syntax or schema errors.
    ParseError,
}

/// Error type for configuration loading failures.
#[derive(Debug)]
pub enum ConfigLoadError {
    /// Failed to read the config file from disk.
    Read {
        source: std::io::Error,
        path: PathBuf,
    },
    /// Failed to parse the TOML content.
    Parse {
        source: toml::de::Error,
        path: PathBuf,
    },
}

impl std::fmt::Display for ConfigLoadError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConfigLoadError::Read { source, path } => {
                write!(
                    f,
                    "Failed to read config file {}: {}",
                    path.display(),
                    source
                )
            }
            ConfigLoadError::Parse { source, path } => {
                write!(
                    f,
                    "Failed to parse config file {}: {}",
                    path.display(),
                    source
                )
            }
        }
    }
}

impl std::error::Error for ConfigLoadError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            ConfigLoadError::Read { source, .. } => Some(source),
            ConfigLoadError::Parse { source, .. } => Some(source),
        }
    }
}

/// Application name for XDG directories.
const APP_NAME: &str = "arf";

/// Main configuration structure.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
#[derive(Default)]
pub struct Config {
    pub startup: StartupConfig,
    pub editor: EditorConfig,
    pub prompt: PromptConfig,
    pub completion: CompletionConfig,
    pub history: HistoryConfig,
    /// R runtime configuration.
    pub r: RConfig,
    /// Mode-specific static configuration (not changeable at runtime).
    /// For initial mode state (enabled/disabled), see `startup.mode`.
    pub mode: ModeConfig,
    pub colors: ColorsConfig,
    #[serde(default)]
    pub experimental: ExperimentalConfig,
}

/// Get the XDG config directory for this application.
pub fn config_dir() -> Option<PathBuf> {
    dirs::config_dir().map(|p| p.join(APP_NAME))
}

/// Get the XDG data directory for this application.
pub fn data_dir() -> Option<PathBuf> {
    dirs::data_dir().map(|p| p.join(APP_NAME))
}

/// Get the XDG cache directory for this application.
pub fn cache_dir() -> Option<PathBuf> {
    dirs::cache_dir().map(|p| p.join(APP_NAME))
}

/// Get the path to the config file.
pub fn config_file_path() -> Option<PathBuf> {
    config_dir().map(|p| p.join("arf.toml"))
}

/// Get the history directory path.
///
/// History files are stored in a subdirectory: `~/.local/share/arf/history/`
/// - R mode: `history/r.db`
/// - Shell mode: `history/shell.db`
pub fn history_dir() -> Option<PathBuf> {
    data_dir().map(|p| p.join("history"))
}

/// Mask home directory in path with `~` for privacy.
///
/// Replaces the user's home directory prefix with `~` to avoid displaying
/// usernames in paths. Works on both Unix and Windows (PowerShell supports `~`).
/// Uses platform-native path separators.
pub fn mask_home_path(path: &std::path::Path) -> String {
    if let Some(home) = dirs::home_dir()
        && let Ok(stripped) = path.strip_prefix(&home)
    {
        return format!("~{}{}", std::path::MAIN_SEPARATOR, stripped.display());
    }
    path.display().to_string()
}

/// Load configuration from the default XDG config file.
///
/// Returns `Ok(Config::default())` if no config file exists.
/// Returns `Err` if the file exists but cannot be read or parsed.
pub fn load_config() -> Result<Config, ConfigLoadError> {
    let Some(config_path) = config_file_path() else {
        return Ok(Config::default());
    };

    if !config_path.exists() {
        return Ok(Config::default());
    }

    load_config_from_path(&config_path)
}

/// Load configuration from a specific path.
///
/// Returns `Ok(Config::default())` if the file does not exist.
/// Returns `Err` if the file exists but cannot be read or parsed.
pub fn load_config_from_path(path: &std::path::Path) -> Result<Config, ConfigLoadError> {
    if !path.exists() {
        log::warn!("Config file not found: {:?}", path);
        return Ok(Config::default());
    }

    let content = fs::read_to_string(path).map_err(|e| ConfigLoadError::Read {
        source: e,
        path: path.to_path_buf(),
    })?;

    toml::from_str(&content).map_err(|e| ConfigLoadError::Parse {
        source: e,
        path: path.to_path_buf(),
    })
}

/// Generate default configuration as a TOML string with comments.
pub fn generate_default_config() -> String {
    let config = Config::default();
    let toml_content = toml::to_string_pretty(&config).expect("Failed to serialize default config");

    // Add Tombi Schema Document Directive on the first line
    // See: https://tombi-toml.github.io/tombi/docs/comment-directive/schema-document-directive/
    let header = r#"#:schema https://raw.githubusercontent.com/eitsupi/arf/main/artifacts/arf.schema.json
# arf configuration file
#
# Documentation: https://github.com/eitsupi/arf

"#;

    format!("{}{}", header, toml_content)
}

/// Initialize a default configuration file at the XDG config location.
///
/// Returns the path where the config was written.
pub fn init_config(force: bool) -> anyhow::Result<std::path::PathBuf> {
    let config_path = config_file_path()
        .ok_or_else(|| anyhow::anyhow!("Could not determine config directory"))?;

    // Check if file already exists
    if config_path.exists() && !force {
        anyhow::bail!(
            "Configuration file already exists at: {}\nUse --force to overwrite.",
            config_path.display()
        );
    }

    // Ensure parent directory exists
    if let Some(parent) = config_path.parent() {
        fs::create_dir_all(parent)?;
    }

    // Generate and write config
    let content = generate_default_config();
    fs::write(&config_path, content)?;

    Ok(config_path)
}

/// Ensure all XDG directories exist.
pub fn ensure_directories() -> anyhow::Result<()> {
    if let Some(dir) = config_dir() {
        fs::create_dir_all(&dir)?;
    }
    if let Some(dir) = data_dir() {
        fs::create_dir_all(&dir)?;
    }
    if let Some(dir) = cache_dir() {
        fs::create_dir_all(&dir)?;
    }
    Ok(())
}

/// Schema generation for configuration.
#[allow(dead_code)]
pub mod schema {
    use super::Config;
    use schemars::schema_for;
    use std::path::PathBuf;

    /// Root directory for artifacts (relative to crate root).
    const ARTIFACTS_DIR: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/../../artifacts");

    /// Generate JSON schema for the configuration.
    pub fn generate_schema() -> String {
        let schema = schema_for!(Config);
        serde_json::to_string_pretty(&schema).expect("Failed to serialize schema")
    }

    /// Get the path to the schema file.
    pub fn schema_path() -> PathBuf {
        PathBuf::from(ARTIFACTS_DIR).join("arf.schema.json")
    }

    /// Write the schema to the artifacts directory.
    pub fn write_schema() -> std::io::Result<()> {
        let schema = generate_schema();
        let path = schema_path();
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }
        std::fs::write(path, schema)
    }
}

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

    #[test]
    fn test_default_config() {
        let config = Config::default();
        assert!(
            config.editor.auto_match,
            "auto_match should be enabled by default"
        );
        assert_eq!(config.editor.mode, EditorMode::Emacs);
        assert!(matches!(
            config.startup.r_source,
            RSource::Mode(RSourceMode::Auto)
        ));
        assert!(config.startup.show_banner);
    }

    #[test]
    fn test_default_r_auto_width() {
        let config = Config::default();
        assert!(
            config.r.auto_width,
            "auto_width should be enabled by default"
        );
    }

    #[test]
    fn test_parse_r_auto_width_disabled() {
        let toml_str = r#"
[r]
auto_width = false
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(!config.r.auto_width);
    }

    #[test]
    fn test_parse_r_auto_width_default_when_omitted() {
        let toml_str = r#"
[editor]
mode = "vi"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(
            config.r.auto_width,
            "auto_width should default to true when [r] section is omitted"
        );
    }

    #[test]
    fn test_parse_config_with_auto_match_enabled() {
        let toml_str = r#"
[editor]
auto_match = true
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(config.editor.auto_match);
    }

    #[test]
    fn test_parse_config_with_auto_match_disabled() {
        let toml_str = r#"
[editor]
auto_match = false
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(!config.editor.auto_match);
    }

    #[test]
    fn test_parse_startup_section_config() {
        let toml_str = r##"
[startup]
r_source = "rig"
show_banner = false

[startup.mode]
reprex = true
autoformat = true

[editor]
mode = "vi"
auto_match = false

[prompt]
format = "R> "
continuation = ".. "

[completion]
enabled = true
timeout_ms = 100

[mode.reprex]
comment = "# "
"##;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(matches!(
            config.startup.r_source,
            RSource::Mode(RSourceMode::Rig)
        ));
        assert!(!config.startup.show_banner);
        assert_eq!(config.editor.mode, EditorMode::Vi);
        assert!(!config.editor.auto_match);
        assert_eq!(config.prompt.format, "R> ");
        assert!(config.startup.mode.reprex);
        assert!(config.startup.mode.autoformat);
        assert_eq!(config.mode.reprex.comment, "# ");
    }

    #[test]
    fn test_parse_new_key_map_config() {
        let toml_str = r#"
[editor]
mode = "emacs"

[editor.key_map]
"alt-hyphen" = " <- "
"ctrl-shift-m" = " |> "
"alt-=" = " == "
"#;
        let config: Config = toml::from_str(toml_str).unwrap();

        let alt_hyphen: KeyCombination = "alt-hyphen".parse().unwrap();
        let ctrl_shift_m: KeyCombination = "ctrl-shift-m".parse().unwrap();
        let alt_eq: KeyCombination = "alt-=".parse().unwrap();

        assert_eq!(
            config.editor.key_map.get(&alt_hyphen),
            Some(&" <- ".to_string())
        );
        assert_eq!(
            config.editor.key_map.get(&ctrl_shift_m),
            Some(&" |> ".to_string())
        );
        assert_eq!(
            config.editor.key_map.get(&alt_eq),
            Some(&" == ".to_string())
        );
    }

    #[test]
    fn test_default_key_map() {
        let config = Config::default();

        let alt_hyphen: KeyCombination = "alt-hyphen".parse().unwrap();
        let alt_p: KeyCombination = "alt-p".parse().unwrap();

        assert_eq!(
            config.editor.key_map.get(&alt_hyphen),
            Some(&" <- ".to_string())
        );
        assert_eq!(config.editor.key_map.get(&alt_p), Some(&" |> ".to_string()));
    }

    #[test]
    fn test_default_mode_indicator() {
        let config = Config::default();
        assert_eq!(config.prompt.mode_indicator, ModeIndicatorPosition::Prefix);
        assert_eq!(config.prompt.indicators.reprex, "[reprex] ");
        assert_eq!(config.prompt.indicators.autoformat, "[format] ");
    }

    #[test]
    fn test_parse_mode_indicator_suffix() {
        let toml_str = r#"
[prompt]
mode_indicator = "suffix"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.prompt.mode_indicator, ModeIndicatorPosition::Suffix);
    }

    #[test]
    fn test_parse_mode_indicator_none() {
        let toml_str = r#"
[prompt]
mode_indicator = "none"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.prompt.mode_indicator, ModeIndicatorPosition::None);
    }

    #[test]
    fn test_parse_history_disabled() {
        let toml_str = r#"
[history]
disabled = true
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(config.history.disabled);
    }

    #[test]
    fn test_default_history_forget_config() {
        let config = Config::default();
        assert!(!config.experimental.history_forget.enabled);
        assert_eq!(config.experimental.history_forget.delay, 2);
        assert!(!config.experimental.history_forget.on_exit_only);
    }

    #[test]
    fn test_parse_history_forget_config() {
        let toml_str = r#"
[experimental.history_forget]
enabled = true
delay = 5
on_exit_only = true
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(config.experimental.history_forget.enabled);
        assert_eq!(config.experimental.history_forget.delay, 5);
        assert!(config.experimental.history_forget.on_exit_only);
    }

    #[test]
    fn test_auto_suggestions_default_is_all() {
        let config = Config::default();
        assert_eq!(config.editor.auto_suggestions, AutoSuggestions::All);
    }

    #[test]
    fn test_parse_auto_suggestions_none_string() {
        let toml_str = r#"
[editor]
auto_suggestions = "none"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.editor.auto_suggestions, AutoSuggestions::None);
    }

    #[test]
    fn test_parse_auto_suggestions_all_string() {
        let toml_str = r#"
[editor]
auto_suggestions = "all"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.editor.auto_suggestions, AutoSuggestions::All);
    }

    #[test]
    fn test_parse_auto_suggestions_cwd_string() {
        let toml_str = r#"
[editor]
auto_suggestions = "cwd"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.editor.auto_suggestions, AutoSuggestions::Cwd);
    }

    #[test]
    fn test_parse_auto_suggestions_bool_true() {
        let toml_str = r#"
[editor]
auto_suggestions = true
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.editor.auto_suggestions, AutoSuggestions::All);
    }

    #[test]
    fn test_parse_auto_suggestions_bool_false() {
        let toml_str = r#"
[editor]
auto_suggestions = false
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert_eq!(config.editor.auto_suggestions, AutoSuggestions::None);
    }

    #[test]
    fn test_parse_auto_suggestions_invalid_string() {
        let toml_str = r#"
[editor]
auto_suggestions = "invalid"
"#;
        let result: Result<Config, _> = toml::from_str(toml_str);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("unknown variant"),
            "Error should mention unknown variant: {}",
            err
        );
    }

    #[test]
    fn test_parse_auto_suggestions_string_true_rejected() {
        // String "true" should be rejected (use boolean true instead)
        let toml_str = r#"
[editor]
auto_suggestions = "true"
"#;
        let result: Result<Config, _> = toml::from_str(toml_str);
        assert!(result.is_err(), "String 'true' should be rejected");
    }

    #[test]
    fn test_parse_auto_suggestions_string_false_rejected() {
        // String "false" should be rejected (use boolean false instead)
        let toml_str = r#"
[editor]
auto_suggestions = "false"
"#;
        let result: Result<Config, _> = toml::from_str(toml_str);
        assert!(result.is_err(), "String 'false' should be rejected");
    }

    #[test]
    fn test_parse_r_source_auto() {
        let toml_str = r#"
[startup]
r_source = "auto"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(matches!(
            config.startup.r_source,
            RSource::Mode(RSourceMode::Auto)
        ));
    }

    #[test]
    fn test_parse_r_source_rig() {
        let toml_str = r#"
[startup]
r_source = "rig"
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(matches!(
            config.startup.r_source,
            RSource::Mode(RSourceMode::Rig)
        ));
    }

    #[test]
    fn test_parse_r_source_path() {
        let toml_str = r#"
[startup]
r_source = { path = "/opt/R/4.5.2" }
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        match &config.startup.r_source {
            RSource::Path { path } => {
                assert_eq!(path, &PathBuf::from("/opt/R/4.5.2"));
            }
            _ => panic!("Expected RSource::Path"),
        }
    }

    #[test]
    fn test_parse_r_source_default_when_omitted() {
        let toml_str = r#"
[startup]
show_banner = false
"#;
        let config: Config = toml::from_str(toml_str).unwrap();
        assert!(matches!(
            config.startup.r_source,
            RSource::Mode(RSourceMode::Auto)
        ));
    }

    #[test]
    fn test_generate_default_config() {
        let config_str = generate_default_config();

        // Should have Tombi Schema Document Directive on first line
        assert!(config_str.starts_with(
            "#:schema https://raw.githubusercontent.com/eitsupi/arf/main/artifacts/arf.schema.json"
        ));

        // Should be valid TOML
        let parsed: Config =
            toml::from_str(&config_str).expect("Generated config should be valid TOML");

        // Should have default values
        assert!(matches!(
            parsed.startup.r_source,
            RSource::Mode(RSourceMode::Auto)
        ));
        assert!(parsed.startup.show_banner);
        assert_eq!(parsed.editor.mode, EditorMode::Emacs);
    }

    #[test]
    fn test_generate_default_config_has_new_structure() {
        let config_str = generate_default_config();

        // Should have [startup] section with r_source and show_banner
        assert!(
            config_str.contains("[startup]"),
            "Should have [startup] section"
        );
        assert!(
            config_str.contains("r_source = "),
            "Should have r_source in startup section"
        );
        assert!(
            config_str.contains("show_banner = "),
            "Should have show_banner in startup section"
        );

        // Should have [startup.mode] section
        assert!(
            config_str.contains("[startup.mode]"),
            "Should have [startup.mode] section"
        );

        // Should have [mode.reprex] section
        assert!(
            config_str.contains("[mode.reprex]"),
            "Should have [mode.reprex] section"
        );

        // Should NOT have old sections
        assert!(
            !config_str.contains("[general]"),
            "Should NOT have [general] section"
        );
        assert!(
            !config_str.contains("[shortcuts]"),
            "Should NOT have [shortcuts] section"
        );
        assert!(
            !config_str.contains("[formatter]"),
            "Should NOT have [formatter] section"
        );

        // Should have other sections
        assert!(
            config_str.contains("[editor]"),
            "Should have [editor] section"
        );
    }

    mod schema_tests {
        use crate::config::schema::{generate_schema, schema_path, write_schema};

        #[test]
        fn test_schema_snapshot() {
            let schema = generate_schema();
            insta::assert_snapshot!("config_schema", schema);
        }

        /// Snapshot test for the default configuration file.
        /// This ensures we notice when the config structure changes.
        #[test]
        fn test_default_config_snapshot() {
            let config = crate::config::generate_default_config();
            insta::assert_snapshot!("default_config", config);
        }

        #[test]
        fn test_schema_matches_artifact() {
            let schema = generate_schema();
            let path = schema_path();

            // If the artifact file exists, verify it matches the generated schema
            if path.exists() {
                let contents = std::fs::read_to_string(&path).expect("Failed to read schema file");
                assert_eq!(
                    schema, contents,
                    "Schema file is out of date. Run the generate_schema_file test to update."
                );
            }
        }

        /// Generate the schema file in artifacts/.
        /// Run with: cargo test -p arf-console generate_schema_file -- --ignored
        #[test]
        #[ignore]
        fn generate_schema_file() {
            write_schema().expect("Failed to write schema file");
            println!("Schema written to {:?}", schema_path());
        }

        #[test]
        fn test_schema_is_valid_json() {
            let schema = generate_schema();
            let parsed: serde_json::Value =
                serde_json::from_str(&schema).expect("Schema should be valid JSON");

            // Verify it has expected top-level fields
            assert!(
                parsed.get("$schema").is_some(),
                "Schema should have $schema field"
            );
            assert!(
                parsed.get("title").is_some(),
                "Schema should have title field"
            );
            assert!(
                parsed.get("type").is_some(),
                "Schema should have type field"
            );
            assert!(
                parsed.get("properties").is_some(),
                "Schema should have properties field"
            );
        }

        #[test]
        fn test_schema_has_new_structure() {
            let schema = generate_schema();
            let parsed: serde_json::Value =
                serde_json::from_str(&schema).expect("Schema should be valid JSON");

            let properties = parsed
                .get("properties")
                .expect("Schema should have properties");

            // Should have startup section (contains r_source, show_banner, mode)
            assert!(
                properties.get("startup").is_some(),
                "Schema should have startup section"
            );

            // Should have mode section (contains reprex static config)
            assert!(
                properties.get("mode").is_some(),
                "Schema should have mode section"
            );

            // Should have other sections
            assert!(
                properties.get("editor").is_some(),
                "Schema should have editor section"
            );
            assert!(
                properties.get("prompt").is_some(),
                "Schema should have prompt section"
            );
            assert!(
                properties.get("completion").is_some(),
                "Schema should have completion section"
            );
            assert!(
                properties.get("experimental").is_some(),
                "Schema should have experimental section"
            );

            // Should NOT have legacy sections or top-level fields that moved
            assert!(
                properties.get("general").is_none(),
                "Schema should NOT have general section"
            );
            assert!(
                properties.get("reprex").is_none(),
                "reprex should be in mode section, not top-level"
            );
            assert!(
                properties.get("r_version").is_none(),
                "r_version should be in startup section, not top-level"
            );
            assert!(
                properties.get("show_banner").is_none(),
                "show_banner should be in startup section, not top-level"
            );
            assert!(
                properties.get("shortcuts").is_none(),
                "Schema should NOT have shortcuts section"
            );
            assert!(
                properties.get("formatter").is_none(),
                "Schema should NOT have formatter section"
            );
        }
    }

    #[test]
    fn test_mask_home_path_with_home_prefix() {
        if let Some(home) = dirs::home_dir() {
            let test_path = home.join("test").join("file.txt");
            let masked = mask_home_path(&test_path);
            assert!(
                masked.starts_with("~"),
                "Path should start with ~: {}",
                masked
            );
            assert!(
                masked.contains("test"),
                "Path should contain 'test': {}",
                masked
            );
            assert!(
                masked.contains("file.txt"),
                "Path should contain 'file.txt': {}",
                masked
            );
        }
    }

    #[test]
    fn test_mask_home_path_without_home_prefix() {
        let test_path = PathBuf::from("/opt/R/4.5.0");
        let expected = test_path.display().to_string();
        let masked = mask_home_path(&test_path);
        assert_eq!(
            masked, expected,
            "Path without home prefix should be unchanged"
        );
    }

    #[test]
    fn test_mask_home_path_exact_home() {
        if let Some(home) = dirs::home_dir() {
            let masked = mask_home_path(&home);
            // Should be just "~/" or "~\" depending on platform
            assert!(
                masked.starts_with("~"),
                "Home path should start with ~: {}",
                masked
            );
        }
    }

    #[test]
    fn test_load_config_from_path_parse_error() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("bad.toml");
        std::fs::write(&path, "[editor\nauto_match = true").unwrap();

        let result = load_config_from_path(&path);
        assert!(result.is_err(), "Invalid TOML should return Err");

        let err = result.unwrap_err();
        assert!(
            matches!(err, ConfigLoadError::Parse { .. }),
            "Should be a ParseError: {:?}",
            err
        );
        let msg = err.to_string();
        assert!(
            msg.contains("bad.toml"),
            "Error should mention the file path: {}",
            msg
        );
    }

    #[test]
    fn test_load_config_from_path_valid() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("good.toml");
        std::fs::write(
            &path,
            r#"
[editor]
auto_match = false
"#,
        )
        .unwrap();

        let result = load_config_from_path(&path);
        assert!(result.is_ok(), "Valid TOML should return Ok");
        let config = result.unwrap();
        assert!(!config.editor.auto_match);
    }

    #[test]
    fn test_load_config_from_path_not_found() {
        let path = PathBuf::from("/nonexistent/config.toml");
        let result = load_config_from_path(&path);
        assert!(result.is_ok(), "Missing file should return Ok(default)");
        let config = result.unwrap();
        assert!(config.editor.auto_match, "Should be default config");
    }

    #[test]
    fn test_config_load_error_display() {
        let err = ConfigLoadError::Parse {
            source: toml::from_str::<Config>("[bad\n").unwrap_err(),
            path: PathBuf::from("/home/user/.config/arf/arf.toml"),
        };
        let msg = err.to_string();
        assert!(msg.contains("parse"), "Should mention parse: {}", msg);
        assert!(msg.contains("arf.toml"), "Should mention path: {}", msg);
    }

    #[cfg(unix)]
    #[test]
    fn test_load_config_from_path_read_error() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("unreadable.toml");
        std::fs::write(&path, "[editor]\nauto_match = true").unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o000)).unwrap();

        let result = load_config_from_path(&path);
        assert!(result.is_err(), "Unreadable file should return Err");

        let err = result.unwrap_err();
        assert!(
            matches!(err, ConfigLoadError::Read { .. }),
            "Should be a ReadError: {:?}",
            err
        );

        // Restore permissions so tempdir cleanup succeeds
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();
    }
}