kelora 0.4.0

A command-line log analysis tool with embedded Rhai scripting
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
#![allow(dead_code)]
use clap::ValueEnum;

/// Main configuration struct for Kelora
#[derive(Debug, Clone)]
pub struct KeloraConfig {
    pub input: InputConfig,
    pub output: OutputConfig,
    pub processing: ProcessingConfig,
    pub performance: PerformanceConfig,
}

/// Input configuration
#[derive(Debug, Clone)]
pub struct InputConfig {
    pub files: Vec<String>,
    pub format: InputFormat,
    pub file_order: FileOrder,
    pub skip_lines: usize,
    pub ignore_lines: Option<regex::Regex>,
    pub keep_lines: Option<regex::Regex>,
    pub multiline: Option<MultilineConfig>,
    /// Custom timestamp field name (reserved for --since/--until features)
    #[allow(dead_code)]
    pub ts_field: Option<String>,
    /// Custom timestamp format string
    pub ts_format: Option<String>,
    /// Default timezone for naive timestamps (None = local time)
    pub default_timezone: Option<String>,
    /// Extract text before separator to specified field (runs before parsing)
    pub extract_prefix: Option<String>,
    /// Separator string for prefix extraction (default: pipe '|')
    pub prefix_sep: String,
}

/// Output configuration
#[derive(Debug, Clone)]
pub struct OutputConfig {
    pub format: OutputFormat,
    pub keys: Vec<String>,
    pub exclude_keys: Vec<String>,
    pub core: bool,
    pub brief: bool,
    pub wrap: bool,
    pub color: ColorMode,
    pub no_emoji: bool,
    pub stats: bool,
    pub metrics: bool,
    pub metrics_file: Option<String>,
    pub mark_gaps: Option<chrono::Duration>,
    /// Timestamp formatting configuration (display-only)
    pub timestamp_formatting: TimestampFormatConfig,
}

/// Ordered script stages that preserve CLI order
#[derive(Debug, Clone)]
pub enum ScriptStageType {
    Filter(String),
    Exec(String),
}

/// Error reporting configuration
#[derive(Debug, Clone)]
pub struct ErrorReportConfig {
    pub style: ErrorReportStyle,
}

#[derive(Debug, Clone)]
pub enum ErrorReportStyle {
    Off,
    Summary,
    Print,
}

/// Processing configuration
#[derive(Debug, Clone)]
pub struct ProcessingConfig {
    pub begin: Option<String>,
    pub stages: Vec<ScriptStageType>,
    pub end: Option<String>,
    pub error_report: ErrorReportConfig,
    pub levels: Vec<String>,
    pub exclude_levels: Vec<String>,
    /// Window size for sliding window functionality (0 = disabled)
    pub window_size: usize,
    /// Timestamp filtering configuration
    pub timestamp_filter: Option<TimestampFilterConfig>,
    /// Limit output to the first N events (None = no limit)
    pub take_limit: Option<usize>,
    /// Exit on first error (fail-fast behavior) - new resiliency model
    pub strict: bool,
    /// Show detailed error information (levels: 0-3) - new resiliency model
    pub verbose: u8,
    /// Quiet mode level (0=normal, 1=suppress diagnostics, 2=suppress events, 3=suppress script output)
    pub quiet_level: u8,
}

/// Performance configuration
#[derive(Debug, Clone)]
pub struct PerformanceConfig {
    pub parallel: bool,
    pub threads: usize,
    pub batch_size: Option<usize>,
    pub batch_timeout: u64,
    pub no_preserve_order: bool,
}

/// Input format enumeration
#[derive(ValueEnum, Clone, Debug, PartialEq)]
pub enum InputFormat {
    Auto,
    Json,
    Line,
    Raw,
    Logfmt,
    Syslog,
    Cef,
    Csv,
    Tsv,
    Csvnh,
    Tsvnh,
    Combined,
}

/// Output format enumeration
#[derive(ValueEnum, Clone, Debug, Default)]
pub enum OutputFormat {
    Json,
    #[default]
    Default,
    Logfmt,
    Inspect,
    Levelmap,
    Csv,
    Tsv,
    Csvnh,
    Tsvnh,
    None,
}

