sbom-tools 0.1.19

Semantic SBOM diff and analysis tool
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
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
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
//! Configuration types for sbom-tools operations.
//!
//! Provides structured configuration for diff, view, and multi-comparison operations.

use crate::matching::FuzzyMatchConfig;
use crate::reports::{ReportFormat, ReportType};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

// ============================================================================
// Unified Application Configuration
// ============================================================================

/// Unified application configuration that can be loaded from CLI args or config files.
///
/// This is the top-level configuration struct that aggregates all configuration
/// options. It can be constructed from CLI arguments, config files, or both
/// (with CLI overriding file settings).
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct AppConfig {
    /// Matching configuration (thresholds, presets)
    pub matching: MatchingConfig,
    /// Output configuration (format, file, colors)
    pub output: OutputConfig,
    /// Filtering options
    pub filtering: FilterConfig,
    /// Behavior flags
    pub behavior: BehaviorConfig,
    /// Graph-aware diffing configuration
    pub graph_diff: GraphAwareDiffConfig,
    /// Custom matching rules configuration
    pub rules: MatchingRulesPathConfig,
    /// Ecosystem-specific rules configuration
    pub ecosystem_rules: EcosystemRulesConfig,
    /// TUI-specific configuration
    pub tui: TuiConfig,
    /// Enrichment configuration (OSV, etc.)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub enrichment: Option<EnrichmentConfig>,
}

impl AppConfig {
    /// Create a new `AppConfig` with default values.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create an `AppConfig` builder.
    pub fn builder() -> AppConfigBuilder {
        AppConfigBuilder::default()
    }
}

// ============================================================================
// Builder for AppConfig
// ============================================================================

/// Builder for constructing `AppConfig` with fluent API.
#[derive(Debug, Default)]
#[must_use]
pub struct AppConfigBuilder {
    config: AppConfig,
}

impl AppConfigBuilder {
    /// Set the fuzzy matching preset.
    pub fn fuzzy_preset(mut self, preset: FuzzyPreset) -> Self {
        self.config.matching.fuzzy_preset = preset;
        self
    }

    /// Set the matching threshold.
    pub const fn matching_threshold(mut self, threshold: f64) -> Self {
        self.config.matching.threshold = Some(threshold);
        self
    }

    /// Set the output format.
    pub const fn output_format(mut self, format: ReportFormat) -> Self {
        self.config.output.format = format;
        self
    }

    /// Set the output file.
    pub fn output_file(mut self, file: Option<PathBuf>) -> Self {
        self.config.output.file = file;
        self
    }

    /// Disable colored output.
    pub const fn no_color(mut self, no_color: bool) -> Self {
        self.config.output.no_color = no_color;
        self
    }

    /// Include unchanged components.
    pub const fn include_unchanged(mut self, include: bool) -> Self {
        self.config.matching.include_unchanged = include;
        self
    }

    /// Enable fail-on-vulnerability mode.
    pub const fn fail_on_vuln(mut self, fail: bool) -> Self {
        self.config.behavior.fail_on_vuln = fail;
        self
    }

    /// Enable fail-on-change mode.
    pub const fn fail_on_change(mut self, fail: bool) -> Self {
        self.config.behavior.fail_on_change = fail;
        self
    }

    /// Enable quiet mode.
    pub const fn quiet(mut self, quiet: bool) -> Self {
        self.config.behavior.quiet = quiet;
        self
    }

    /// Enable graph-aware diffing.
    pub fn graph_diff(mut self, enabled: bool) -> Self {
        self.config.graph_diff = if enabled {
            GraphAwareDiffConfig::enabled()
        } else {
            GraphAwareDiffConfig::default()
        };
        self
    }

    /// Set matching rules file.
    pub fn matching_rules_file(mut self, file: Option<PathBuf>) -> Self {
        self.config.rules.rules_file = file;
        self
    }

    /// Set ecosystem rules file.
    pub fn ecosystem_rules_file(mut self, file: Option<PathBuf>) -> Self {
        self.config.ecosystem_rules.config_file = file;
        self
    }

