kelora 1.5.0

A command-line log analysis tool with embedded Rhai scripting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
use std::fs;
use std::process::{Command, Stdio};
use tempfile::TempDir;

/// Helper to run kelora in a specific directory with config files
fn run_kelora_in_dir(dir: &std::path::Path, args: &[&str], input: &str) -> (String, String, i32) {
    // Get absolute path to binary from current working directory before changing
    let binary_path = if cfg!(debug_assertions) {
        std::env::current_dir().unwrap().join("target/debug/kelora")
    } else {
        std::env::current_dir()
            .unwrap()
            .join("target/release/kelora")
    };

    let mut cmd = Command::new(&binary_path)
        .current_dir(dir)
        .env("HOME", dir) // Set HOME to temp dir for isolated config testing
        .env("XDG_CONFIG_HOME", dir.join(".config"))
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("Failed to start kelora");

    if let Some(stdin) = cmd.stdin.as_mut() {
        use std::io::Write;
        stdin
            .write_all(input.as_bytes())
            .expect("Failed to write to stdin");
    }

    let output = cmd.wait_with_output().expect("Failed to read output");

    (
        String::from_utf8_lossy(&output.stdout).to_string(),
        String::from_utf8_lossy(&output.stderr).to_string(),
        output.status.code().unwrap_or(-1),
    )
}

fn run_kelora_in_dir_with_env(
    dir: &std::path::Path,
    args: &[&str],
    input: &str,
    envs: &[(&str, &str)],
) -> (String, String, i32) {
    let binary_path = if cfg!(debug_assertions) {
        std::env::current_dir().unwrap().join("target/debug/kelora")
    } else {
        std::env::current_dir()
            .unwrap()
            .join("target/release/kelora")
    };

    let mut cmd = Command::new(&binary_path);
    cmd.current_dir(dir)
        .env("HOME", dir)
        .env("XDG_CONFIG_HOME", dir.join(".config"))
        .args(args)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped());

    for (key, value) in envs {
        cmd.env(key, value);
    }

    let mut child = cmd.spawn().expect("Failed to start kelora");

    if let Some(stdin) = child.stdin.as_mut() {
        use std::io::Write;
        stdin
            .write_all(input.as_bytes())
            .expect("Failed to write to stdin");
    }

    let output = child.wait_with_output().expect("Failed to read output");

    (
        String::from_utf8_lossy(&output.stdout).to_string(),
        String::from_utf8_lossy(&output.stderr).to_string(),
        output.status.code().unwrap_or(-1),
    )
}

#[test]
fn test_config_file_with_defaults() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create a config file with defaults
    fs::write(&config_path, "defaults = -f json --with-stats\n").unwrap();

    // Create a simple JSON log file
    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, r#"{"level": "info", "msg": "test"}"#).unwrap();

    // Run kelora with --config-file pointing to our test config
    let (_stdout, stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            config_path.to_str().unwrap(),
            log_file.to_str().unwrap(),
        ],
        "",
    );

    assert_eq!(exit_code, 0, "kelora should exit successfully");
    assert!(
        stderr.contains("Events") || stderr.contains("processed"),
        "Expected stats in output, got: {}",
        stderr
    );
}

#[test]
fn test_default_config_path_is_not_printed_on_normal_runs() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");
    fs::write(&config_path, "defaults = -f line\n").unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "hello\n").unwrap();

    let (_stdout, stderr, exit_code) =
        run_kelora_in_dir(temp_dir.path(), &[log_file.to_str().unwrap()], "");

    assert_eq!(exit_code, 0, "kelora should exit successfully");
    assert!(
        !stderr.contains("Config:"),
        "default config path should be suppressed on normal runs: {}",
        stderr
    );
    assert!(
        !stderr.contains("Defaults:"),
        "default config expansion details should be suppressed on normal runs: {}",
        stderr
    );
}

#[test]
fn test_explicit_config_file_path_is_still_printed() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join("custom.ini");
    fs::write(&config_path, "defaults = -f line\n").unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "hello\n").unwrap();

    let (_stdout, stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            config_path.to_str().unwrap(),
            log_file.to_str().unwrap(),
        ],
        "",
    );

    assert_eq!(exit_code, 0, "kelora should exit successfully");
    assert!(
        stderr.contains("Config:"),
        "explicit config file path should still be shown: {}",
        stderr
    );
}

