tokmd-settings 1.10.0

Clap-free settings types for tokmd scan and format layers.
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
//! # tokmd-settings
//!
//! **Tier 0 (Pure Settings)**
//!
//! Clap-free settings types for the scan and format layers.
//! These types mirror CLI arguments without Clap dependencies,
//! making them suitable for FFI boundaries and library consumers.
//!
//! ## What belongs here
//! * Pure data types with Serde derive
//! * Scan, language, module, export, analyze, diff settings
//! * Default values and conversions
//!
//! ## What does NOT belong here
//! * Clap parsing (use `tokmd::cli`)
//! * I/O operations
//! * Business logic

use std::collections::BTreeMap;
use std::path::Path;

use serde::{Deserialize, Serialize};

// Re-export types from tokmd_types for convenience
pub use tokmd_types::{ChildIncludeMode, ChildrenMode, ConfigMode, ExportFormat, RedactMode};

// Legacy profile contract persisted by the historical `config.json` format.
//
// These types are intentionally kept in `tokmd-settings` so that the config
// profile contract is available without CLI parsing dependencies.

/// Legacy profile map used by historical `config.json` files.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UserConfig {
    pub profiles: BTreeMap<String, Profile>,
    pub repos: BTreeMap<String, String>, // "owner/repo" -> "profile_name"
}

/// Legacy profile options shared by configuration consumers.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Profile {
    // Shared
    pub format: Option<String>, // "json", "md", "tsv", "csv", "jsonl"
    pub top: Option<usize>,

    // Lang
    pub files: Option<bool>,

    // Module / Export
    pub module_roots: Option<Vec<String>>,
    pub module_depth: Option<usize>,
    pub min_code: Option<usize>,
    pub max_rows: Option<usize>,
    pub redact: Option<RedactMode>,
    pub meta: Option<bool>,

    // "children" can be ChildrenMode or ChildIncludeMode string
    pub children: Option<String>,
}

/// Scan options shared by all commands that invoke the scanner.
///
/// This mirrors the scan-relevant fields of CLI global args without any
/// UI-specific fields (`verbose`, `no_progress`). Lower-tier crates
/// (scan, format, model) depend on this instead of the CLI parser.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ScanOptions {
    /// Glob patterns to exclude.
    #[serde(default)]
    pub excluded: Vec<String>,

    /// Whether to load scan config files (`tokei.toml` / `.tokeirc`).
    #[serde(default)]
    pub config: ConfigMode,

    /// Count hidden files and directories.
    #[serde(default)]
    pub hidden: bool,

    /// Don't respect ignore files (.gitignore, .ignore, etc.).
    #[serde(default)]
    pub no_ignore: bool,

    /// Don't respect ignore files in parent directories.
    #[serde(default)]
    pub no_ignore_parent: bool,

    /// Don't respect .ignore and .tokeignore files.
    #[serde(default)]
    pub no_ignore_dot: bool,

    /// Don't respect VCS ignore files (.gitignore, .hgignore, etc.).
    #[serde(default)]
    pub no_ignore_vcs: bool,

    /// Treat doc strings as comments.
    #[serde(default)]
    pub treat_doc_strings_as_comments: bool,
}

/// Global scan settings shared by all operations.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct ScanSettings {
    /// Paths to scan (defaults to `["."]`).
    #[serde(default)]
    pub paths: Vec<String>,

    /// Scan options (excludes, ignore flags, etc.).
    #[serde(flatten)]
    pub options: ScanOptions,
}

impl ScanSettings {
    /// Create settings for scanning the current directory with defaults.
    pub fn current_dir() -> Self {
        Self {
            paths: vec![".".to_string()],
            ..Default::default()
        }
    }

    /// Create settings for scanning specific paths.
    pub fn for_paths(paths: Vec<String>) -> Self {
        Self {
            paths,
            ..Default::default()
        }
    }
}

/// Settings for language summary (`tokmd lang`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LangSettings {
    /// Show only the top N rows (0 = all).
    #[serde(default)]
    pub top: usize,

    /// Include file counts and average lines per file.
    #[serde(default)]
    pub files: bool,

    /// How to handle embedded languages.
    #[serde(default = "default_children_mode")]
    pub children: ChildrenMode,

    /// Redaction mode for output.
    #[serde(default)]
    pub redact: Option<RedactMode>,
}