    /// Enable enrichment.
    pub fn enrichment(mut self, config: EnrichmentConfig) -> Self {
        self.config.enrichment = Some(config);
        self
    }

    /// Build the `AppConfig`.
    #[must_use]
    pub fn build(self) -> AppConfig {
        self.config
    }
}

// ============================================================================
// Config Enums
// ============================================================================

/// TUI theme name
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum ThemeName {
    /// Dark theme (default)
    #[default]
    Dark,
    /// Light theme
    Light,
    /// High-contrast theme
    HighContrast,
}

impl ThemeName {
    /// Get the string representation of the theme name.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Dark => "dark",
            Self::Light => "light",
            Self::HighContrast => "high-contrast",
        }
    }
}

impl std::fmt::Display for ThemeName {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::str::FromStr for ThemeName {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "dark" => Ok(Self::Dark),
            "light" => Ok(Self::Light),
            "high-contrast" | "highcontrast" | "hc" => Ok(Self::HighContrast),
            _ => Err(format!("unknown theme: {s}")),
        }
    }
}

/// Fuzzy matching preset
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "kebab-case")]
pub enum FuzzyPreset {
    /// Strict matching (fewer false positives)
    Strict,
    /// Balanced matching (default)
    #[default]
    Balanced,
    /// Permissive matching (fewer false negatives)
    Permissive,
    /// Strict matching optimized for multi-SBOM comparison
    StrictMulti,
    /// Balanced matching optimized for multi-SBOM comparison
    BalancedMulti,
    /// Security-focused matching
    SecurityFocused,
}

impl FuzzyPreset {
    /// Get the string representation of the preset.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Strict => "strict",
            Self::Balanced => "balanced",
            Self::Permissive => "permissive",
            Self::StrictMulti => "strict-multi",
            Self::BalancedMulti => "balanced-multi",
            Self::SecurityFocused => "security-focused",
        }
    }
}

impl std::str::FromStr for FuzzyPreset {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().replace('_', "-").as_str() {
            "strict" => Ok(Self::Strict),
            "balanced" => Ok(Self::Balanced),
            "permissive" => Ok(Self::Permissive),
            "strict-multi" => Ok(Self::StrictMulti),
            "balanced-multi" => Ok(Self::BalancedMulti),
            "security-focused" => Ok(Self::SecurityFocused),
            _ => Err(format!("unknown fuzzy preset: {s}")),
        }
    }
}

impl std::fmt::Display for FuzzyPreset {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

// ============================================================================
// TUI Preferences (persisted)
// ============================================================================

/// TUI preferences that persist across sessions.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct TuiPreferences {
    /// Theme name
    pub theme: ThemeName,
    /// Last active tab in diff mode (e.g., "summary", "components")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_tab: Option<String>,
    /// Last active tab in view mode (e.g., "overview", "tree")
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub last_view_tab: Option<String>,
}

impl Default for TuiPreferences {
    fn default() -> Self {
        Self {
            theme: ThemeName::Dark,
            last_tab: None,
            last_view_tab: None,
        }
    }
}

impl TuiPreferences {
    /// Get the path to the preferences file.
    #[must_use]
    pub fn config_path() -> Option<PathBuf> {
        dirs::config_dir().map(|p| p.join("sbom-tools").join("preferences.json"))
    }

    /// Load preferences from disk, or return defaults if not found.
    #[must_use]
    pub fn load() -> Self {
        Self::config_path()
            .and_then(|p| std::fs::read_to_string(p).ok())
            .and_then(|s| serde_json::from_str(&s).ok())
            .unwrap_or_default()
    }

    /// Save preferences to disk.
    pub fn save(&self) -> std::io::Result<()> {
        if let Some(path) = Self::config_path() {
            if let Some(parent) = path.parent() {
                std::fs::create_dir_all(parent)?;
            }
            let json = serde_json::to_string_pretty(self)
                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
            std::fs::write(path, json)?;
        }
        Ok(())
    }
}

// ============================================================================
// TUI Configuration
// ============================================================================