/// File processing order
#[derive(ValueEnum, Clone, Debug)]
pub enum FileOrder {
    Cli,
    Name,
    Mtime,
}

/// Color output mode
#[derive(ValueEnum, Clone, Debug)]
pub enum ColorMode {
    Auto,
    Always,
    Never,
}

/// Timestamp filtering configuration
#[derive(Debug, Clone)]
pub struct TimestampFilterConfig {
    pub since: Option<chrono::DateTime<chrono::Utc>>,
    pub until: Option<chrono::DateTime<chrono::Utc>>,
}

/// Timestamp formatting configuration (display-only, affects default output format only)
#[derive(Debug, Clone, Default)]
pub struct TimestampFormatConfig {
    /// Specific fields to format as timestamps
    pub format_fields: Vec<String>,
    /// Auto-format all known timestamp fields
    pub auto_format_all: bool,
    /// Target timezone for formatting (true = UTC, false = local)
    pub format_as_utc: bool,
}

/// Multi-line event detection configuration
#[derive(Debug, Clone)]
pub struct MultilineConfig {
    pub strategy: MultilineStrategy,
}

/// Multi-line event detection strategies
#[derive(Debug, Clone)]
pub enum MultilineStrategy {
    /// Events start with timestamp pattern
    Timestamp { pattern: String },
    /// Continuation lines are indented
    Indent {
        spaces: Option<u32>,
        tabs: bool,
        mixed: bool,
    },
    /// Lines end with continuation character
    Backslash { char: char },
    /// Events start with pattern
    Start { pattern: String },
    /// Events end with pattern
    End { pattern: String },
    /// Events have both start and end boundaries
    Boundary { start: String, end: String },
    /// Read entire input as a single event
    Whole,
}

impl MultilineConfig {
    /// Parse multiline configuration from CLI string
    pub fn parse(value: &str) -> Result<Self, String> {
        let parts: Vec<&str> = value.split(':').collect();

        if parts.is_empty() {
            return Err("Empty multiline configuration".to_string());
        }

        let strategy_name = parts[0];
        let strategy = match strategy_name {
            "timestamp" => {
                let pattern = if parts.len() > 1 {
                    Self::parse_pattern_option(parts[1])?
                } else {
                    // Default timestamp patterns (ISO and syslog) - both anchored to start
                    r"^(\d{4}-\d{2}-\d{2}|\w{3}\s+\d{1,2})".to_string()
                };
                MultilineStrategy::Timestamp { pattern }
            }
            "indent" => {
                let (spaces, tabs, mixed) = if parts.len() > 1 {
                    Self::parse_indent_options(parts[1])?
                } else {
                    (None, false, true) // Default: any whitespace
                };
                MultilineStrategy::Indent {
                    spaces,
                    tabs,
                    mixed,
                }
            }
            "backslash" => {
                let char = if parts.len() > 1 {
                    Self::parse_char_option(parts[1])?
                } else {
                    '\\' // Default backslash
                };
                MultilineStrategy::Backslash { char }
            }
            "start" => {
                if parts.len() < 2 {
                    return Err("Start strategy requires pattern: start:REGEX".to_string());
                }
                let pattern = parts[1].to_string();
                MultilineStrategy::Start { pattern }
            }
            "end" => {
                if parts.len() < 2 {
                    return Err("End strategy requires pattern: end:REGEX".to_string());
                }
                let pattern = parts[1].to_string();
                MultilineStrategy::End { pattern }
            }
            "boundary" => {
                if parts.len() < 2 {
                    return Err(
                        "Boundary strategy requires start and end: boundary:start=REGEX:end=REGEX"
                            .to_string(),
                    );
                }
                let (start, end) = Self::parse_boundary_options(&parts[1..])?;
                MultilineStrategy::Boundary { start, end }
            }
            "whole" => MultilineStrategy::Whole,
            _ => return Err(format!("Unknown multiline strategy: {}", strategy_name)),
        };

        Ok(MultilineConfig { strategy })
    }