impl Default for LangSettings {
    fn default() -> Self {
        Self {
            top: 0,
            files: false,
            children: ChildrenMode::Collapse,
            redact: None,
        }
    }
}

fn default_children_mode() -> ChildrenMode {
    ChildrenMode::Collapse
}

/// Settings for module summary (`tokmd module`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModuleSettings {
    /// Show only the top N modules (0 = all).
    #[serde(default)]
    pub top: usize,

    /// Top-level directories as "module roots".
    #[serde(default = "default_module_roots")]
    pub module_roots: Vec<String>,

    /// Path segments to include for module roots.
    #[serde(default = "default_module_depth")]
    pub module_depth: usize,

    /// How to handle embedded languages.
    #[serde(default = "default_child_include_mode")]
    pub children: ChildIncludeMode,

    /// Redaction mode for output.
    #[serde(default)]
    pub redact: Option<RedactMode>,
}

fn default_module_roots() -> Vec<String> {
    vec!["crates".to_string(), "packages".to_string()]
}

fn default_module_depth() -> usize {
    2
}

fn default_child_include_mode() -> ChildIncludeMode {
    ChildIncludeMode::Separate
}

impl Default for ModuleSettings {
    fn default() -> Self {
        Self {
            top: 0,
            module_roots: default_module_roots(),
            module_depth: default_module_depth(),
            children: default_child_include_mode(),
            redact: None,
        }
    }
}

/// Settings for file-level export (`tokmd export`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExportSettings {
    /// Output format.
    #[serde(default = "default_export_format")]
    pub format: ExportFormat,

    /// Module roots (see `ModuleSettings`).
    #[serde(default = "default_module_roots")]
    pub module_roots: Vec<String>,

    /// Module depth (see `ModuleSettings`).
    #[serde(default = "default_module_depth")]
    pub module_depth: usize,

    /// How to handle embedded languages.
    #[serde(default = "default_child_include_mode")]
    pub children: ChildIncludeMode,

    /// Drop rows with fewer than N code lines.
    #[serde(default)]
    pub min_code: usize,

    /// Stop after emitting N rows (0 = unlimited).
    #[serde(default)]
    pub max_rows: usize,

    /// Redaction mode.
    #[serde(default = "default_redact_mode")]
    pub redact: RedactMode,

    /// Include a meta record.
    #[serde(default = "default_meta")]
    pub meta: bool,

    /// Strip this prefix from paths.
    #[serde(default)]
    pub strip_prefix: Option<String>,
}

fn default_redact_mode() -> RedactMode {
    RedactMode::None
}

fn default_export_format() -> ExportFormat {
    ExportFormat::Jsonl
}

fn default_meta() -> bool {
    true
}

impl Default for ExportSettings {
    fn default() -> Self {
        Self {
            format: default_export_format(),
            module_roots: default_module_roots(),
            module_depth: default_module_depth(),
            children: default_child_include_mode(),
            min_code: 0,
            max_rows: 0,
            redact: RedactMode::None,
            meta: true,
            strip_prefix: None,
        }
    }
}

/// Settings for analysis (`tokmd analyze`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AnalyzeSettings {
    /// Analysis preset to run.
    #[serde(default = "default_preset")]
    pub preset: String,

    /// Context window size (tokens) for utilization bars.
    #[serde(default)]
    pub window: Option<usize>,

    /// Force-enable git-based metrics.
    #[serde(default)]
    pub git: Option<bool>,

    /// Limit files walked for asset/deps/content scans.
    #[serde(default)]
    pub max_files: Option<usize>,

    /// Limit total bytes read during content scans.
    #[serde(default)]
    pub max_bytes: Option<u64>,

    /// Limit bytes per file during content scans.
    #[serde(default)]
    pub max_file_bytes: Option<u64>,

    /// Limit commits scanned for git metrics.
    #[serde(default)]
    pub max_commits: Option<usize>,

    /// Limit files per commit for git metrics.
    #[serde(default)]
    pub max_commit_files: Option<usize>,

    /// Import graph granularity.
    #[serde(default = "default_granularity")]
    pub granularity: String,

    /// Effort model for estimate calculations.
    #[serde(default)]
    pub effort_model: Option<String>,

    /// Effort report layer.
    #[serde(default)]
    pub effort_layer: Option<String>,

    /// Base reference for effort delta computation.
    #[serde(default)]
    pub effort_base_ref: Option<String>,

    /// Head reference for effort delta computation.
    #[serde(default)]
    pub effort_head_ref: Option<String>,

    /// Enable Monte Carlo uncertainty for effort estimation.
    #[serde(default)]
    pub effort_monte_carlo: Option<bool>,

    /// Monte Carlo iterations for effort estimation.
    #[serde(default)]
    pub effort_mc_iterations: Option<usize>,

    /// Monte Carlo seed for effort estimation.
    #[serde(default)]
    pub effort_mc_seed: Option<u64>,
}