/// TUI-specific configuration.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct TuiConfig {
    /// Theme name
    pub theme: ThemeName,
    /// Show line numbers in code views
    pub show_line_numbers: bool,
    /// Enable mouse support
    pub mouse_enabled: bool,
    /// Initial matching threshold for TUI threshold tuning
    #[schemars(range(min = 0.0, max = 1.0))]
    pub initial_threshold: f64,
}

impl Default for TuiConfig {
    fn default() -> Self {
        Self {
            theme: ThemeName::Dark,
            show_line_numbers: true,
            mouse_enabled: true,
            initial_threshold: 0.8,
        }
    }
}

// ============================================================================
// Command-specific Configuration Types
// ============================================================================

/// Configuration for diff operations
#[derive(Debug, Clone)]
pub struct DiffConfig {
    /// Paths to compare
    pub paths: DiffPaths,
    /// Output configuration
    pub output: OutputConfig,
    /// Matching configuration
    pub matching: MatchingConfig,
    /// Filtering options
    pub filtering: FilterConfig,
    /// Behavior flags
    pub behavior: BehaviorConfig,
    /// Graph-aware diffing configuration
    pub graph_diff: GraphAwareDiffConfig,
    /// Custom matching rules configuration
    pub rules: MatchingRulesPathConfig,
    /// Ecosystem-specific rules configuration
    pub ecosystem_rules: EcosystemRulesConfig,
    /// Enrichment configuration (always defined, runtime feature check)
    pub enrichment: EnrichmentConfig,
}

/// Paths for diff operation
#[derive(Debug, Clone)]
pub struct DiffPaths {
    /// Path to old/baseline SBOM
    pub old: PathBuf,
    /// Path to new SBOM
    pub new: PathBuf,
}

/// Configuration for view operations
#[derive(Debug, Clone)]
pub struct ViewConfig {
    /// Path to SBOM file
    pub sbom_path: PathBuf,
    /// Output configuration
    pub output: OutputConfig,
    /// Whether to validate against NTIA
    pub validate_ntia: bool,
    /// Filter by minimum vulnerability severity (critical, high, medium, low)
    pub min_severity: Option<String>,
    /// Only show components with vulnerabilities
    pub vulnerable_only: bool,
    /// Filter by ecosystem
    pub ecosystem_filter: Option<String>,
    /// Exit with code 2 if vulnerabilities are present
    pub fail_on_vuln: bool,
    /// BOM profile override (auto-detected if None)
    pub bom_profile: Option<crate::model::BomProfile>,
    /// Enrichment configuration
    pub enrichment: EnrichmentConfig,
}

/// Configuration for multi-diff operations
#[derive(Debug, Clone)]
pub struct MultiDiffConfig {
    /// Path to baseline SBOM
    pub baseline: PathBuf,
    /// Paths to target SBOMs
    pub targets: Vec<PathBuf>,
    /// Output configuration
    pub output: OutputConfig,
    /// Matching configuration
    pub matching: MatchingConfig,
    /// Filtering options
    pub filtering: FilterConfig,
    /// Behavior flags
    pub behavior: BehaviorConfig,
    /// Graph-aware diffing configuration
    pub graph_diff: GraphAwareDiffConfig,
    /// Custom matching rules configuration
    pub rules: MatchingRulesPathConfig,
    /// Ecosystem-specific rules configuration
    pub ecosystem_rules: EcosystemRulesConfig,
    /// Enrichment configuration
    pub enrichment: EnrichmentConfig,
}

/// Configuration for timeline analysis
#[derive(Debug, Clone)]
pub struct TimelineConfig {
    /// Paths to SBOMs in chronological order
    pub sbom_paths: Vec<PathBuf>,
    /// Output configuration
    pub output: OutputConfig,
    /// Matching configuration
    pub matching: MatchingConfig,
    /// Filtering options
    pub filtering: FilterConfig,
    /// Behavior flags
    pub behavior: BehaviorConfig,
    /// Graph-aware diffing configuration
    pub graph_diff: GraphAwareDiffConfig,
    /// Custom matching rules configuration
    pub rules: MatchingRulesPathConfig,
    /// Ecosystem-specific rules configuration
    pub ecosystem_rules: EcosystemRulesConfig,
    /// Enrichment configuration
    pub enrichment: EnrichmentConfig,
}