#[test]
fn test_config_file_with_alias() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create a config file with an alias
    fs::write(
        &config_path,
        "[aliases]\nerrors = --filter \"e.level == \\\"error\\\"\"\n",
    )
    .unwrap();

    // Create a JSON log file with mixed levels
    let log_file = temp_dir.path().join("test.log");
    fs::write(
        &log_file,
        r#"{"level": "info", "msg": "info message"}
{"level": "error", "msg": "error message"}
{"level": "info", "msg": "another info"}"#,
    )
    .unwrap();

    // Run kelora with the alias
    let (stdout, stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            config_path.to_str().unwrap(),
            "-f",
            "json",
            "--alias",
            "errors",
            log_file.to_str().unwrap(),
        ],
        "",
    );

    assert_eq!(
        exit_code, 0,
        "kelora should exit successfully, stderr: {}",
        stderr
    );
    assert!(
        stdout.contains("error message"),
        "Expected filtered error message, got: {}",
        stdout
    );
    assert!(
        !stdout.contains("info message"),
        "Should not contain info messages"
    );
}

#[test]
fn test_ignore_config_flag() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create a config file with defaults that would affect output
    fs::write(&config_path, "defaults = --with-stats\n").unwrap();

    // Create a simple log file
    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "test log line\n").unwrap();

    // Run kelora with --ignore-config (should NOT show stats)
    let (_stdout, stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &["--ignore-config", log_file.to_str().unwrap()],
        "",
    );

    assert_eq!(exit_code, 0, "kelora should exit successfully");
    // Should NOT show stats because config was ignored
    assert!(
        !stderr.contains("Events processed") && !stderr.contains("Events created"),
        "Should not show stats when config ignored, got: {}",
        stderr
    );
}

#[test]
fn test_ignore_config_env_skips_ambient_project_and_user_config() {
    let temp_dir = TempDir::new().unwrap();
    let project_config = temp_dir.path().join(".kelora.ini");
    let user_config_dir = temp_dir.path().join(".config").join("kelora");
    let user_config = user_config_dir.join("kelora.ini");

    fs::write(&project_config, "defaults = --with-stats\n").unwrap();
    fs::create_dir_all(&user_config_dir).unwrap();
    fs::write(&user_config, "defaults = --with-stats\n").unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "test log line\n").unwrap();

    let (_stdout, stderr, exit_code) = run_kelora_in_dir_with_env(
        temp_dir.path(),
        &[log_file.to_str().unwrap()],
        "",
        &[("KELORA_IGNORE_CONFIG", "1")],
    );

    assert_eq!(exit_code, 0, "kelora should exit successfully");
    assert!(
        !stderr.contains("Config:"),
        "Should not show config expansion info, got: {}",
        stderr
    );
    assert!(
        !stderr.contains("Events processed") && !stderr.contains("Events created"),
        "Should not apply ambient config defaults, got: {}",
        stderr
    );
}

#[test]
fn test_ignore_config_env_still_allows_explicit_config_file() {
    let temp_dir = TempDir::new().unwrap();
    let ambient_project_config = temp_dir.path().join(".kelora.ini");
    let explicit_config = temp_dir.path().join("explicit.ini");

    fs::write(&ambient_project_config, "defaults = -q\n").unwrap();
    fs::write(&explicit_config, "defaults = --with-stats\n").unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "test log line\n").unwrap();

    let (_stdout, stderr, exit_code) = run_kelora_in_dir_with_env(
        temp_dir.path(),
        &[
            "--config-file",
            explicit_config.to_str().unwrap(),
            log_file.to_str().unwrap(),
        ],
        "",
        &[("KELORA_IGNORE_CONFIG", "1")],
    );

    assert_eq!(exit_code, 0, "kelora should exit successfully");
    assert!(
        stderr.contains("Config:"),
        "Expected explicit config file to load, got: {}",
        stderr
    );
    assert!(
        stderr.contains("Events") || stderr.contains("processed"),
        "Expected explicit config defaults to apply, got: {}",
        stderr
    );
}