fn default_preset() -> String {
    "receipt".to_string()
}

fn default_granularity() -> String {
    "module".to_string()
}

impl Default for AnalyzeSettings {
    fn default() -> Self {
        Self {
            preset: default_preset(),
            window: None,
            git: None,
            max_files: None,
            max_bytes: None,
            max_file_bytes: None,
            max_commits: None,
            max_commit_files: None,
            granularity: default_granularity(),
            effort_model: None,
            effort_layer: None,
            effort_base_ref: None,
            effort_head_ref: None,
            effort_monte_carlo: None,
            effort_mc_iterations: None,
            effort_mc_seed: None,
        }
    }
}

/// Settings for cockpit PR metrics (`tokmd cockpit`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CockpitSettings {
    /// Base ref to compare from.
    #[serde(default = "default_cockpit_base")]
    pub base: String,

    /// Head ref to compare to.
    #[serde(default = "default_cockpit_head")]
    pub head: String,

    /// Range mode: "two-dot" or "three-dot".
    #[serde(default = "default_cockpit_range_mode")]
    pub range_mode: String,

    /// Optional baseline file path for trend comparison.
    #[serde(default)]
    pub baseline: Option<String>,
}

fn default_cockpit_base() -> String {
    "main".to_string()
}

fn default_cockpit_head() -> String {
    "HEAD".to_string()
}

fn default_cockpit_range_mode() -> String {
    "two-dot".to_string()
}

impl Default for CockpitSettings {
    fn default() -> Self {
        Self {
            base: default_cockpit_base(),
            head: default_cockpit_head(),
            range_mode: default_cockpit_range_mode(),
            baseline: None,
        }
    }
}

/// Settings for diff comparison (`tokmd diff`).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DiffSettings {
    /// Base reference to compare from.
    pub from: String,

    /// Target reference to compare to.
    pub to: String,
}

// =============================================================================
// TOML Configuration File Structures
// =============================================================================

/// Root TOML configuration structure.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct TomlConfig {
    /// Scan settings (applies to all commands).
    pub scan: ScanConfig,

    /// Module command settings.
    pub module: ModuleConfig,

    /// Export command settings.
    pub export: ExportConfig,

    /// Analyze command settings.
    pub analyze: AnalyzeConfig,

    /// Context command settings.
    pub context: ContextConfig,

    /// Badge command settings.
    pub badge: BadgeConfig,

    /// Gate command settings.
    pub gate: GateConfig,

    /// Named view profiles (e.g., [view.llm], [view.ci]).
    #[serde(default)]
    pub view: BTreeMap<String, ViewProfile>,
}

/// Scan settings shared by all commands.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ScanConfig {
    /// Paths to scan (default: ["."])
    pub paths: Option<Vec<String>>,

    /// Glob patterns to exclude.
    pub exclude: Option<Vec<String>>,

    /// Include hidden files and directories.
    pub hidden: Option<bool>,

    /// Config file strategy for tokei: "auto" or "none".
    pub config: Option<String>,

    /// Disable all ignore files.
    pub no_ignore: Option<bool>,

    /// Disable parent directory ignore file traversal.
    pub no_ignore_parent: Option<bool>,

    /// Disable .ignore/.tokeignore files.
    pub no_ignore_dot: Option<bool>,

    /// Disable .gitignore files.
    pub no_ignore_vcs: Option<bool>,

    /// Treat doc comments as comments instead of code.
    pub doc_comments: Option<bool>,
}