/// Configuration for query operations (searching components across multiple SBOMs)
#[derive(Debug, Clone)]
pub struct QueryConfig {
    /// Paths to SBOM files to search
    pub sbom_paths: Vec<PathBuf>,
    /// Output configuration
    pub output: OutputConfig,
    /// Enrichment configuration
    pub enrichment: EnrichmentConfig,
    /// Maximum number of results to return
    pub limit: Option<usize>,
    /// Group results by SBOM source
    pub group_by_sbom: bool,
}

/// Configuration for matrix comparison
#[derive(Debug, Clone)]
pub struct MatrixConfig {
    /// Paths to SBOMs
    pub sbom_paths: Vec<PathBuf>,
    /// Output configuration
    pub output: OutputConfig,
    /// Matching configuration
    pub matching: MatchingConfig,
    /// Similarity threshold for clustering (0.0-1.0)
    pub cluster_threshold: f64,
    /// Filtering options
    pub filtering: FilterConfig,
    /// Behavior flags
    pub behavior: BehaviorConfig,
    /// Graph-aware diffing configuration
    pub graph_diff: GraphAwareDiffConfig,
    /// Custom matching rules configuration
    pub rules: MatchingRulesPathConfig,
    /// Ecosystem-specific rules configuration
    pub ecosystem_rules: EcosystemRulesConfig,
    /// Enrichment configuration
    pub enrichment: EnrichmentConfig,
}

/// Configuration for the `vex` subcommand.
#[derive(Debug, Clone)]
pub struct VexConfig {
    /// Path to SBOM file
    pub sbom_path: PathBuf,
    /// Paths to external VEX documents
    pub vex_paths: Vec<PathBuf>,
    /// Output format
    pub output_format: ReportFormat,
    /// Output file path (None for stdout)
    pub output_file: Option<PathBuf>,
    /// Suppress non-essential output
    pub quiet: bool,
    /// Only show actionable vulnerabilities (exclude NotAffected/Fixed)
    pub actionable_only: bool,
    /// Filter by VEX state
    pub filter_state: Option<String>,
    /// Enrichment configuration (for OSV/EOL before VEX overlay)
    pub enrichment: EnrichmentConfig,
}

// ============================================================================
// Sub-configuration Types
// ============================================================================

/// Output-related configuration
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct OutputConfig {
    /// Output format
    pub format: ReportFormat,
    /// Output file path (None for stdout)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file: Option<PathBuf>,
    /// Report types to include
    pub report_types: ReportType,
    /// Disable colored output
    pub no_color: bool,
    /// Streaming configuration for large SBOMs
    pub streaming: StreamingConfig,
    /// Optional export filename template for TUI exports.
    ///
    /// Placeholders: `{date}` (YYYY-MM-DD), `{time}` (HHMMSS),
    /// `{format}` (json/md/html), `{command}` (diff/view).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub export_template: Option<String>,
}

impl Default for OutputConfig {
    fn default() -> Self {
        Self {
            format: ReportFormat::Auto,
            file: None,
            report_types: ReportType::All,
            no_color: false,
            streaming: StreamingConfig::default(),
            export_template: None,
        }
    }
}

/// Streaming configuration for memory-efficient processing of large SBOMs.
///
/// When streaming is enabled, the tool uses streaming parsers and reporters
/// to avoid loading entire SBOMs into memory. This is essential for SBOMs
/// with thousands of components.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct StreamingConfig {
    /// Enable streaming mode automatically for files larger than this threshold (in bytes).
    /// Default: 10 MB (`10_485_760` bytes)
    #[schemars(range(min = 0))]
    pub threshold_bytes: u64,
    /// Force streaming mode regardless of file size.
    /// Useful for testing or when processing stdin.
    pub force: bool,
    /// Disable streaming mode entirely (always load full SBOMs into memory).
    pub disabled: bool,
    /// Enable streaming for stdin input (since size is unknown).
    /// Default: true
    pub stream_stdin: bool,
}