#[test]
fn test_project_config_precedence() {
    let temp_dir = TempDir::new().unwrap();

    // Create a project config in the current directory
    let project_config = temp_dir.path().join(".kelora.ini");
    fs::write(
        &project_config,
        "defaults = --with-stats\n[aliases]\ntest-alias = -q\n",
    )
    .unwrap();

    // Create a log file
    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "test log line\n").unwrap();

    // Run kelora from temp_dir (should pick up .kelora.ini)
    let (_stdout, stderr, exit_code) =
        run_kelora_in_dir(temp_dir.path(), &[log_file.to_str().unwrap()], "");

    assert_eq!(exit_code, 0, "kelora should exit successfully");
    // Should show stats from project config
    assert!(
        stderr.contains("Events") || stderr.contains("Stats"),
        "Expected stats from project config, got: {}",
        stderr
    );
}

#[test]
fn test_custom_config_file_path() {
    let temp_dir = TempDir::new().unwrap();

    // Create a config file in a non-standard location
    let custom_config = temp_dir.path().join("custom.ini");
    fs::write(&custom_config, "defaults = --with-stats\n").unwrap();

    // Create a log file
    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "test log line\n").unwrap();

    // Run kelora with --config-file pointing to custom location
    let (_stdout, stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            custom_config.to_str().unwrap(),
            log_file.to_str().unwrap(),
        ],
        "",
    );

    assert_eq!(exit_code, 0, "kelora should exit successfully");
    assert!(
        stderr.contains("Events") || stderr.contains("Stats"),
        "Expected stats from custom config, got: {}",
        stderr
    );
}

#[test]
fn test_invalid_config_produces_error() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create an invalid config file (unparseable defaults)
    fs::write(&config_path, "defaults = --filter 'unclosed quote\n").unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "test log line\n").unwrap();

    // Run kelora with the invalid config
    let (_stdout, stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            config_path.to_str().unwrap(),
            log_file.to_str().unwrap(),
        ],
        "",
    );

    // Should fail with error code
    assert_ne!(exit_code, 0, "Should fail with invalid config");
    // Should mention the parsing error
    assert!(
        stderr.to_lowercase().contains("fail")
            || stderr.to_lowercase().contains("error")
            || stderr.to_lowercase().contains("invalid"),
        "Expected error message, got: {}",
        stderr
    );
}

#[test]
fn test_nonexistent_config_file_error() {
    let temp_dir = TempDir::new().unwrap();
    let nonexistent_config = temp_dir.path().join("does-not-exist.ini");

    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "test log line\n").unwrap();

    // Run kelora with --config-file pointing to nonexistent file
    let (_stdout, stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            nonexistent_config.to_str().unwrap(),
            log_file.to_str().unwrap(),
        ],
        "",
    );

    // Should fail with error code
    assert_ne!(exit_code, 0, "Should fail with nonexistent config");
    assert!(
        stderr.contains("Failed to read config file") || stderr.contains("No such file"),
        "Expected file not found error, got: {}",
        stderr
    );
}

#[test]
fn test_recursive_alias_resolution() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create config with nested aliases
    fs::write(
        &config_path,
        "[aliases]\nbase = -f json\nerrors = --alias base --filter \"e.level == \\\"error\\\"\"\n",
    )
    .unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, r#"{"level": "error", "msg": "test"}"#).unwrap();

    // Run with nested alias
    let (_stdout, _stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            config_path.to_str().unwrap(),
            "--alias",
            "errors",
            log_file.to_str().unwrap(),
        ],
        "",
    );

    // Should successfully resolve nested aliases and process
    assert_eq!(exit_code, 0, "Should resolve nested aliases");
}

#[test]
fn test_circular_alias_error() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create config with circular aliases
    fs::write(
        &config_path,
        "[aliases]\nalias1 = --alias alias2\nalias2 = --alias alias1\n",
    )
    .unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "test\n").unwrap();

    // Run with circular alias
    let (_stdout, stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            config_path.to_str().unwrap(),
            "--alias",
            "alias1",
            log_file.to_str().unwrap(),
        ],
        "",
    );

    // Should fail with circular dependency error
    assert_ne!(exit_code, 0, "Should fail on circular alias");
    assert!(
        stderr.to_lowercase().contains("circular"),
        "Expected circular dependency error, got: {}",
        stderr
    );
}

