batless 0.5.0

A non-blocking, LLM-friendly code viewer inspired by bat
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
//! Configuration management for batless
//!
//! This module handles all configuration-related functionality including
//! default values, validation, and configuration parsing.

use crate::config_validation::validate_config;
use crate::error::{BatlessError, BatlessResult};
use crate::summary::SummaryLevel;
use crate::traits::ProcessingConfig;
use serde::{Deserialize, Serialize};

/// Strategy for splitting streaming chunks
#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, Hash)]
#[serde(rename_all = "lowercase")]
pub enum ChunkStrategy {
    /// Split at fixed line counts (default)
    #[default]
    Line,
    /// Split at top-level declaration boundaries using tree-sitter (falls back to line-based for
    /// unsupported languages)
    Semantic,
}
use std::fs;
use std::path::{Path, PathBuf};

/// Configuration structure for batless operations
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct BatlessConfig {
    /// Maximum number of lines to process
    #[serde(default = "default_max_lines")]
    pub max_lines: usize,
    /// Maximum number of bytes to process (optional)
    #[serde(default)]
    pub max_bytes: Option<usize>,
    /// Override language detection with specific language
    #[serde(default)]
    pub language: Option<String>,
    /// Theme name for syntax highlighting
    #[serde(default = "default_theme")]
    pub theme: String,
    /// Whether to strip ANSI escape sequences
    #[serde(default)]
    pub strip_ansi: bool,
    /// Whether to use color output
    #[serde(default = "default_use_color")]
    pub use_color: bool,
    /// Whether to include tokens in JSON output
    #[serde(default)]
    pub include_tokens: bool,
    /// Summary extraction level
    #[serde(default)]
    pub summary_level: SummaryLevel,
    /// Whether to enable summary mode (deprecated, use summary_level)
    #[serde(default)]
    pub summary_mode: bool,
    /// Enable streaming JSON output for large files
    #[serde(default)]
    pub streaming_json: bool,
    /// Chunk size for streaming output (in lines)
    #[serde(default = "default_streaming_chunk_size")]
    pub streaming_chunk_size: usize,
    /// Enable resume capability with checkpoint support
    #[serde(default)]
    pub enable_resume: bool,
    /// Schema version for JSON output compatibility
    #[serde(default = "default_schema_version")]
    pub schema_version: String,
    /// Enable debug mode with detailed processing information
    #[serde(default)]
    pub debug: bool,
    /// Show line numbers (cat -n compatibility)
    #[serde(default)]
    pub show_line_numbers: bool,
    /// Show line numbers for non-blank lines only (cat -b compatibility)
    #[serde(default)]
    pub show_line_numbers_nonblank: bool,
    /// Pretty print JSON output (non-streaming JSON mode)
    #[serde(default)]
    pub pretty_json: bool,
    /// Include 1-based line numbers in JSON output lines array
    #[serde(default)]
    pub json_line_numbers: bool,
    /// Compute and include SHA-256 file hash in JSON output
    #[serde(default)]
    pub hash: bool,
    /// Strip comment-only lines from output
    #[serde(default)]
    pub strip_comments: bool,
    /// Strip blank lines from output
    #[serde(default)]
    pub strip_blank_lines: bool,
    /// Strategy for splitting streaming chunks
    #[serde(default)]
    pub chunk_strategy: ChunkStrategy,
}

fn default_max_lines() -> usize {
    10000
}

fn default_theme() -> String {
    "base16-ocean.dark".to_string()
}

fn default_use_color() -> bool {
    true
}

fn default_streaming_chunk_size() -> usize {
    1000
}

fn default_schema_version() -> String {
    "2.1".to_string()
}