impl Default for StreamingConfig {
    fn default() -> Self {
        Self {
            threshold_bytes: 10 * 1024 * 1024, // 10 MB
            force: false,
            disabled: false,
            stream_stdin: true,
        }
    }
}

impl StreamingConfig {
    /// Check if streaming should be used for a file of the given size.
    #[must_use]
    pub fn should_stream(&self, file_size: Option<u64>, is_stdin: bool) -> bool {
        if self.disabled {
            return false;
        }
        if self.force {
            return true;
        }
        if is_stdin && self.stream_stdin {
            return true;
        }
        file_size.map_or(self.stream_stdin, |size| size >= self.threshold_bytes)
    }

    /// Create a streaming config that always streams.
    #[must_use]
    pub fn always() -> Self {
        Self {
            force: true,
            ..Default::default()
        }
    }

    /// Create a streaming config that never streams.
    #[must_use]
    pub fn never() -> Self {
        Self {
            disabled: true,
            ..Default::default()
        }
    }

    /// Set the threshold in megabytes.
    #[must_use]
    pub const fn with_threshold_mb(mut self, mb: u64) -> Self {
        self.threshold_bytes = mb * 1024 * 1024;
        self
    }
}

/// Matching and comparison configuration
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct MatchingConfig {
    /// Fuzzy matching preset
    pub fuzzy_preset: FuzzyPreset,
    /// Custom matching threshold (overrides preset)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[schemars(range(min = 0.0, max = 1.0))]
    pub threshold: Option<f64>,
    /// Include unchanged components in output
    pub include_unchanged: bool,
}

impl Default for MatchingConfig {
    fn default() -> Self {
        Self {
            fuzzy_preset: FuzzyPreset::Balanced,
            threshold: None,
            include_unchanged: false,
        }
    }
}

impl MatchingConfig {
    /// Convert preset name to `FuzzyMatchConfig`
    #[must_use]
    pub fn to_fuzzy_config(&self) -> FuzzyMatchConfig {
        let mut config =
            FuzzyMatchConfig::from_preset(self.fuzzy_preset.as_str()).unwrap_or_else(|| {
                // Enum guarantees valid preset, but from_preset may not know all variants
                FuzzyMatchConfig::balanced()
            });

        // Apply custom threshold if specified
        if let Some(threshold) = self.threshold {
            config = config.with_threshold(threshold);
        }

        config
    }
}

/// Filtering options for diff results
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct FilterConfig {
    /// Only show items with changes
    pub only_changes: bool,
    /// Minimum severity filter
    #[serde(skip_serializing_if = "Option::is_none")]
    pub min_severity: Option<String>,
    /// Exclude vulnerabilities with VEX status `not_affected` or fixed
    #[serde(alias = "exclude_vex_not_affected")]
    pub exclude_vex_resolved: bool,
    /// Exit with error if introduced vulnerabilities lack VEX statements
    pub fail_on_vex_gap: bool,
}

/// Behavior flags for diff operations
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct BehaviorConfig {
    /// Exit with code 2 if new vulnerabilities are introduced
    pub fail_on_vuln: bool,
    /// Exit with code 1 if any changes detected
    pub fail_on_change: bool,
    /// Suppress non-essential output
    pub quiet: bool,
    /// Show detailed match explanations for each matched component
    pub explain_matches: bool,
    /// Recommend optimal matching threshold based on the SBOMs
    pub recommend_threshold: bool,
}

/// Graph-aware diffing configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct GraphAwareDiffConfig {
    /// Enable graph-aware diffing
    pub enabled: bool,
    /// Detect component reparenting
    pub detect_reparenting: bool,
    /// Detect depth changes
    pub detect_depth_changes: bool,
    /// Maximum depth to analyze (0 = unlimited)
    pub max_depth: u32,
    /// Minimum impact level to include in output ("low", "medium", "high", "critical")
    pub impact_threshold: Option<String>,
    /// Relationship type filter — only include edges matching these types (empty = all)
    pub relation_filter: Vec<String>,
}