    fn parse_pattern_option(option: &str) -> Result<String, String> {
        if let Some(pattern) = option.strip_prefix("pattern=") {
            Ok(pattern.to_string())
        } else {
            Err(format!("Invalid timestamp option: {}", option))
        }
    }

    fn parse_indent_options(option: &str) -> Result<(Option<u32>, bool, bool), String> {
        match option {
            "tabs" => Ok((None, true, false)),
            "mixed" => Ok((None, false, true)),
            option if option.starts_with("spaces=") => {
                let spaces_str = &option[7..];
                match spaces_str.parse::<u32>() {
                    Ok(n) => Ok((Some(n), false, false)),
                    Err(_) => Err(format!("Invalid spaces value: {}", spaces_str)),
                }
            }
            _ => Err(format!("Invalid indent option: {}", option)),
        }
    }

    fn parse_char_option(option: &str) -> Result<char, String> {
        if let Some(char_str) = option.strip_prefix("char=") {
            if char_str.len() == 1 {
                Ok(char_str.chars().next().unwrap())
            } else {
                Err(format!(
                    "Continuation character must be single character: {}",
                    char_str
                ))
            }
        } else {
            Err(format!("Invalid backslash option: {}", option))
        }
    }

    fn parse_boundary_options(parts: &[&str]) -> Result<(String, String), String> {
        let mut start = None;
        let mut end = None;

        for part in parts {
            if let Some(start_pattern) = part.strip_prefix("start=") {
                start = Some(start_pattern.to_string());
            } else if let Some(end_pattern) = part.strip_prefix("end=") {
                end = Some(end_pattern.to_string());
            } else {
                return Err(format!("Invalid boundary option: {}", part));
            }
        }

        match (start, end) {
            (Some(s), Some(e)) => Ok((s, e)),
            _ => Err("Boundary strategy requires both start=REGEX and end=REGEX".to_string()),
        }
    }
}

impl Default for MultilineConfig {
    fn default() -> Self {
        Self {
            strategy: MultilineStrategy::Timestamp {
                pattern: r"^(\d{4}-\d{2}-\d{2}|\w{3}\s+\d{1,2})".to_string(),
            },
        }
    }
}

impl InputFormat {
    /// Get default multiline configuration for this input format
    ///
    /// NOTE: Multiline processing is disabled by default for all formats
    /// to avoid unexpected buffering behavior in streaming scenarios.
    /// Users must explicitly enable multiline with --multiline option.
    pub fn default_multiline(&self) -> Option<MultilineConfig> {
        // Multiline is now strictly opt-in for all formats to avoid
        // unexpected "last event buffering" behavior in streaming scenarios
        None
    }
}

impl KeloraConfig {
    /// Get the list of core field names (ts, level, msg variants)
    pub fn get_core_field_names() -> Vec<String> {
        let mut core_fields = Vec::new();

        // Use constants from event.rs to ensure consistency
        core_fields.extend(
            crate::event::TIMESTAMP_FIELD_NAMES
                .iter()
                .map(|s| s.to_string()),
        );
        core_fields.extend(
            crate::event::LEVEL_FIELD_NAMES
                .iter()
                .map(|s| s.to_string()),
        );
        core_fields.extend(
            crate::event::MESSAGE_FIELD_NAMES
                .iter()
                .map(|s| s.to_string()),
        );

        core_fields
    }

    /// Format an error message with appropriate prefix (emoji or "kelora:")
    pub fn format_error_message(&self, message: &str) -> String {
        let use_colors = crate::tty::should_use_colors_with_mode(&self.output.color);
        let use_emoji = use_colors && !self.output.no_emoji;

        if use_emoji {
            format!("🔸{}", message)
        } else {
            format!("kelora: {}", message)
        }
    }

    /// Format a stats message with appropriate prefix (emoji or "Stats:")
    pub fn format_stats_message(&self, message: &str) -> String {
        let use_colors = crate::tty::should_use_colors_with_mode(&self.output.color);
        let use_emoji = use_colors && !self.output.no_emoji;

        if use_emoji {
            format!("🔹Kelora Stats\n{}", message)
        } else {
            format!("kelora: Stats\n{}", message)
        }
    }