impl Default for BatlessConfig {
    fn default() -> Self {
        Self {
            max_lines: 10000,
            max_bytes: None,
            language: None,
            theme: "base16-ocean.dark".to_string(),
            strip_ansi: false,
            use_color: true,
            include_tokens: false,
            summary_level: SummaryLevel::None,
            summary_mode: false,
            streaming_json: false,
            streaming_chunk_size: default_streaming_chunk_size(),
            enable_resume: false,
            schema_version: default_schema_version(),
            debug: false,
            show_line_numbers: false,
            show_line_numbers_nonblank: false,
            pretty_json: false,
            json_line_numbers: false,
            hash: false,
            strip_comments: false,
            strip_blank_lines: false,
            chunk_strategy: ChunkStrategy::Line,
        }
    }
}

impl BatlessConfig {
    /// Create a new configuration with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Set maximum lines
    pub fn with_max_lines(mut self, max_lines: usize) -> Self {
        self.max_lines = max_lines;
        self
    }

    /// Set maximum bytes
    pub fn with_max_bytes(mut self, max_bytes: Option<usize>) -> Self {
        self.max_bytes = max_bytes;
        self
    }

    /// Set language override
    pub fn with_language(mut self, language: Option<String>) -> Self {
        self.language = language;
        self
    }

    /// Set theme
    pub fn with_theme(mut self, theme: String) -> Self {
        self.theme = theme;
        self
    }

    /// Set ANSI stripping
    pub fn with_strip_ansi(mut self, strip_ansi: bool) -> Self {
        self.strip_ansi = strip_ansi;
        self
    }

    /// Set color usage
    pub fn with_use_color(mut self, use_color: bool) -> Self {
        self.use_color = use_color;
        self
    }

    /// Set token inclusion
    pub fn with_include_tokens(mut self, include_tokens: bool) -> Self {
        self.include_tokens = include_tokens;
        self
    }

    /// Set summary mode
    pub fn with_summary_mode(mut self, summary_mode: bool) -> Self {
        self.summary_mode = summary_mode;
        // For backward compatibility, map boolean to SummaryLevel
        if summary_mode {
            self.summary_level = SummaryLevel::Standard;
        } else {
            self.summary_level = SummaryLevel::None;
        }
        self
    }

    /// Set summary level
    pub fn with_summary_level(mut self, summary_level: SummaryLevel) -> Self {
        // Update deprecated summary_mode for backward compatibility
        self.summary_mode = summary_level.is_enabled();
        self.summary_level = summary_level;
        self
    }

    /// Enable streaming JSON output
    pub fn with_streaming_json(mut self, streaming_json: bool) -> Self {
        self.streaming_json = streaming_json;
        self
    }

    /// Set streaming chunk size
    pub fn with_streaming_chunk_size(mut self, chunk_size: usize) -> Self {
        self.streaming_chunk_size = chunk_size;
        self
    }

    /// Enable resume capability
    pub fn with_enable_resume(mut self, enable_resume: bool) -> Self {
        self.enable_resume = enable_resume;
        self
    }

    /// Set schema version
    pub fn with_schema_version(mut self, version: String) -> Self {
        self.schema_version = version;
        self
    }

    /// Enable debug mode
    pub fn with_debug(mut self, debug: bool) -> Self {
        self.debug = debug;
        self
    }

    /// Enable line numbering (cat -n compatibility)
    pub fn with_show_line_numbers(mut self, show_line_numbers: bool) -> Self {
        self.show_line_numbers = show_line_numbers;
        self
    }

    /// Enable line numbering for non-blank lines only (cat -b compatibility)
    pub fn with_show_line_numbers_nonblank(mut self, show_line_numbers_nonblank: bool) -> Self {
        self.show_line_numbers_nonblank = show_line_numbers_nonblank;
        self
    }

    /// Enable pretty JSON output
    pub fn with_pretty_json(mut self, pretty: bool) -> Self {
        self.pretty_json = pretty;
        self
    }

    /// Include 1-based line numbers in JSON output lines array
    pub fn with_json_line_numbers(mut self, enabled: bool) -> Self {
        self.json_line_numbers = enabled;
        self
    }

    /// Compute and include SHA-256 file hash in JSON output
    pub fn with_hash(mut self, enabled: bool) -> Self {
        self.hash = enabled;
        self
    }

    /// Strip comment-only lines from output
    pub fn with_strip_comments(mut self, enabled: bool) -> Self {
        self.strip_comments = enabled;
        self
    }