impl GraphAwareDiffConfig {
    /// Create enabled graph diff options with defaults
    #[must_use]
    pub const fn enabled() -> Self {
        Self {
            enabled: true,
            detect_reparenting: true,
            detect_depth_changes: true,
            max_depth: 0,
            impact_threshold: None,
            relation_filter: Vec::new(),
        }
    }
}

/// Custom matching rules configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct MatchingRulesPathConfig {
    /// Path to matching rules YAML file
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rules_file: Option<PathBuf>,
    /// Dry-run mode (show what would match without applying)
    pub dry_run: bool,
}

/// Ecosystem-specific rules configuration
#[derive(Debug, Clone, Default, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct EcosystemRulesConfig {
    /// Path to ecosystem rules configuration file
    #[serde(skip_serializing_if = "Option::is_none")]
    pub config_file: Option<PathBuf>,
    /// Disable ecosystem-specific normalization
    pub disabled: bool,
    /// Enable typosquat detection warnings
    pub detect_typosquats: bool,
}

/// Enrichment configuration for vulnerability data sources.
///
/// This configuration is always defined regardless of the `enrichment` feature flag.
/// When the feature is disabled, the configuration is silently ignored at runtime.
#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
#[serde(default)]
pub struct EnrichmentConfig {
    /// Enable enrichment (if false, no enrichment is performed)
    pub enabled: bool,
    /// Enrichment provider ("osv", "nvd", etc.)
    pub provider: String,
    /// Cache time-to-live in hours
    #[schemars(range(min = 1))]
    pub cache_ttl_hours: u64,
    /// Maximum concurrent requests
    #[schemars(range(min = 1))]
    pub max_concurrent: usize,
    /// Cache directory for vulnerability data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache_dir: Option<std::path::PathBuf>,
    /// Bypass cache and fetch fresh vulnerability data
    pub bypass_cache: bool,
    /// API timeout in seconds
    #[schemars(range(min = 1))]
    pub timeout_secs: u64,
    /// Enable end-of-life detection via endoflife.date API
    pub enable_eol: bool,
    /// Paths to external VEX documents (OpenVEX format)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub vex_paths: Vec<std::path::PathBuf>,
}

impl Default for EnrichmentConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            provider: "osv".to_string(),
            cache_ttl_hours: 24,
            max_concurrent: 10,
            cache_dir: None,
            bypass_cache: false,
            timeout_secs: 30,
            enable_eol: false,
            vex_paths: Vec::new(),
        }
    }
}

impl EnrichmentConfig {
    /// Create an enabled enrichment config with OSV provider.
    #[must_use]
    pub fn osv() -> Self {
        Self {
            enabled: true,
            provider: "osv".to_string(),
            ..Default::default()
        }
    }

    /// Create an enabled enrichment config with custom settings.
    #[must_use]
    pub fn with_cache_dir(mut self, dir: std::path::PathBuf) -> Self {
        self.cache_dir = Some(dir);
        self
    }

    /// Set the cache TTL in hours.
    #[must_use]
    pub const fn with_cache_ttl_hours(mut self, hours: u64) -> Self {
        self.cache_ttl_hours = hours;
        self
    }

    /// Enable cache bypass (refresh).
    #[must_use]
    pub const fn with_bypass_cache(mut self) -> Self {
        self.bypass_cache = true;
        self
    }

    /// Set the API timeout in seconds.
    #[must_use]
    pub const fn with_timeout_secs(mut self, secs: u64) -> Self {
        self.timeout_secs = secs;
        self
    }

    /// Set VEX document paths.
    #[must_use]
    pub fn with_vex_paths(mut self, paths: Vec<std::path::PathBuf>) -> Self {
        self.vex_paths = paths;
        self
    }
}

// ============================================================================
// Builder for DiffConfig
// ============================================================================