    /// Format a metrics message with appropriate prefix (emoji or "Metrics:")
    pub fn format_metrics_message(&self, message: &str) -> String {
        let use_colors = crate::tty::should_use_colors_with_mode(&self.output.color);
        let use_emoji = use_colors && !self.output.no_emoji;

        if use_emoji {
            format!("🔹Tracked metrics\n{}", message)
        } else {
            format!("kelora: Tracked metrics\n{}", message)
        }
    }
}

/// Format an error message with appropriate prefix when config is not available
/// Uses auto color detection and allows NO_EMOJI environment variable override
pub fn format_error_message_auto(message: &str) -> String {
    let use_colors = crate::tty::should_use_colors_with_mode(&ColorMode::Auto);
    let no_emoji = std::env::var("NO_EMOJI").is_ok();
    let use_emoji = use_colors && !no_emoji;

    if use_emoji {
        format!("🔸{}", message)
    } else {
        format!("kelora: {}", message)
    }
}

/// Format a verbose error message with line number and error type
pub fn format_verbose_error(line_num: Option<usize>, error_type: &str, message: &str) -> String {
    format_verbose_error_with_config(line_num, error_type, message, None)
}

/// Format a verbose error message with explicit configuration
pub fn format_verbose_error_with_config(
    line_num: Option<usize>,
    error_type: &str,
    message: &str,
    config: Option<&KeloraConfig>,
) -> String {
    let use_colors = crate::tty::should_use_colors_with_mode(&ColorMode::Auto);

    // Check emoji settings in order of preference: config flag > NO_EMOJI env var
    let no_emoji = if let Some(cfg) = config {
        cfg.output.no_emoji || std::env::var("NO_EMOJI").is_ok()
    } else {
        std::env::var("NO_EMOJI").is_ok()
    };

    let use_emoji = use_colors && !no_emoji;
    let prefix = if use_emoji { "🔸" } else { "kelora: " };

    if let Some(line) = line_num {
        format!("{}line {}: {} - {}", prefix, line, error_type, message)
    } else {
        format!("{}{} - {}", prefix, error_type, message)
    }
}

/// Print a verbose error message to stderr with proper formatting
/// Always goes directly to stderr, bypassing any capture mechanisms for immediate output
pub fn print_verbose_error_to_stderr(
    line_num: Option<usize>,
    error_type: &str,
    message: &str,
    config: Option<&KeloraConfig>,
) {
    // Check if output is suppressed (quiet mode)
    if let Some(cfg) = config {
        if cfg.processing.quiet_level > 0 {
            return;
        }
    }

    let formatted = format_verbose_error_with_config(line_num, error_type, message, config);
    eprintln!("{}", formatted);
}

/// Print a verbose error message to stderr with PipelineConfig
/// Always goes directly to stderr, bypassing any capture mechanisms for immediate output
pub fn print_verbose_error_to_stderr_pipeline(
    line_num: Option<usize>,
    error_type: &str,
    message: &str,
    config: Option<&crate::pipeline::PipelineConfig>,
) {
    // Check if output is suppressed (quiet mode)
    if let Some(cfg) = config {
        if cfg.quiet_level > 0 {
            return;
        }
    }

    let formatted =
        format_verbose_error_with_pipeline_config(line_num, error_type, message, config);
    eprintln!("{}", formatted);
}

/// Format a verbose error message with PipelineConfig
pub fn format_verbose_error_with_pipeline_config(
    line_num: Option<usize>,
    error_type: &str,
    message: &str,
    config: Option<&crate::pipeline::PipelineConfig>,
) -> String {
    let color_mode = config.map(|c| &c.color_mode).unwrap_or(&ColorMode::Auto);
    let use_colors = crate::tty::should_use_colors_with_mode(color_mode);

    // Check emoji settings in order of preference: config flag > NO_EMOJI env var
    let no_emoji = if let Some(cfg) = config {
        cfg.no_emoji || std::env::var("NO_EMOJI").is_ok()
    } else {
        std::env::var("NO_EMOJI").is_ok()
    };

    let use_emoji = use_colors && !no_emoji;
    let prefix = if use_emoji { "🔸" } else { "kelora: " };

    if let Some(line) = line_num {
        format!("{}line {}: {} - {}", prefix, line, error_type, message)
    } else {
        format!("{}{} - {}", prefix, error_type, message)
    }
}