    /// Strip blank lines from output
    pub fn with_strip_blank_lines(mut self, enabled: bool) -> Self {
        self.strip_blank_lines = enabled;
        self
    }

    /// Set streaming chunk strategy
    pub fn with_chunk_strategy(mut self, strategy: ChunkStrategy) -> Self {
        self.chunk_strategy = strategy;
        self
    }

    /// Get effective summary level (considering both new and deprecated fields)
    pub fn effective_summary_level(&self) -> SummaryLevel {
        // Priority: summary_level takes precedence over deprecated summary_mode
        if self.summary_level != SummaryLevel::None {
            self.summary_level
        } else if self.summary_mode {
            SummaryLevel::Standard
        } else {
            SummaryLevel::None
        }
    }

    /// Validate the configuration
    ///
    /// Delegates to [`crate::config_validation::validate_config`] for the actual checks.
    pub fn validate(&self) -> BatlessResult<()> {
        validate_config(self)
    }

    /// Check if color output should be used based on configuration and environment
    pub fn should_use_color(&self, is_terminal: bool) -> bool {
        self.use_color && is_terminal
    }

    /// Get the effective maximum lines (considering both line and byte limits)
    pub fn effective_max_lines(&self) -> usize {
        self.max_lines
    }

    /// Check if byte limiting is enabled
    pub fn has_byte_limit(&self) -> bool {
        self.max_bytes.is_some()
    }

    /// Get byte limit if set
    pub fn get_byte_limit(&self) -> Option<usize> {
        self.max_bytes
    }

    /// Load configuration from a TOML file
    pub fn from_file<P: AsRef<Path>>(path: P) -> BatlessResult<Self> {
        let content = fs::read_to_string(path.as_ref()).map_err(|e| {
            BatlessError::config_error_with_help(
                format!(
                    "Failed to read config file '{}': {}",
                    path.as_ref().display(),
                    e
                ),
                Some("Check that the file exists and has proper permissions".to_string()),
            )
        })?;

        let config: BatlessConfig = toml::from_str(&content).map_err(|e| {
            BatlessError::config_error_with_help(
                format!(
                    "Failed to parse config file '{}': {}",
                    path.as_ref().display(),
                    e
                ),
                Some("Check the TOML syntax - use 'batless --help' for valid options".to_string()),
            )
        })?;

        config.validate()?;
        Ok(config)
    }

    /// Load configuration from JSON file (.batlessrc format)
    pub fn from_json_file<P: AsRef<Path>>(path: P) -> BatlessResult<Self> {
        let content = fs::read_to_string(path.as_ref()).map_err(|e| {
            BatlessError::config_error_with_help(
                format!(
                    "Failed to read config file '{}': {}",
                    path.as_ref().display(),
                    e
                ),
                Some("Check that the file exists and has proper permissions".to_string()),
            )
        })?;

        let config: BatlessConfig = serde_json::from_str(&content).map_err(|e| {
            BatlessError::config_error_with_help(
                format!(
                    "Failed to parse config file '{}': {}",
                    path.as_ref().display(),
                    e
                ),
                Some("Check the JSON syntax - use 'batless --help' for valid options".to_string()),
            )
        })?;

        config.validate()?;
        Ok(config)
    }

    /// Save configuration to a TOML file
    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> BatlessResult<()> {
        let content = toml::to_string_pretty(self).map_err(|e| {
            BatlessError::config_error_with_help(
                format!("Failed to serialize config: {e}"),
                Some("This is likely a bug - please report it".to_string()),
            )
        })?;

        fs::write(path.as_ref(), content).map_err(|e| {
            BatlessError::config_error_with_help(
                format!(
                    "Failed to write config file '{}': {}",
                    path.as_ref().display(),
                    e
                ),
                Some("Check that the directory exists and has write permissions".to_string()),
            )
        })
    }