/// Builder for `DiffConfig`
#[derive(Debug, Default)]
pub struct DiffConfigBuilder {
    old: Option<PathBuf>,
    new: Option<PathBuf>,
    output: OutputConfig,
    matching: MatchingConfig,
    filtering: FilterConfig,
    behavior: BehaviorConfig,
    graph_diff: GraphAwareDiffConfig,
    rules: MatchingRulesPathConfig,
    ecosystem_rules: EcosystemRulesConfig,
    enrichment: EnrichmentConfig,
}

impl DiffConfigBuilder {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    #[must_use]
    pub fn old_path(mut self, path: PathBuf) -> Self {
        self.old = Some(path);
        self
    }

    #[must_use]
    pub fn new_path(mut self, path: PathBuf) -> Self {
        self.new = Some(path);
        self
    }

    #[must_use]
    pub const fn output_format(mut self, format: ReportFormat) -> Self {
        self.output.format = format;
        self
    }

    #[must_use]
    pub fn output_file(mut self, file: Option<PathBuf>) -> Self {
        self.output.file = file;
        self
    }

    #[must_use]
    pub const fn report_types(mut self, types: ReportType) -> Self {
        self.output.report_types = types;
        self
    }

    #[must_use]
    pub const fn no_color(mut self, no_color: bool) -> Self {
        self.output.no_color = no_color;
        self
    }

    #[must_use]
    pub fn fuzzy_preset(mut self, preset: FuzzyPreset) -> Self {
        self.matching.fuzzy_preset = preset;
        self
    }

    #[must_use]
    pub const fn matching_threshold(mut self, threshold: Option<f64>) -> Self {
        self.matching.threshold = threshold;
        self
    }

    #[must_use]
    pub const fn include_unchanged(mut self, include: bool) -> Self {
        self.matching.include_unchanged = include;
        self
    }

    #[must_use]
    pub const fn only_changes(mut self, only: bool) -> Self {
        self.filtering.only_changes = only;
        self
    }

    #[must_use]
    pub fn min_severity(mut self, severity: Option<String>) -> Self {
        self.filtering.min_severity = severity;
        self
    }

    #[must_use]
    pub const fn fail_on_vuln(mut self, fail: bool) -> Self {
        self.behavior.fail_on_vuln = fail;
        self
    }

    #[must_use]
    pub const fn fail_on_change(mut self, fail: bool) -> Self {
        self.behavior.fail_on_change = fail;
        self
    }

    #[must_use]
    pub const fn quiet(mut self, quiet: bool) -> Self {
        self.behavior.quiet = quiet;
        self
    }

    #[must_use]
    pub const fn explain_matches(mut self, explain: bool) -> Self {
        self.behavior.explain_matches = explain;
        self
    }

    #[must_use]
    pub const fn recommend_threshold(mut self, recommend: bool) -> Self {
        self.behavior.recommend_threshold = recommend;
        self
    }

    #[must_use]
    pub fn graph_diff(mut self, enabled: bool) -> Self {
        self.graph_diff = if enabled {
            GraphAwareDiffConfig::enabled()
        } else {
            GraphAwareDiffConfig::default()
        };
        self
    }

    #[must_use]
    pub fn matching_rules_file(mut self, file: Option<PathBuf>) -> Self {
        self.rules.rules_file = file;
        self
    }

    #[must_use]
    pub const fn dry_run_rules(mut self, dry_run: bool) -> Self {
        self.rules.dry_run = dry_run;
        self
    }

    #[must_use]
    pub fn ecosystem_rules_file(mut self, file: Option<PathBuf>) -> Self {
        self.ecosystem_rules.config_file = file;
        self
    }

    #[must_use]
    pub const fn disable_ecosystem_rules(mut self, disabled: bool) -> Self {
        self.ecosystem_rules.disabled = disabled;
        self
    }

    #[must_use]
    pub const fn detect_typosquats(mut self, detect: bool) -> Self {
        self.ecosystem_rules.detect_typosquats = detect;
        self
    }