/// Module command settings.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ModuleConfig {
    /// Root directories for module grouping.
    pub roots: Option<Vec<String>>,

    /// Depth for module grouping.
    pub depth: Option<usize>,

    /// Children handling: "collapse" or "separate".
    pub children: Option<String>,
}

/// Export command settings.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ExportConfig {
    /// Minimum lines of code to include.
    pub min_code: Option<usize>,

    /// Maximum rows in output.
    pub max_rows: Option<usize>,

    /// Redaction mode: "none", "paths", or "all".
    pub redact: Option<String>,

    /// Output format: "jsonl", "csv", "json", "cyclonedx".
    pub format: Option<String>,

    /// Children handling: "collapse" or "separate".
    pub children: Option<String>,
}

/// Analyze command settings.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct AnalyzeConfig {
    /// Analysis preset.
    pub preset: Option<String>,

    /// Context window size for utilization analysis.
    pub window: Option<usize>,

    /// Output format.
    pub format: Option<String>,

    /// Force git metrics on/off.
    pub git: Option<bool>,

    /// Max files for asset/deps/content scans.
    pub max_files: Option<usize>,

    /// Max total bytes for content scans.
    pub max_bytes: Option<u64>,

    /// Max bytes per file for content scans.
    pub max_file_bytes: Option<u64>,

    /// Max commits for git metrics.
    pub max_commits: Option<usize>,

    /// Max files per commit for git metrics.
    pub max_commit_files: Option<usize>,

    /// Import graph granularity: "module" or "file".
    pub granularity: Option<String>,

    /// Effort model for estimate calculations.
    pub effort_model: Option<String>,

    /// Effort report layer.
    pub effort_layer: Option<String>,

    /// Base reference for effort delta computation.
    pub effort_base_ref: Option<String>,

    /// Head reference for effort delta computation.
    pub effort_head_ref: Option<String>,

    /// Enable Monte Carlo uncertainty for effort estimation.
    pub effort_monte_carlo: Option<bool>,

    /// Monte Carlo iterations for effort estimation.
    pub effort_mc_iterations: Option<usize>,

    /// Monte Carlo seed for effort estimation.
    pub effort_mc_seed: Option<u64>,
}

/// Context command settings.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ContextConfig {
    /// Token budget with optional k/m suffix.
    pub budget: Option<String>,

    /// Packing strategy: "greedy" or "spread".
    pub strategy: Option<String>,

    /// Ranking metric: "code", "tokens", "churn", "hotspot".
    pub rank_by: Option<String>,

    /// Output mode: "list", "bundle", "json".
    pub output: Option<String>,

    /// Strip blank lines from bundle output.
    pub compress: Option<bool>,
}

/// Badge command settings.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct BadgeConfig {
    /// Default metric for badges.
    pub metric: Option<String>,
}

/// Gate command settings.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct GateConfig {
    /// Path to policy file.
    pub policy: Option<String>,

    /// Path to baseline file for ratchet comparison.
    pub baseline: Option<String>,

    /// Analysis preset for compute-then-gate mode.
    pub preset: Option<String>,

    /// Fail fast on first error.
    pub fail_fast: Option<bool>,

    /// Inline policy rules.
    pub rules: Option<Vec<GateRule>>,

    /// Inline ratchet rules for baseline comparison.
    pub ratchet: Option<Vec<RatchetRuleConfig>>,

    /// Allow missing baseline values (treat as pass).
    pub allow_missing_baseline: Option<bool>,

    /// Allow missing current values (treat as pass).
    pub allow_missing_current: Option<bool>,
}

/// A single ratchet rule for baseline comparison (TOML configuration).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RatchetRuleConfig {
    /// JSON Pointer to the metric (e.g., "/complexity/avg_cyclomatic").
    pub pointer: String,

    /// Maximum allowed percentage increase from baseline.
    #[serde(default)]
    pub max_increase_pct: Option<f64>,

    /// Maximum allowed absolute value (hard ceiling).
    #[serde(default)]
    pub max_value: Option<f64>,

    /// Rule severity level: "error" (default) or "warn".
    #[serde(default)]
    pub level: Option<String>,

    /// Human-readable description of the rule.
    #[serde(default)]
    pub description: Option<String>,
}