    /// Find configuration files in standard locations
    /// Returns a list of config file paths in order of precedence (highest first)
    pub fn find_config_files() -> Vec<PathBuf> {
        let mut paths = Vec::new();

        // 1. Project-level config files (highest precedence)
        paths.push(PathBuf::from(".batlessrc"));
        paths.push(PathBuf::from("batless.toml"));

        // 2. User home directory config files
        if let Some(home_dir) = dirs::home_dir() {
            paths.push(home_dir.join(".batlessrc"));
            paths.push(home_dir.join(".config/batless/config.toml"));
            paths.push(home_dir.join(".config/batless.toml"));
        }

        // 3. System config directories (lowest precedence)
        if let Some(config_dir) = dirs::config_dir() {
            paths.push(config_dir.join("batless/config.toml"));
        }

        paths
    }

    /// Load configuration with precedence: CLI args > project config > user config > defaults
    pub fn load_with_precedence() -> BatlessResult<Self> {
        let mut config = Self::default();

        // Try to load from config files in reverse precedence order
        for config_path in Self::find_config_files().into_iter().rev() {
            if config_path.exists() {
                let file_config = if config_path.extension() == Some(std::ffi::OsStr::new("toml")) {
                    Self::from_file(&config_path)?
                } else {
                    Self::from_json_file(&config_path)?
                };
                config = config.merge_with(file_config);
            }
        }

        Ok(config)
    }

    /// Merge this configuration with another, taking non-default values from the other
    pub fn merge_with(mut self, other: Self) -> Self {
        let default = Self::default();

        // Only update if the other value is different from default
        if other.max_lines != default.max_lines {
            self.max_lines = other.max_lines;
        }
        if other.max_bytes != default.max_bytes {
            self.max_bytes = other.max_bytes;
        }
        if other.language != default.language {
            self.language = other.language;
        }
        if other.theme != default.theme {
            self.theme = other.theme;
        }
        if other.strip_ansi != default.strip_ansi {
            self.strip_ansi = other.strip_ansi;
        }
        if other.use_color != default.use_color {
            self.use_color = other.use_color;
        }
        if other.include_tokens != default.include_tokens {
            self.include_tokens = other.include_tokens;
        }
        if other.summary_mode != default.summary_mode {
            self.summary_mode = other.summary_mode;
        }
        if other.summary_level != default.summary_level {
            self.summary_level = other.summary_level;
        }
        if other.streaming_json != default.streaming_json {
            self.streaming_json = other.streaming_json;
        }
        if other.streaming_chunk_size != default.streaming_chunk_size {
            self.streaming_chunk_size = other.streaming_chunk_size;
        }
        if other.enable_resume != default.enable_resume {
            self.enable_resume = other.enable_resume;
        }
        if other.schema_version != default.schema_version {
            self.schema_version = other.schema_version;
        }
        if other.debug != default.debug {
            self.debug = other.debug;
        }
        if other.show_line_numbers != default.show_line_numbers {
            self.show_line_numbers = other.show_line_numbers;
        }
        if other.show_line_numbers_nonblank != default.show_line_numbers_nonblank {
            self.show_line_numbers_nonblank = other.show_line_numbers_nonblank;
        }
        if other.pretty_json != default.pretty_json {
            self.pretty_json = other.pretty_json;
        }
        if other.json_line_numbers != default.json_line_numbers {
            self.json_line_numbers = other.json_line_numbers;
        }
        if other.hash != default.hash {
            self.hash = other.hash;
        }
        if other.strip_comments != default.strip_comments {
            self.strip_comments = other.strip_comments;
        }
        if other.strip_blank_lines != default.strip_blank_lines {
            self.strip_blank_lines = other.strip_blank_lines;
        }
        if other.chunk_strategy != default.chunk_strategy {
            self.chunk_strategy = other.chunk_strategy;
        }

        self
    }
}

impl ProcessingConfig for BatlessConfig {
    fn max_lines(&self) -> usize {
        self.max_lines
    }

    fn max_bytes(&self) -> Option<usize> {
        self.max_bytes
    }

    fn language(&self) -> Option<&str> {
        self.language.as_deref()
    }