/// Format input line for error messages with smart handling of special characters
pub fn format_error_line(line: &str) -> String {
    if line.chars().any(|c| c.is_control() && c != '\n') {
        format!("{:?}", line) // Use Debug for control chars
    } else if line.ends_with('\n') {
        line.trim_end().to_string() // Suppress newlines, they are an artifact of our handling
    } else {
        line.to_string() // Raw for clean content
    }
}

impl OutputConfig {
    /// Get the effective keys for filtering, combining core fields with user-specified keys
    pub fn get_effective_keys(&self) -> Vec<String> {
        if self.core {
            let mut keys = KeloraConfig::get_core_field_names();
            // Add user-specified keys to the core fields, avoiding duplicates
            for key in &self.keys {
                if !keys.contains(key) {
                    keys.push(key.clone());
                }
            }
            keys
        } else {
            self.keys.clone()
        }
    }
}

impl KeloraConfig {
    /// Create configuration from CLI arguments
    pub fn from_cli(cli: &crate::Cli) -> Self {
        // Determine color mode from flags (no-color takes precedence over force-color)
        let color_mode = if cli.no_color {
            ColorMode::Never
        } else if cli.force_color {
            ColorMode::Always
        } else {
            ColorMode::Auto
        };

        Self {
            input: InputConfig {
                files: cli.files.clone(),
                format: if cli.json_input {
                    InputFormat::Json
                } else {
                    cli.format.clone().into()
                },
                file_order: cli.file_order.clone().into(),
                skip_lines: cli.skip_lines.unwrap_or(0),
                ignore_lines: None, // Will be set after CLI parsing
                keep_lines: None,   // Will be set after CLI parsing
                multiline: None,    // Will be set after CLI parsing
                ts_field: cli.ts_field.clone(),
                ts_format: cli.ts_format.clone(),
                default_timezone: determine_default_timezone(cli),
                extract_prefix: cli.extract_prefix.clone(),
                prefix_sep: cli.prefix_sep.clone(),
            },
            output: OutputConfig {
                format: if cli.stats_only {
                    OutputFormat::None
                } else if cli.quiet >= 2 {
                    // Quiet level 2+: suppress event output
                    OutputFormat::None
                } else if cli.json_output {
                    OutputFormat::Json
                } else {
                    cli.output_format.clone().into()
                },
                keys: cli.keys.clone(),
                exclude_keys: cli.exclude_keys.clone(),
                core: cli.core,
                brief: cli.brief,
                wrap: !cli.no_wrap, // Default true, disabled by --no-wrap
                color: color_mode,
                no_emoji: cli.no_emoji,
                stats: cli.stats || cli.stats_only,
                metrics: cli.metrics,
                metrics_file: cli.metrics_file.clone(),
                mark_gaps: None,
                timestamp_formatting: create_timestamp_format_config(cli),
            },
            processing: ProcessingConfig {
                begin: cli.begin.clone(),
                stages: Vec::new(), // Will be set by main() after CLI parsing
                end: cli.end.clone(),
                error_report: parse_error_report_config(cli),
                levels: cli.levels.clone(),
                exclude_levels: cli.exclude_levels.clone(),
                window_size: cli.window_size.unwrap_or(0),
                timestamp_filter: None, // Will be set in main() after parsing since/until
                take_limit: cli.take,
                strict: cli.strict,
                verbose: cli.verbose,
                quiet_level: cli.quiet,
            },
            performance: PerformanceConfig {
                parallel: cli.parallel,
                threads: cli.threads,
                batch_size: cli.batch_size,
                batch_timeout: cli.batch_timeout,
                no_preserve_order: cli.no_preserve_order,
            },
        }
    }

    /// Check if parallel processing should be used
    pub fn should_use_parallel(&self) -> bool {
        self.performance.parallel
            || self.performance.threads > 0
            || self.performance.batch_size.is_some()
    }