#[test]
fn test_unknown_alias_error() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create config with one alias
    fs::write(&config_path, "[aliases]\nknown = -f json\n").unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "test\n").unwrap();

    // Run with unknown alias
    let (_stdout, stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            config_path.to_str().unwrap(),
            "--alias",
            "unknown",
            log_file.to_str().unwrap(),
        ],
        "",
    );

    // Should fail with unknown alias error
    assert_ne!(exit_code, 0, "Should fail on unknown alias");
    assert!(
        stderr.contains("Unknown alias") || stderr.to_lowercase().contains("unknown"),
        "Expected unknown alias error, got: {}",
        stderr
    );
}

#[test]
fn test_defaults_with_cli_override() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Config sets format to json
    fs::write(&config_path, "defaults = -f json\n").unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "plain text log\n").unwrap();

    // CLI explicitly specifies line format after config defaults
    let (_stdout, _stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            config_path.to_str().unwrap(),
            "-f",
            "line",
            log_file.to_str().unwrap(),
        ],
        "",
    );

    // Should succeed - CLI args should work alongside defaults
    assert_eq!(exit_code, 0, "CLI override should work with defaults");
}

#[test]
fn test_alias_with_quoted_args() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create alias with quoted filter expression
    fs::write(&config_path,
        "[aliases]\ncomplex = --filter \"e.level == \\\"error\\\" && e.msg.matches(\\\"critical\\\")\"\n").unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(
        &log_file,
        r#"{"level": "error", "msg": "critical error"}
{"level": "error", "msg": "normal error"}
{"level": "info", "msg": "critical info"}"#,
    )
    .unwrap();

    let (stdout, stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            config_path.to_str().unwrap(),
            "-f",
            "json",
            "--alias",
            "complex",
            log_file.to_str().unwrap(),
        ],
        "",
    );

    assert_eq!(
        exit_code, 0,
        "kelora should exit successfully, stderr: {}",
        stderr
    );
    // Should only match the critical error
    assert!(
        stdout.contains("critical error"),
        "Should match critical error, got: {}",
        stdout
    );
    assert!(
        !stdout.contains("normal error"),
        "Should not match normal error"
    );
    assert!(
        !stdout.contains("critical info"),
        "Should not match info level"
    );
}

#[test]
fn test_empty_config_file() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create empty config file
    fs::write(&config_path, "").unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "test log line\n").unwrap();

    let (_stdout, _stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            config_path.to_str().unwrap(),
            log_file.to_str().unwrap(),
        ],
        "",
    );

    // Should succeed with empty config
    assert_eq!(exit_code, 0, "Empty config should not cause errors");
}

#[test]
fn test_config_with_comments() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create config with comments
    fs::write(&config_path,
        "# This is a comment\ndefaults = --with-stats\n; Another comment\n[aliases]\n# Alias comment\nerrors = -l error\n").unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, "test\n").unwrap();

    let (_stdout, stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            config_path.to_str().unwrap(),
            log_file.to_str().unwrap(),
        ],
        "",
    );

    // Should parse config correctly, ignoring comments
    assert_eq!(exit_code, 0, "Config with comments should parse");
    assert!(
        stderr.contains("Events") || stderr.contains("Stats"),
        "Should apply defaults from commented config, got: {}",
        stderr
    );
}

#[test]
fn test_show_config_displays_content() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    let config_content = "defaults = -f json\n[aliases]\ntest = --with-stats\n";
    fs::write(&config_path, config_content).unwrap();

    let (stdout, _stderr, exit_code) = run_kelora_in_dir(temp_dir.path(), &["--show-config"], "");

    assert_eq!(
        exit_code, 0,
        "kelora --show-config should exit successfully"
    );
    // Should display the config file path and contents
    assert!(
        stdout.contains("defaults = -f json"),
        "Should show defaults, got: {}",
        stdout
    );
    assert!(stdout.contains("[aliases]"), "Should show aliases section");
    assert!(stdout.contains("test = --with-stats"), "Should show alias");
}