/// A single gate policy rule (for inline TOML configuration).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GateRule {
    /// Human-readable name for the rule.
    pub name: String,

    /// JSON Pointer to the value to check (RFC 6901).
    pub pointer: String,

    /// Comparison operator.
    pub op: String,

    /// Single value for comparison.
    #[serde(default)]
    pub value: Option<serde_json::Value>,

    /// Multiple values for "in" operator.
    #[serde(default)]
    pub values: Option<Vec<serde_json::Value>>,

    /// Negate the result.
    #[serde(default)]
    pub negate: bool,

    /// Rule severity level: "error" or "warn".
    #[serde(default)]
    pub level: Option<String>,

    /// Custom failure message.
    #[serde(default)]
    pub message: Option<String>,
}

/// A named view profile that can override settings for specific use cases.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct ViewProfile {
    // Shared settings
    /// Output format.
    pub format: Option<String>,

    /// Show only top N rows.
    pub top: Option<usize>,

    // Lang settings
    /// Include file counts in lang output.
    pub files: Option<bool>,

    // Module / Export settings
    /// Module roots for grouping.
    pub module_roots: Option<Vec<String>>,

    /// Module depth for grouping.
    pub module_depth: Option<usize>,

    /// Minimum lines of code.
    pub min_code: Option<usize>,

    /// Maximum rows in output.
    pub max_rows: Option<usize>,

    /// Redaction mode.
    pub redact: Option<String>,

    /// Include metadata record.
    pub meta: Option<bool>,

    /// Children handling mode.
    pub children: Option<String>,

    // Analyze settings
    /// Analysis preset.
    pub preset: Option<String>,

    /// Context window size.
    pub window: Option<usize>,

    // Context settings
    /// Token budget.
    pub budget: Option<String>,

    /// Packing strategy.
    pub strategy: Option<String>,

    /// Ranking metric.
    pub rank_by: Option<String>,

    /// Output mode for context.
    pub output: Option<String>,

    /// Strip blank lines.
    pub compress: Option<bool>,

    // Badge settings
    /// Badge metric.
    pub metric: Option<String>,
}

impl TomlConfig {
    /// Load configuration from a TOML string.
    pub fn parse(s: &str) -> Result<Self, toml::de::Error> {
        toml::from_str(s)
    }

    /// Load configuration from a file path.
    pub fn from_file(path: &Path) -> std::io::Result<Self> {
        let content = std::fs::read_to_string(path)?;
        toml::from_str(&content)
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
    }
}