    /// Get effective batch size with defaults
    pub fn effective_batch_size(&self) -> usize {
        self.performance.batch_size.unwrap_or(1000)
    }

    /// Get effective thread count with defaults
    pub fn effective_threads(&self) -> usize {
        if self.performance.threads == 0 {
            num_cpus::get()
        } else {
            self.performance.threads
        }
    }
}

impl Default for KeloraConfig {
    fn default() -> Self {
        Self {
            input: InputConfig {
                files: Vec::new(),
                format: InputFormat::Json,
                file_order: FileOrder::Cli,
                skip_lines: 0,
                ignore_lines: None,
                keep_lines: None,
                multiline: None,
                ts_field: None,
                ts_format: None,
                default_timezone: None,
                extract_prefix: None,
                prefix_sep: "|".to_string(),
            },
            output: OutputConfig {
                format: OutputFormat::Default,
                keys: Vec::new(),
                exclude_keys: Vec::new(),
                core: false,
                brief: false,
                wrap: true, // Default to enabled
                color: ColorMode::Auto,
                no_emoji: false,
                stats: false,
                metrics: false,
                metrics_file: None,
                mark_gaps: None,
                timestamp_formatting: TimestampFormatConfig::default(),
            },
            processing: ProcessingConfig {
                begin: None,
                stages: Vec::new(),
                end: None,
                error_report: ErrorReportConfig {
                    style: ErrorReportStyle::Summary,
                },
                levels: Vec::new(),
                exclude_levels: Vec::new(),
                window_size: 0,
                timestamp_filter: None,
                take_limit: None,
                strict: false,
                verbose: 0,
                quiet_level: 0,
            },
            performance: PerformanceConfig {
                parallel: false,
                threads: 0,
                batch_size: None,
                batch_timeout: 200,
                no_preserve_order: false,
            },
        }
    }
}

/// Create timestamp formatting configuration from CLI options
fn create_timestamp_format_config(cli: &crate::Cli) -> TimestampFormatConfig {
    let format_fields = if let Some(ref pretty_ts) = cli.pretty_ts {
        pretty_ts.split(',').map(|s| s.trim().to_string()).collect()
    } else {
        Vec::new()
    };

    let auto_format_all = cli.format_timestamps_local || cli.format_timestamps_utc;
    let format_as_utc = cli.format_timestamps_utc;

    TimestampFormatConfig {
        format_fields,
        auto_format_all,
        format_as_utc,
    }
}

/// Parse error report configuration from CLI
fn parse_error_report_config(cli: &crate::Cli) -> ErrorReportConfig {
    // Default error report style based on new resiliency model
    let style = if cli.strict {
        ErrorReportStyle::Print // Show each error immediately in strict mode
    } else {
        ErrorReportStyle::Summary // Show summary in resilient mode
    };

    ErrorReportConfig { style }
}

/// Determine the default timezone based on CLI options and environment
/// Following the new spec: --input-tz defaults to UTC
fn determine_default_timezone(cli: &crate::Cli) -> Option<String> {
    // Priority 1: --input-tz option
    if let Some(ref input_tz) = cli.input_tz {
        if input_tz == "local" {
            return None; // None means local time
        } else {
            return Some(input_tz.clone());
        }
    }

    // Priority 2: TZ environment variable
    if let Ok(tz) = std::env::var("TZ") {
        if !tz.is_empty() {
            return Some(tz);
        }
    }

    // DEFAULT: UTC (per spec, --input-tz defaults to UTC)
    Some("UTC".to_string())
}

// Conversion traits to maintain compatibility with existing CLI types
impl From<crate::InputFormat> for InputFormat {
    fn from(format: crate::InputFormat) -> Self {
        match format {
            crate::InputFormat::Auto => InputFormat::Auto,
            crate::InputFormat::Json => InputFormat::Json,
            crate::InputFormat::Line => InputFormat::Line,
            crate::InputFormat::Raw => InputFormat::Raw,
            crate::InputFormat::Logfmt => InputFormat::Logfmt,
            crate::InputFormat::Syslog => InputFormat::Syslog,
            crate::InputFormat::Cef => InputFormat::Cef,
            crate::InputFormat::Csv => InputFormat::Csv,
            crate::InputFormat::Tsv => InputFormat::Tsv,
            crate::InputFormat::Csvnh => InputFormat::Csvnh,
            crate::InputFormat::Tsvnh => InputFormat::Tsvnh,
            crate::InputFormat::Combined => InputFormat::Combined,
        }
    }
}