#[test]
fn test_show_config_no_file_found() {
    let temp_dir = TempDir::new().unwrap();

    // No config file in temp directory
    let (stdout, _stderr, exit_code) = run_kelora_in_dir(temp_dir.path(), &["--show-config"], "");

    assert_eq!(
        exit_code, 0,
        "kelora --show-config should exit successfully even without config"
    );
    // Should show message about no config found and example
    assert!(
        stdout.contains("No config found") || stdout.contains("Example"),
        "Should show helpful message when no config found, got: {}",
        stdout
    );
}

#[test]
fn test_multiple_aliases_in_one_command() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create config with multiple aliases
    fs::write(&config_path, "[aliases]\njson-fmt = -f json\nquiet = -q\n").unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(&log_file, r#"{"level": "info", "msg": "test"}"#).unwrap();

    let (_stdout, _stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            config_path.to_str().unwrap(),
            "--alias",
            "json-fmt",
            "--alias",
            "quiet",
            log_file.to_str().unwrap(),
        ],
        "",
    );

    // Should successfully expand multiple aliases
    assert_eq!(exit_code, 0, "Should handle multiple aliases");
}

#[test]
fn test_defaults_and_alias_combination() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Defaults set format, alias adds filter
    fs::write(
        &config_path,
        "defaults = -f json\n[aliases]\nerrors = --filter \"e.level == \\\"error\\\"\"\n",
    )
    .unwrap();

    let log_file = temp_dir.path().join("test.log");
    fs::write(
        &log_file,
        r#"{"level": "info", "msg": "info"}
{"level": "error", "msg": "error"}"#,
    )
    .unwrap();

    let (stdout, _stderr, exit_code) = run_kelora_in_dir(
        temp_dir.path(),
        &[
            "--config-file",
            config_path.to_str().unwrap(),
            "--alias",
            "errors",
            log_file.to_str().unwrap(),
        ],
        "",
    );

    assert_eq!(exit_code, 0, "kelora should exit successfully");
    // Should apply both defaults (json format) and alias (error filter)
    assert!(
        stdout.contains("error"),
        "Should show error level, got: {}",
        stdout
    );
    assert!(!stdout.contains("info"), "Should not show info level");
}

#[test]
fn test_save_alias_update_with_self_reference() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create initial alias
    fs::write(&config_path, "[aliases]\nerrors = -l error\n").unwrap();

    // Update it with self-reference + new flag
    let binary_path = if cfg!(debug_assertions) {
        std::env::current_dir().unwrap().join("target/debug/kelora")
    } else {
        std::env::current_dir()
            .unwrap()
            .join("target/release/kelora")
    };

    let output = Command::new(&binary_path)
        .args([
            "--save-alias",
            "errors",
            "--config-file",
            config_path.to_str().unwrap(),
            "-a",
            "errors",
            "--stats",
        ])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "kelora should exit successfully, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let config_content = fs::read_to_string(&config_path).unwrap();
    // Should resolve -a errors to -l error, then add --stats
    assert!(
        config_content.contains("errors = -l error --stats"),
        "Config should contain flattened alias, got: {}",
        config_content
    );
    // Should NOT contain -a reference
    assert!(
        !config_content.contains("-a errors") && !config_content.contains("--alias errors"),
        "Config should not contain alias reference, got: {}",
        config_content
    );
}

#[test]
fn test_save_alias_compose_with_reference() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create base alias
    fs::write(&config_path, "[aliases]\nerrors = -l error\n").unwrap();

    // Create new alias referencing the base
    let binary_path = if cfg!(debug_assertions) {
        std::env::current_dir().unwrap().join("target/debug/kelora")
    } else {
        std::env::current_dir()
            .unwrap()
            .join("target/release/kelora")
    };

    let output = Command::new(&binary_path)
        .args([
            "--save-alias",
            "json-errors",
            "--config-file",
            config_path.to_str().unwrap(),
            "-a",
            "errors",
            "-f",
            "json",
        ])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "kelora should exit successfully, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let config_content = fs::read_to_string(&config_path).unwrap();
    // Should preserve the -a reference
    assert!(
        config_content.contains("json-errors = -a errors -f json"),
        "Config should preserve alias reference, got: {}",
        config_content
    );
}