    fn summary_mode(&self) -> bool {
        self.summary_mode
    }

    fn include_tokens(&self) -> bool {
        self.include_tokens
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{profile::CustomProfile, summary::SummaryLevel};

    #[test]
    fn test_default_config() {
        let config = BatlessConfig::default();
        assert_eq!(config.max_lines, 10000);
        assert_eq!(config.max_bytes, None);
        assert_eq!(config.language, None);
        assert_eq!(config.theme, "base16-ocean.dark");
        assert!(!config.strip_ansi);
        assert!(config.use_color);
        assert!(!config.include_tokens);
        assert!(!config.summary_mode);
    }

    #[test]
    fn test_builder_pattern() {
        let config = BatlessConfig::new()
            .with_max_lines(5000)
            .with_max_bytes(Some(1024))
            .with_language(Some("rust".to_string()))
            .with_theme("monokai".to_string())
            .with_strip_ansi(true)
            .with_use_color(false)
            .with_include_tokens(true)
            .with_summary_mode(true);

        assert_eq!(config.max_lines, 5000);
        assert_eq!(config.max_bytes, Some(1024));
        assert_eq!(config.language, Some("rust".to_string()));
        assert_eq!(config.theme, "monokai");
        assert!(config.strip_ansi);
        assert!(!config.use_color);
        assert!(config.include_tokens);
        assert!(config.summary_mode);
    }

    #[test]
    fn test_validate_delegates_to_config_validation() {
        // Smoke test: validate() delegates to config_validation module
        assert!(BatlessConfig::default().validate().is_ok());
        assert!(BatlessConfig::default()
            .with_max_lines(0)
            .validate()
            .is_err());
    }

    #[test]
    fn test_should_use_color() {
        let config = BatlessConfig::default();
        assert!(config.should_use_color(true));
        assert!(!config.should_use_color(false));

        let config_no_color = config.with_use_color(false);
        assert!(!config_no_color.should_use_color(true));
        assert!(!config_no_color.should_use_color(false));
    }

    #[test]
    fn test_byte_limit_helpers() {
        let config = BatlessConfig::default();
        assert!(!config.has_byte_limit());
        assert_eq!(config.get_byte_limit(), None);

        let config_with_limit = config.with_max_bytes(Some(1024));
        assert!(config_with_limit.has_byte_limit());
        assert_eq!(config_with_limit.get_byte_limit(), Some(1024));
    }

    #[test]
    fn test_toml_serialization() {
        let config = BatlessConfig::default()
            .with_max_lines(5000)
            .with_theme("monokai".to_string());

        let toml_str = toml::to_string_pretty(&config).unwrap();
        assert!(toml_str.contains("max_lines = 5000"));
        assert!(toml_str.contains("theme = \"monokai\""));

        let deserialized: BatlessConfig = toml::from_str(&toml_str).unwrap();
        assert_eq!(deserialized.max_lines, 5000);
        assert_eq!(deserialized.theme, "monokai");
    }

    #[test]
    fn test_json_serialization() {
        let config = BatlessConfig::default()
            .with_max_lines(3000)
            .with_include_tokens(true);

        let json_str = serde_json::to_string_pretty(&config).unwrap();
        let deserialized: BatlessConfig = serde_json::from_str(&json_str).unwrap();
        assert_eq!(deserialized.max_lines, 3000);
        assert!(deserialized.include_tokens);
    }

    #[test]
    fn test_merge_with() {
        let base = BatlessConfig::default();
        let override_config = BatlessConfig::default()
            .with_max_lines(2000)
            .with_theme("solarized".to_string())
            .with_summary_level(SummaryLevel::Detailed)
            .with_streaming_json(true)
            .with_streaming_chunk_size(42)
            .with_enable_resume(true)
            .with_schema_version("9.9".to_string())
            .with_debug(true)
            .with_show_line_numbers(true)
            .with_show_line_numbers_nonblank(true)
            .with_pretty_json(true);

        let merged = base.merge_with(override_config);
        assert_eq!(merged.max_lines, 2000);
        assert_eq!(merged.theme, "solarized");
        assert_eq!(merged.summary_level, SummaryLevel::Detailed);
        assert!(merged.streaming_json);
        assert_eq!(merged.streaming_chunk_size, 42);
        assert!(merged.enable_resume);
        assert_eq!(merged.schema_version, "9.9");
        assert!(merged.debug);
        assert!(merged.show_line_numbers);
        assert!(merged.show_line_numbers_nonblank);
        assert!(merged.pretty_json);
        // Other values should remain default
        assert!(!merged.strip_ansi);
        assert!(merged.use_color);
    }

    #[test]
    fn test_config_file_discovery() {
        let paths = BatlessConfig::find_config_files();
        assert!(!paths.is_empty());
        assert!(paths
            .iter()
            .any(|p| p.file_name() == Some(std::ffi::OsStr::new(".batlessrc"))));
        assert!(paths
            .iter()
            .any(|p| p.file_name() == Some(std::ffi::OsStr::new("batless.toml"))));
    }

    #[test]
    fn test_load_from_toml_file() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let toml_content = r#"
max_lines = 15000
theme = "zenburn"
use_color = false
summary_mode = true
"#;

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(toml_content.as_bytes()).unwrap();

        let config = BatlessConfig::from_file(temp_file.path()).unwrap();
        assert_eq!(config.max_lines, 15000);
        assert_eq!(config.theme, "zenburn");
        assert!(!config.use_color);
        assert!(config.summary_mode);
    }