/// Result type alias for TOML parsing errors.
pub type TomlResult<T> = Result<T, toml::de::Error>;

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    #[test]
    fn scan_options_default() {
        let opts = ScanOptions::default();
        assert!(opts.excluded.is_empty());
        assert!(!opts.hidden);
        assert!(!opts.no_ignore);
    }

    #[test]
    fn scan_settings_current_dir() {
        let s = ScanSettings::current_dir();
        assert_eq!(s.paths, vec!["."]);
    }

    #[test]
    fn scan_settings_for_paths() {
        let s = ScanSettings::for_paths(vec!["src".into(), "lib".into()]);
        assert_eq!(s.paths.len(), 2);
    }

    #[test]
    fn scan_settings_flatten() {
        // Verify that ScanOptions fields are accessible through ScanSettings
        let s = ScanSettings {
            paths: vec![".".into()],
            options: ScanOptions {
                hidden: true,
                ..Default::default()
            },
        };
        assert!(s.options.hidden);
    }

    #[test]
    fn serde_roundtrip_scan_options() {
        let opts = ScanOptions {
            excluded: vec!["target".into()],
            config: ConfigMode::None,
            hidden: true,
            no_ignore: false,
            no_ignore_parent: true,
            no_ignore_dot: false,
            no_ignore_vcs: true,
            treat_doc_strings_as_comments: true,
        };
        let json = serde_json::to_string(&opts).unwrap();
        let back: ScanOptions = serde_json::from_str(&json).unwrap();
        assert_eq!(back.excluded, opts.excluded);
        assert!(back.hidden);
        assert!(back.no_ignore_parent);
        assert!(back.no_ignore_vcs);
        assert!(back.treat_doc_strings_as_comments);
    }

    #[test]
    fn serde_roundtrip_scan_settings() {
        let s = ScanSettings {
            paths: vec!["src".into()],
            options: ScanOptions {
                excluded: vec!["*.bak".into()],
                ..Default::default()
            },
        };
        let json = serde_json::to_string(&s).unwrap();
        let back: ScanSettings = serde_json::from_str(&json).unwrap();
        assert_eq!(back.paths, s.paths);
        assert_eq!(back.options.excluded, s.options.excluded);
    }

    #[test]
    fn serde_roundtrip_lang_settings() {
        let s = LangSettings {
            top: 10,
            files: true,
            children: ChildrenMode::Separate,
            redact: Some(RedactMode::Paths),
        };
        let json = serde_json::to_string(&s).unwrap();
        let back: LangSettings = serde_json::from_str(&json).unwrap();
        assert_eq!(back.top, 10);
        assert!(back.files);
    }

    #[test]
    fn serde_roundtrip_export_settings() {
        let s = ExportSettings::default();
        let json = serde_json::to_string(&s).unwrap();
        let back: ExportSettings = serde_json::from_str(&json).unwrap();
        assert_eq!(back.min_code, 0);
        assert!(back.meta);
    }

    #[test]
    fn serde_roundtrip_analyze_settings() {
        let s = AnalyzeSettings::default();
        let json = serde_json::to_string(&s).unwrap();
        let back: AnalyzeSettings = serde_json::from_str(&json).unwrap();
        assert_eq!(back.preset, "receipt");
        assert_eq!(back.granularity, "module");
    }

    #[test]
    fn serde_roundtrip_cockpit_settings() {
        let s = CockpitSettings::default();
        let json = serde_json::to_string(&s).unwrap();
        let back: CockpitSettings = serde_json::from_str(&json).unwrap();
        assert_eq!(back.base, "main");
        assert_eq!(back.head, "HEAD");
        assert_eq!(back.range_mode, "two-dot");
        assert!(back.baseline.is_none());
    }

    #[test]
    fn serde_roundtrip_cockpit_settings_with_baseline() {
        let s = CockpitSettings {
            base: "v1.0".into(),
            head: "feature".into(),
            range_mode: "three-dot".into(),
            baseline: Some("baseline.json".into()),
        };
        let json = serde_json::to_string(&s).unwrap();
        let back: CockpitSettings = serde_json::from_str(&json).unwrap();
        assert_eq!(back.base, "v1.0");
        assert_eq!(back.baseline, Some("baseline.json".to_string()));
    }

    #[test]
    fn serde_roundtrip_diff_settings() {
        let s = DiffSettings {
            from: "v1.0".into(),
            to: "v2.0".into(),
        };
        let json = serde_json::to_string(&s).unwrap();
        let back: DiffSettings = serde_json::from_str(&json).unwrap();
        assert_eq!(back.from, "v1.0");
        assert_eq!(back.to, "v2.0");
    }

    #[test]
    fn toml_parse_and_view_profiles() {
        let toml_str = r#"
[scan]
hidden = true

[view.llm]
format = "json"
top = 10
"#;
        let config = TomlConfig::parse(toml_str).expect("parse config");
        assert_eq!(config.scan.hidden, Some(true));
        let llm = config.view.get("llm").expect("llm profile");
        assert_eq!(llm.format.as_deref(), Some("json"));
        assert_eq!(llm.top, Some(10));
    }

    #[test]
    fn toml_from_file_roundtrip() {
        let toml_content = r#"
[module]
depth = 3
roots = ["src", "tests"]
"#;

        let mut temp_file = NamedTempFile::new().expect("temp file");
        temp_file
            .write_all(toml_content.as_bytes())
            .expect("write config");

        let config = TomlConfig::from_file(temp_file.path()).expect("load config");
        assert_eq!(config.module.depth, Some(3));
        assert_eq!(
            config.module.roots,
            Some(vec!["src".to_string(), "tests".to_string()])
        );
    }
}