impl From<InputFormat> for crate::InputFormat {
    fn from(format: InputFormat) -> Self {
        match format {
            InputFormat::Auto => crate::InputFormat::Auto,
            InputFormat::Json => crate::InputFormat::Json,
            InputFormat::Line => crate::InputFormat::Line,
            InputFormat::Raw => crate::InputFormat::Raw,
            InputFormat::Logfmt => crate::InputFormat::Logfmt,
            InputFormat::Syslog => crate::InputFormat::Syslog,
            InputFormat::Cef => crate::InputFormat::Cef,
            InputFormat::Csv => crate::InputFormat::Csv,
            InputFormat::Tsv => crate::InputFormat::Tsv,
            InputFormat::Csvnh => crate::InputFormat::Csvnh,
            InputFormat::Tsvnh => crate::InputFormat::Tsvnh,
            InputFormat::Combined => crate::InputFormat::Combined,
        }
    }
}

impl From<crate::OutputFormat> for OutputFormat {
    fn from(format: crate::OutputFormat) -> Self {
        match format {
            crate::OutputFormat::Json => OutputFormat::Json,
            crate::OutputFormat::Default => OutputFormat::Default,
            crate::OutputFormat::Logfmt => OutputFormat::Logfmt,
            crate::OutputFormat::Inspect => OutputFormat::Inspect,
            crate::OutputFormat::Levelmap => OutputFormat::Levelmap,
            crate::OutputFormat::Csv => OutputFormat::Csv,
            crate::OutputFormat::Tsv => OutputFormat::Tsv,
            crate::OutputFormat::Csvnh => OutputFormat::Csvnh,
            crate::OutputFormat::Tsvnh => OutputFormat::Tsvnh,
            crate::OutputFormat::None => OutputFormat::None,
        }
    }
}

impl From<OutputFormat> for crate::OutputFormat {
    fn from(format: OutputFormat) -> Self {
        match format {
            OutputFormat::Json => crate::OutputFormat::Json,
            OutputFormat::Default => crate::OutputFormat::Default,
            OutputFormat::Logfmt => crate::OutputFormat::Logfmt,
            OutputFormat::Inspect => crate::OutputFormat::Inspect,
            OutputFormat::Levelmap => crate::OutputFormat::Levelmap,
            OutputFormat::Csv => crate::OutputFormat::Csv,
            OutputFormat::Tsv => crate::OutputFormat::Tsv,
            OutputFormat::Csvnh => crate::OutputFormat::Csvnh,
            OutputFormat::Tsvnh => crate::OutputFormat::Tsvnh,
            OutputFormat::None => crate::OutputFormat::None,
        }
    }
}

impl From<crate::FileOrder> for FileOrder {
    fn from(order: crate::FileOrder) -> Self {
        match order {
            crate::FileOrder::Cli => FileOrder::Cli,
            crate::FileOrder::Name => FileOrder::Name,
            crate::FileOrder::Mtime => FileOrder::Mtime,
        }
    }
}