    #[test]
    fn test_load_from_json_file() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let json_content = r#"{
  "max_lines": 8000,
  "theme": "github",
  "include_tokens": true,
  "strip_ansi": true
}"#;

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(json_content.as_bytes()).unwrap();

        let config = BatlessConfig::from_json_file(temp_file.path()).unwrap();
        assert_eq!(config.max_lines, 8000);
        assert_eq!(config.theme, "github");
        assert!(config.include_tokens);
        assert!(config.strip_ansi);
    }

    #[test]
    fn test_invalid_toml_config() {
        use std::io::Write;
        use tempfile::NamedTempFile;

        let invalid_toml = r#"
max_lines = "not_a_number"
"#;

        let mut temp_file = NamedTempFile::new().unwrap();
        temp_file.write_all(invalid_toml.as_bytes()).unwrap();

        let result = BatlessConfig::from_file(temp_file.path());
        assert!(result.is_err());
    }

    #[test]
    fn test_save_to_file() {
        use tempfile::NamedTempFile;

        let config = BatlessConfig::default()
            .with_max_lines(7000)
            .with_theme("dracula".to_string());

        let temp_file = NamedTempFile::new().unwrap();
        config.save_to_file(temp_file.path()).unwrap();

        let loaded_config = BatlessConfig::from_file(temp_file.path()).unwrap();
        assert_eq!(loaded_config.max_lines, 7000);
        assert_eq!(loaded_config.theme, "dracula");
    }

    // Custom Profile Tests
    #[test]
    fn test_custom_profile_creation() {
        let profile = CustomProfile::new(
            "test-profile".to_string(),
            Some("A test profile for unit testing".to_string()),
        );

        assert_eq!(profile.name, "test-profile");
        assert_eq!(
            profile.description,
            Some("A test profile for unit testing".to_string())
        );
        assert_eq!(profile.version, "1.0");
        assert!(profile.max_lines.is_none());
        assert!(profile.max_bytes.is_none());
        assert!(profile.tags.is_empty());
    }

    #[test]
    fn test_custom_profile_apply_to_config() {
        let profile = CustomProfile {
            name: "coding-profile".to_string(),
            description: None,
            version: "1.0".to_string(),
            max_lines: Some(2500),
            max_bytes: Some(50000),
            language: Some("rust".to_string()),
            theme: Some("zenburn".to_string()),
            strip_ansi: Some(true),
            use_color: Some(false),
            include_tokens: Some(true),
            summary_level: Some(SummaryLevel::Standard),
            output_mode: Some("json".to_string()),
            ai_model: Some("gpt4-turbo".to_string()),
            streaming_json: Some(false),
            streaming_chunk_size: Some(1000),
            enable_resume: Some(false),
            debug: Some(false),
            tags: vec!["coding".to_string(), "development".to_string()],
            created_at: None,
            updated_at: None,
        };

        let base_config = BatlessConfig::default();
        let applied_config = profile.apply_to_config(base_config);

        assert_eq!(applied_config.max_lines, 2500);
        assert_eq!(applied_config.max_bytes, Some(50000));
        assert_eq!(applied_config.language, Some("rust".to_string()));
        assert_eq!(applied_config.theme, "zenburn");
        assert!(applied_config.strip_ansi);
        assert!(!applied_config.use_color);
        assert!(applied_config.include_tokens);
        assert_eq!(applied_config.summary_level, SummaryLevel::Standard);
    }

    #[test]
    fn test_custom_profile_partial_application() {
        let profile = CustomProfile {
            name: "minimal-profile".to_string(),
            description: None,
            version: "1.0".to_string(),
            max_lines: Some(1000),
            max_bytes: None,
            language: None,
            theme: None,
            strip_ansi: None,
            use_color: None,
            include_tokens: None,
            summary_level: None,
            output_mode: None,
            ai_model: None,
            streaming_json: None,
            streaming_chunk_size: None,
            enable_resume: None,
            debug: None,
            tags: Vec::new(),
            created_at: None,
            updated_at: None,
        };

        let base_config = BatlessConfig::default()
            .with_theme("monokai".to_string())
            .with_use_color(false);

        let applied_config = profile.apply_to_config(base_config);

        // Profile should only override max_lines
        assert_eq!(applied_config.max_lines, 1000);
        assert_eq!(applied_config.theme, "monokai"); // Unchanged
        assert!(!applied_config.use_color); // Unchanged
    }

    #[test]
    fn test_custom_profile_validation() {
        // Valid profile
        let valid_profile = CustomProfile::new(
            "valid-profile".to_string(),
            Some("A valid profile".to_string()),
        );
        assert!(valid_profile.validate().is_ok());

        // Empty name
        let empty_name_profile = CustomProfile::new(String::new(), None);
        assert!(empty_name_profile.validate().is_err());

        // Name too long
        let long_name_profile = CustomProfile::new("a".repeat(60), None);
        assert!(long_name_profile.validate().is_err());
    }

    #[test]
    fn test_custom_profile_output_mode_preference() {
        let profile = CustomProfile {
            name: "test".to_string(),
            description: None,
            version: "1.0".to_string(),
            max_lines: None,
            max_bytes: None,
            language: None,
            theme: None,
            strip_ansi: None,
            use_color: None,
            include_tokens: None,
            summary_level: None,
            output_mode: Some("summary".to_string()),
            ai_model: Some("claude35-sonnet".to_string()),
            streaming_json: None,
            streaming_chunk_size: None,
            enable_resume: None,
            debug: None,
            tags: Vec::new(),
            created_at: None,
            updated_at: None,
        };

        assert_eq!(profile.get_output_mode(), Some("summary"));
        assert_eq!(profile.get_ai_model(), Some("claude35-sonnet"));
    }

    #[test]
    fn test_custom_profile_json_serialization() {
        let profile = CustomProfile::new(
            "test-profile".to_string(),
            Some("Test description".to_string()),
        );

        let json_str = serde_json::to_string_pretty(&profile).unwrap();
        let deserialized: CustomProfile = serde_json::from_str(&json_str).unwrap();

        assert_eq!(deserialized.name, profile.name);
        assert_eq!(deserialized.description, profile.description);
        assert_eq!(deserialized.version, profile.version);
    }

    #[test]
    fn test_custom_profile_discover_profiles() {
        // This test just ensures the function runs without panicking
        // In a real environment, it would find actual profile files
        let profiles = CustomProfile::discover_profiles();
        // Should return a Vec (even if empty, which is fine for testing)
        assert!(profiles.is_empty() || !profiles.is_empty());
    }
}