#[test]
fn test_save_alias_error_on_unknown_reference() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create config with one alias
    fs::write(&config_path, "[aliases]\nknown = -l error\n").unwrap();

    // Try to create alias referencing unknown alias
    let binary_path = if cfg!(debug_assertions) {
        std::env::current_dir().unwrap().join("target/debug/kelora")
    } else {
        std::env::current_dir()
            .unwrap()
            .join("target/release/kelora")
    };

    let output = Command::new(&binary_path)
        .args([
            "--save-alias",
            "new-alias",
            "--config-file",
            config_path.to_str().unwrap(),
            "-a",
            "unknown",
            "--stats",
        ])
        .output()
        .unwrap();

    assert!(
        !output.status.success(),
        "kelora should fail when referencing unknown alias"
    );
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        stderr.contains("Referenced alias 'unknown' does not exist") || stderr.contains("unknown"),
        "Error message should mention unknown alias, got: {}",
        stderr
    );
}

#[test]
fn test_save_alias_nested_resolution_in_update() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    // Create nested aliases
    fs::write(
        &config_path,
        "[aliases]\nbase = -f json\nerrors = -a base -l error\n",
    )
    .unwrap();

    // Update errors with self-reference (should fully resolve)
    let binary_path = if cfg!(debug_assertions) {
        std::env::current_dir().unwrap().join("target/debug/kelora")
    } else {
        std::env::current_dir()
            .unwrap()
            .join("target/release/kelora")
    };

    let output = Command::new(&binary_path)
        .args([
            "--save-alias",
            "errors",
            "--config-file",
            config_path.to_str().unwrap(),
            "-a",
            "errors",
            "--stats",
        ])
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "kelora should exit successfully, stderr: {}",
        String::from_utf8_lossy(&output.stderr)
    );

    let config_content = fs::read_to_string(&config_path).unwrap();
    // Should fully resolve: -a errors -> -a base -l error -> -f json -l error
    // Then add --stats
    assert!(
        config_content.contains("errors = -f json -l error --stats"),
        "Config should contain fully resolved alias, got: {}",
        config_content
    );
    assert!(
        !config_content.contains("json-errors")
            || !config_content[config_content.find("errors = ").unwrap()..].contains("-a"),
        "Errors alias should not contain -a reference, got: {}",
        config_content
    );
}

#[test]
fn test_save_alias_full_workflow() {
    let temp_dir = TempDir::new().unwrap();
    let config_path = temp_dir.path().join(".kelora.ini");

    let binary_path = if cfg!(debug_assertions) {
        std::env::current_dir().unwrap().join("target/debug/kelora")
    } else {
        std::env::current_dir()
            .unwrap()
            .join("target/release/kelora")
    };

    // Step 1: Create base alias
    Command::new(&binary_path)
        .args([
            "--save-alias",
            "json",
            "--config-file",
            config_path.to_str().unwrap(),
            "-f",
            "json",
        ])
        .output()
        .unwrap();

    // Step 2: Compose new alias referencing base
    Command::new(&binary_path)
        .args([
            "--save-alias",
            "json-errors",
            "--config-file",
            config_path.to_str().unwrap(),
            "-a",
            "json",
            "-l",
            "error",
        ])
        .output()
        .unwrap();

    let content = fs::read_to_string(&config_path).unwrap();
    assert!(
        content.contains("json = -f json"),
        "Should have json alias, got: {}",
        content
    );
    assert!(
        content.contains("json-errors = -a json -l error"),
        "Should have json-errors with reference, got: {}",
        content
    );

    // Step 3: Update json-errors with self-reference
    Command::new(&binary_path)
        .args([
            "--save-alias",
            "json-errors",
            "--config-file",
            config_path.to_str().unwrap(),
            "-a",
            "json-errors",
            "--stats",
        ])
        .output()
        .unwrap();

    let content = fs::read_to_string(&config_path).unwrap();
    // Should resolve: -a json-errors -> -a json -l error -> -f json -l error
    // Then add --stats
    assert!(
        content.contains("json-errors = -f json -l error --stats"),
        "Should have flattened json-errors, got: {}",
        content
    );
}