impl From<FileOrder> for crate::FileOrder {
    fn from(order: FileOrder) -> Self {
        match order {
            FileOrder::Cli => crate::FileOrder::Cli,
            FileOrder::Name => crate::FileOrder::Name,
            FileOrder::Mtime => crate::FileOrder::Mtime,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::Cli;
    use clap::Parser;
    use once_cell::sync::Lazy;
    use std::sync::Mutex;

    static ENV_LOCK: Lazy<Mutex<()>> = Lazy::new(|| Mutex::new(()));

    struct EnvGuard {
        vars: Vec<(&'static str, Option<String>)>,
    }

    impl EnvGuard {
        fn new(keys: &[&'static str]) -> Self {
            let vars = keys
                .iter()
                .map(|key| (*key, std::env::var(key).ok()))
                .collect();
            Self { vars }
        }
    }

    impl Drop for EnvGuard {
        fn drop(&mut self) {
            for (key, value) in &self.vars {
                if let Some(v) = value {
                    std::env::set_var(key, v);
                } else {
                    std::env::remove_var(key);
                }
            }
        }
    }

    fn with_env_lock<F: FnOnce()>(keys: &[&'static str], f: F) {
        let _lock = ENV_LOCK.lock().unwrap();
        let _guard = EnvGuard::new(keys);
        f();
    }

    #[test]
    fn determine_default_timezone_defaults_to_utc() {
        with_env_lock(&["TZ"], || {
            std::env::remove_var("TZ");
            let cli = Cli::parse_from(["kelora"]);
            let tz = super::determine_default_timezone(&cli);
            assert_eq!(tz.as_deref(), Some("UTC"));
        });
    }

    #[test]
    fn determine_default_timezone_respects_cli_local() {
        with_env_lock(&["TZ"], || {
            std::env::remove_var("TZ");
            let cli = Cli::parse_from(["kelora", "--input-tz", "local"]);
            let tz = super::determine_default_timezone(&cli);
            assert_eq!(tz, None);
        });
    }

    #[test]
    fn determine_default_timezone_prefers_cli_over_env() {
        with_env_lock(&["TZ"], || {
            std::env::set_var("TZ", "America/New_York");
            let cli = Cli::parse_from(["kelora", "--input-tz", "Europe/Berlin"]);
            let tz = super::determine_default_timezone(&cli);
            assert_eq!(tz.as_deref(), Some("Europe/Berlin"));
        });
    }

    #[test]
    fn determine_default_timezone_uses_environment_when_present() {
        with_env_lock(&["TZ"], || {
            std::env::set_var("TZ", "Asia/Tokyo");
            let cli = Cli::parse_from(["kelora"]);
            let tz = super::determine_default_timezone(&cli);
            assert_eq!(tz.as_deref(), Some("Asia/Tokyo"));
        });
    }

    #[test]
    fn format_error_message_respects_color_settings() {
        with_env_lock(&["NO_COLOR", "NO_EMOJI", "FORCE_COLOR"], || {
            std::env::remove_var("NO_COLOR");
            std::env::remove_var("NO_EMOJI");
            std::env::remove_var("FORCE_COLOR");

            let mut config = KeloraConfig::default();
            config.output.color = ColorMode::Always;
            config.output.no_emoji = false;

            let message = config.format_error_message("problem");
            assert!(message.starts_with("🔸"));
            assert!(message.ends_with("problem"));
        });
    }

    #[test]
    fn format_error_message_without_colors_falls_back_to_plain_prefix() {
        let mut config = KeloraConfig::default();
        config.output.color = ColorMode::Never;
        config.output.no_emoji = true;

        let message = config.format_error_message("issue");
        assert_eq!(message, "kelora: issue");
    }

    #[test]
    fn output_config_get_effective_keys_includes_core_fields() {
        let mut config = KeloraConfig::default();
        config.output.core = true;
        config.output.keys = vec!["custom".to_string(), "ts".to_string()];

        let keys = config.output.get_effective_keys();
        let core = KeloraConfig::get_core_field_names();

        for required in &core {
            assert!(keys.contains(required), "missing core key {required}");
        }
        assert!(keys.contains(&"custom".to_string()));

        let mut unique = keys.clone();
        unique.sort();
        unique.dedup();
        assert_eq!(
            unique.len(),
            keys.len(),
            "keys should not contain duplicates"
        );
    }

    #[test]
    fn output_config_get_effective_keys_respects_non_core_mode() {
        let mut config = KeloraConfig::default();
        config.output.core = false;
        config.output.keys = vec!["alpha".to_string(), "beta".to_string()];

        let keys = config.output.get_effective_keys();
        assert_eq!(keys, vec!["alpha".to_string(), "beta".to_string()]);
    }
}