    #[must_use]
    pub fn enrichment(mut self, config: EnrichmentConfig) -> Self {
        self.enrichment = config;
        self
    }

    #[must_use]
    pub const fn enable_enrichment(mut self, enabled: bool) -> Self {
        self.enrichment.enabled = enabled;
        self
    }

    pub fn build(self) -> anyhow::Result<DiffConfig> {
        let old = self
            .old
            .ok_or_else(|| anyhow::anyhow!("old path is required"))?;
        let new = self
            .new
            .ok_or_else(|| anyhow::anyhow!("new path is required"))?;

        Ok(DiffConfig {
            paths: DiffPaths { old, new },
            output: self.output,
            matching: self.matching,
            filtering: self.filtering,
            behavior: self.behavior,
            graph_diff: self.graph_diff,
            rules: self.rules,
            ecosystem_rules: self.ecosystem_rules,
            enrichment: self.enrichment,
        })
    }
}

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

    #[test]
    fn theme_name_serde_roundtrip() {
        // JSON deserialization (preferences.json format)
        let dark: ThemeName = serde_json::from_str(r#""dark""#).unwrap();
        assert_eq!(dark, ThemeName::Dark);

        let light: ThemeName = serde_json::from_str(r#""light""#).unwrap();
        assert_eq!(light, ThemeName::Light);

        let hc: ThemeName = serde_json::from_str(r#""high-contrast""#).unwrap();
        assert_eq!(hc, ThemeName::HighContrast);

        // Roundtrip
        let serialized = serde_json::to_string(&ThemeName::HighContrast).unwrap();
        assert_eq!(serialized, r#""high-contrast""#);
    }

    #[test]
    fn theme_name_from_str() {
        assert_eq!("dark".parse::<ThemeName>().unwrap(), ThemeName::Dark);
        assert_eq!("light".parse::<ThemeName>().unwrap(), ThemeName::Light);
        assert_eq!(
            "high-contrast".parse::<ThemeName>().unwrap(),
            ThemeName::HighContrast
        );
        assert_eq!("hc".parse::<ThemeName>().unwrap(), ThemeName::HighContrast);
        assert!("neon".parse::<ThemeName>().is_err());
    }

    #[test]
    fn fuzzy_preset_serde_roundtrip() {
        let presets = [
            ("strict", FuzzyPreset::Strict),
            ("balanced", FuzzyPreset::Balanced),
            ("permissive", FuzzyPreset::Permissive),
            ("strict-multi", FuzzyPreset::StrictMulti),
            ("balanced-multi", FuzzyPreset::BalancedMulti),
            ("security-focused", FuzzyPreset::SecurityFocused),
        ];

        for (json_str, expected) in presets {
            let json = format!(r#""{json_str}""#);
            let parsed: FuzzyPreset = serde_json::from_str(&json).unwrap();
            assert_eq!(parsed, expected, "failed to deserialize {json_str}");

            let serialized = serde_json::to_string(&expected).unwrap();
            assert_eq!(serialized, json, "failed to serialize {expected:?}");
        }
    }

    #[test]
    fn fuzzy_preset_from_str() {
        assert_eq!(
            "strict".parse::<FuzzyPreset>().unwrap(),
            FuzzyPreset::Strict
        );
        assert_eq!(
            "security-focused".parse::<FuzzyPreset>().unwrap(),
            FuzzyPreset::SecurityFocused
        );
        // Underscore variant accepted
        assert_eq!(
            "strict_multi".parse::<FuzzyPreset>().unwrap(),
            FuzzyPreset::StrictMulti
        );
        assert!("invalid".parse::<FuzzyPreset>().is_err());
    }

    #[test]
    fn tui_preferences_json_backward_compat() {
        // Simulates loading a preferences.json written by older version
        let old_json = r#"{"theme":"high-contrast","last_tab":"components"}"#;
        let prefs: TuiPreferences = serde_json::from_str(old_json).unwrap();
        assert_eq!(prefs.theme, ThemeName::HighContrast);
        assert_eq!(prefs.last_tab.as_deref(), Some("components"));
    }
}