parsm 0.8.3

Multi-format data processor that understands structured text better than sed or awk. Supports JSON, CSV, YAML, TOML, logfmt, and plain text with powerful filtering and templating.
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
//! Comprehensive DSL Integration Tests
//!
//! This module contains regression tests and comprehensive integration tests for the DSL parser.
//! These tests ensure that critical parsing distinctions and edge cases are preserved
//! across refactoring and modularization efforts.

use parsm::dsl::parse_command;
use parsm::filter::{ComparisonOp, FilterExpr, FilterValue, TemplateItem};

/// Test the critical parsing distinctions required for unambiguous DSL behavior.
///
/// This test ensures that:
/// - `$name` and `${name}` are always parsed as field substitutions (variables)
/// - `"name"` and `{name}` are always parsed as literals
/// - Dollar amounts like `$20`, `$0`, `$1` are always treated as numeric literals (not variables)
/// - Only `${0}`, `${1}`, `${20}` are treated as field substitutions for numeric fields
#[test]
fn test_critical_parsing_distinctions() {
    println!("\n=== Testing Critical Parsing Distinctions ===");

    // Test 1: $name should be parsed as field substitution (variable)
    println!("\nTest 1: $name as field substitution");
    let result = parse_command("$name").unwrap();
    assert!(result.template.is_some(), "$name should be template");
    assert!(result.filter.is_none(), "$name should not be filter");
    assert!(
        result.field_selector.is_none(),
        "$name should not be field selector"
    );

    let template = result.template.unwrap();
    assert_eq!(template.items.len(), 1);
    match &template.items[0] {
        TemplateItem::Field(field) => {
            assert_eq!(field.parts, vec!["name"]);
            println!(
                "  ✓ $name correctly parsed as field substitution: {:?}",
                field.parts
            );
        }
        TemplateItem::Literal(text) => {
            panic!("$name should be field substitution, not literal: {text}");
        }
        TemplateItem::Conditional { .. } => {
            panic!("$name should not be conditional template");
        }
    }

    // Test 2: ${name} as a bare top-level field substitution is covered by
    // `bare_braced_named_variable_requires_p1_3` below (restore-in-P1.3, Set
    // B: cov-tmpl-dollar-zero's branch generalizes to named fields too).

    // Test 3: "name" should be parsed as literal (quoted field selector)
    println!("\nTest 3: \"name\" as literal field selector");
    let result = parse_command("\"name\"").unwrap();
    assert!(
        result.field_selector.is_some(),
        "\"name\" should be field selector"
    );
    assert!(result.filter.is_none(), "\"name\" should not be filter");
    assert!(result.template.is_none(), "\"name\" should not be template");

    let field_selector = result.field_selector.unwrap();
    assert_eq!(field_selector.parts, vec!["name"]);
    println!(
        "  ✓ \"name\" correctly parsed as field selector: {:?}",
        field_selector.parts
    );

    // Test 4: {name} should be parsed as literal template
    println!("\nTest 4: {{name}} as literal template");
    let result = parse_command("{name}").unwrap();
    assert!(result.template.is_some(), "{{name}} should be template");
    assert!(result.filter.is_none(), "{{name}} should not be filter");
    assert!(
        result.field_selector.is_none(),
        "{{name}} should not be field selector"
    );

    let template = result.template.unwrap();
    assert_eq!(template.items.len(), 1);
    match &template.items[0] {
        TemplateItem::Literal(text) => assert_eq!(text, "name"),
        _ => panic!("{{name}} should be literal template, not field substitution"),
    }

    // Test 5 ($20) and Test 6 ($0) - bare top-level all-digit dollar-amount
    // literals - are covered by `bare_dollar_amount_literal_requires_p1_3`
    // below (restore-in-P1.3, Set B: cov-tmpl-dollar-digits).

    // Test 7: ${0} should be parsed as field substitution (numeric field reference)
    println!("\nTest 7: ${{0}} as field substitution");
    let result = parse_command("${0}");
    match result {
        Ok(parsed) => {
            if let Some(template) = parsed.template {
                if template.items.len() == 1 {
                    match &template.items[0] {
                        TemplateItem::Field(field) => {
                            // ${0} maps to "$0" field reference
                            assert_eq!(field.parts, vec!["$0"]);
                            println!("  ✓ ${{0}} correctly parsed as field substitution to $0");
                        }
                        _ => panic!("${{0}} should be field substitution"),
                    }
                }
            } else {
                panic!("${{0}} should parse as template");
            }
        }
        Err(e) => {
            println!("  âš  ${{0}} failed to parse: {e}");
            // This might be acceptable depending on implementation
        }
    }

    println!("\n=== All Critical Parsing Distinction Tests Completed ===");
}

/// `${name}` (a bare, top-level braced variable for a non-numeric field) has
/// no `template_expr` alternative in the pest grammar without the fallback -
/// `braced_variable` only exists embedded inside `{...}`/`[...]` content
/// rules, not as a standalone top-level form. Split out of
/// `test_critical_parsing_distinctions` (formerly "Test 2") because the rest
/// of that test's assertions still hold.
#[test]
fn bare_braced_named_variable_requires_p1_3() {
    let result = parse_command("${name}").unwrap();
    assert!(result.template.is_some(), "${{name}} should be template");
    assert!(result.filter.is_none(), "${{name}} should not be filter");
    assert!(
        result.field_selector.is_none(),
        "${{name}} should not be field selector"
    );

    let template = result.template.unwrap();
    assert_eq!(template.items.len(), 1);
    match &template.items[0] {
        TemplateItem::Field(field) => {
            assert_eq!(field.parts, vec!["name"]);
        }
        TemplateItem::Literal(text) => {
            panic!("${{name}} should be field substitution, not literal: {text}");
        }
        TemplateItem::Conditional { .. } => {
            panic!("${{name}} should not be conditional template");
        }
    }
}

/// Bare top-level all-digit dollar amounts (`$20`, `$0`) have no
/// `template_expr` alternative in the pest grammar without the fallback.
/// Split out of `test_critical_parsing_distinctions` (formerly "Test 5" and
/// "Test 6") because the rest of that test's assertions still hold.
#[test]
fn bare_dollar_amount_literal_requires_p1_3() {
    let result = parse_command("$20").unwrap();
    assert!(result.template.is_some());
    let template = result.template.unwrap();
    assert_eq!(template.items.len(), 1);
    match &template.items[0] {
        TemplateItem::Literal(text) => assert_eq!(text, "$20"),
        _ => panic!("Expected $20 to be literal"),
    }

    let result = parse_command("$0").unwrap();
    assert!(result.template.is_some());
    let template = result.template.unwrap();
    assert_eq!(template.items.len(), 1);
    match &template.items[0] {
        TemplateItem::Literal(text) => assert_eq!(text, "$0"),
        _ => panic!("Expected $0 to be literal"),
    }
}

/// Test quoted string literals parsing correctly as field selectors.
#[test]
fn test_quoted_string_literals() {
    println!("\n=== Testing Quoted String Literals ===");

    // Test 1: "Alice" should be parsed as field selector with value "Alice"
    println!("\nTest 1: \"Alice\" as quoted field selector");
    let result = parse_command("\"Alice\"").unwrap();
    assert!(
        result.field_selector.is_some(),
        "\"Alice\" should be field selector"
    );
    assert!(result.filter.is_none(), "\"Alice\" should not be filter");
    assert!(
        result.template.is_none(),
        "\"Alice\" should not be template"
    );

    let field_selector = result.field_selector.unwrap();
    assert_eq!(field_selector.parts, vec!["Alice"]);
    println!(
        "  ✓ \"Alice\" correctly parsed as field selector: {:?}",
        field_selector.parts
    );

    // Test 2: "25" should be parsed as field selector with value "25" (string)
    println!("\nTest 2: \"25\" as quoted field selector");
    let result = parse_command("\"25\"").unwrap();
    assert!(
        result.field_selector.is_some(),
        "\"25\" should be field selector"
    );
    assert!(result.filter.is_none(), "\"25\" should not be filter");
    assert!(result.template.is_none(), "\"25\" should not be template");

    let field_selector = result.field_selector.unwrap();
    assert_eq!(field_selector.parts, vec!["25"]);
    println!(
        "  ✓ \"25\" correctly parsed as field selector: {:?}",
        field_selector.parts
    );

    // Test 3: Single-quoted strings should work the same way
    println!("\nTest 3: 'Alice' as single-quoted field selector");
    let result = parse_command("'Alice'").unwrap();
    assert!(
        result.field_selector.is_some(),
        "'Alice' should be field selector"
    );
    assert!(result.filter.is_none(), "'Alice' should not be filter");
    assert!(result.template.is_none(), "'Alice' should not be template");

    let field_selector = result.field_selector.unwrap();
    assert_eq!(field_selector.parts, vec!["Alice"]);
    println!(
        "  ✓ 'Alice' correctly parsed as field selector: {:?}",
        field_selector.parts
    );

    // Test 4: 'name with spaces' should work
    println!("\nTest 4: 'field name' as quoted field selector with spaces");
    let result = parse_command("'field name'").unwrap();
    assert!(
        result.field_selector.is_some(),
        "'field name' should be field selector"
    );

    let field_selector = result.field_selector.unwrap();
    assert_eq!(field_selector.parts, vec!["field name"]);
    println!(
        "  ✓ 'field name' correctly parsed as field selector: {:?}",
        field_selector.parts
    );

    // Test 5: "field.with.dots" should handle dots correctly
    println!("\nTest 5: \"field.with.dots\" as dotted field selector");
    let result = parse_command("\"field.with.dots\"").unwrap();
    assert!(
        result.field_selector.is_some(),
        "\"field.with.dots\" should be field selector"
    );

    let field_selector = result.field_selector.unwrap();
    assert_eq!(field_selector.parts, vec!["field", "with", "dots"]);
    println!(
        "  ✓ \"field.with.dots\" correctly parsed as field selector: {:?}",
        field_selector.parts
    );

    println!("\n=== Quoted String Literal Tests Completed ===");
}

/// Test template variable edge cases with numeric and literal patterns.
#[test]
fn test_template_variable_edge_cases() {
    // Test ${0} - should be special variable for original input
    let result = parse_command("${0}").unwrap();
    assert!(result.template.is_some());
    let template = result.template.unwrap();
    assert_eq!(template.items.len(), 1);
    match &template.items[0] {
        TemplateItem::Field(field) => {
            // ${0} should map to "$0" field reference
            assert_eq!(field.parts, vec!["$0"]);
        }
        _ => panic!("Expected ${{0}} to be field substitution"),
    }

    // Test $0 - should be literal (not special)
    let result = parse_command("$0").unwrap();
    assert!(result.template.is_some());
    let template = result.template.unwrap();
    assert_eq!(template.items.len(), 1);
    match &template.items[0] {
        TemplateItem::Literal(text) => assert_eq!(text, "$0"),
        _ => panic!("Expected $0 to be literal"),
    }

    // Test $20 - should be literal dollar amount
    let result = parse_command("$20").unwrap();
    assert!(result.template.is_some());
    let template = result.template.unwrap();
    assert_eq!(template.items.len(), 1);
    match &template.items[0] {
        TemplateItem::Literal(text) => assert_eq!(text, "$20"),
        _ => panic!("Expected $20 to be literal"),
    }

    // Test $1 - should be literal dollar amount
    let result = parse_command("$1").unwrap();
    assert!(result.template.is_some());
    let template = result.template.unwrap();
    assert_eq!(template.items.len(), 1);
    match &template.items[0] {
        TemplateItem::Literal(text) => assert_eq!(text, "$1"),
        _ => panic!("Expected $1 to be literal"),
    }

    // Test ${1} - should be field variable (maps to "1")
    let result = parse_command("${1}").unwrap();
    assert!(result.template.is_some());
    let template = result.template.unwrap();
    assert_eq!(template.items.len(), 1);
    match &template.items[0] {
        TemplateItem::Field(field) => assert_eq!(field.parts, vec!["1"]),
        _ => panic!("Expected ${{1}} to be field substitution"),
    }

    // Test ${2} - should be field variable (maps to "2")
    let result = parse_command("${2}").unwrap();
    assert!(result.template.is_some());
    let template = result.template.unwrap();
    assert_eq!(template.items.len(), 1);
    match &template.items[0] {
        TemplateItem::Field(field) => assert_eq!(field.parts, vec!["2"]),
        _ => panic!("Expected ${{2}} to be field substitution"),
    }

    // Test ${20} - should be field variable (maps to "20")
    let result = parse_command("${20}").unwrap();
    assert!(result.template.is_some());
    let template = result.template.unwrap();
    assert_eq!(template.items.len(), 1);
    match &template.items[0] {
        TemplateItem::Field(field) => assert_eq!(field.parts, vec!["20"]),
        _ => panic!("Expected ${{20}} to be field substitution"),
    }
}

/// Test templates with mixed numeric literals and variables.
#[test]
fn test_mixed_numeric_template_patterns() {
    // Test braced template with dollar amounts and variables: {I have $20 and ${name} has $100}
    let result = parse_command("{I have $20 and ${name} has $100}").unwrap();
    assert!(result.template.is_some());
    let template = result.template.unwrap();

    // Should have 3 items: literal "I have $20 and ", field "name", literal " has $100"
    assert!(template.items.len() >= 2); // At least literal and field

    // Check that we have both literal text with dollar amounts and field substitutions
    let mut found_literal_with_dollar = false;
    let mut found_field = false;

    for item in &template.items {
        match item {
            TemplateItem::Literal(text) => {
                if text.contains("$20") || text.contains("$100") {
                    found_literal_with_dollar = true;
                }
            }
            TemplateItem::Field(field) if field.parts == vec!["name"] => {
                found_field = true;
            }
            _ => {}
        }
    }

    assert!(
        found_literal_with_dollar,
        "Should contain literal dollar amounts"
    );
    assert!(found_field, "Should contain field substitution");
}

/// Test edge cases and boundary conditions for parsing distinctions.
#[test]
fn test_parsing_edge_cases() {
    println!("\n=== Testing Edge Cases ===");

    let test_cases = vec![
        // Edge cases for dollar amounts vs variables
        ("$1", "literal dollar amount"),
        ("$999", "literal dollar amount"),
        ("$00", "literal dollar amount"),
        ("$01", "literal dollar amount"),
        // Edge cases for braced expressions
        ("${1}", "field substitution"),
        ("${999}", "field substitution"),
        ("${00}", "field substitution"),
        ("${01}", "field substitution"),
        // Edge cases for variable names
        ("$a", "field substitution - single letter"),
        ("$_", "field substitution - underscore"),
        ("$name_123", "field substitution - alphanumeric"),
        // Edge cases for literals
        ("{$20}", "literal template with dollar amount"),
        ("{${name}}", "template with field substitution"),
        ("\"$20\"", "quoted literal"),
        // Boundary cases
        ("$", "bare dollar sign"),
        ("${}", "empty braced expression"),
        ("{}", "empty braces"),
    ];

    for (input, description) in test_cases {
        println!("\nTesting edge case: {input} ({description})");
        match parse_command(input) {
            Ok(result) => {
                println!("  ✓ Parsed successfully:");
                println!("    Filter: {:?}", result.filter.is_some());
                println!("    Template: {:?}", result.template.is_some());
                println!("    Field selector: {:?}", result.field_selector.is_some());

                // Verify specific expectations for key cases
                match input {
                    "$1" | "$999" | "$00" | "$01" => {
                        assert!(result.template.is_some(), "{input} should be template");
                        if let Some(template) = result.template
                            && !template.items.is_empty()
                        {
                            match &template.items[0] {
                                TemplateItem::Literal(text) => assert_eq!(text, input),
                                _ => panic!("{input} should be literal"),
                            }
                        }
                    }
                    "${1}" | "${999}" | "${00}" | "${01}" => {
                        assert!(result.template.is_some(), "{input} should be template");
                        if let Some(template) = result.template
                            && !template.items.is_empty()
                        {
                            match &template.items[0] {
                                TemplateItem::Field(_) => {} // Expected
                                _ => panic!("{input} should be field substitution"),
                            }
                        }
                    }
                    "\"$20\"" => {
                        assert!(
                            result.field_selector.is_some(),
                            "{input} should be field selector"
                        );
                    }
                    _ => {} // Other cases just need to not crash
                }
            }
            Err(e) => {
                println!("  âš  Failed to parse: {e}");
                // Some edge cases may legitimately fail to parse
            }
        }
    }

    println!("\n=== Edge Case Tests Completed ===");
}

/// Test comprehensive syntax disambiguation across all DSL forms.
#[test]
fn test_comprehensive_disambiguation() {
    let test_cases = vec![
        // Templates with new syntax
        ("{${name}}", "template"),
        ("{State of ${name}}", "template"),
        ("$name", "template"),
        ("{name}", "literal_template"),
        // Field selectors
        ("name", "field_selector"),
        ("user.email", "field_selector"),
        ("\"field name\"", "field_selector"),
        // Filters
        ("name == \"Alice\"", "filter"),
        ("age > 25", "filter"),
        ("user.active == true", "filter"),
        // Note: bare top-level "${name}" is NOT included here - it has no
        // top-level template_expr alternative without the fallback; see
        // `bare_braced_named_variable_requires_p1_3` above.
    ];

    for (input, expected_type) in test_cases {
        let result = parse_command(input);

        match expected_type {
            "template" => {
                assert!(result.is_ok(), "Template '{input}' should parse");
                let parsed = result.unwrap();
                assert!(
                    parsed.template.is_some(),
                    "Input '{input}' should be template"
                );
                assert!(
                    parsed.filter.is_none(),
                    "Input '{input}' should not be filter"
                );
                assert!(
                    parsed.field_selector.is_none(),
                    "Input '{input}' should not be field selector"
                );
            }
            "field_selector" => {
                assert!(result.is_ok(), "Field selector '{input}' should parse");
                let parsed = result.unwrap();
                assert!(
                    parsed.field_selector.is_some(),
                    "Input '{input}' should be field selector"
                );
                assert!(
                    parsed.filter.is_none(),
                    "Input '{input}' should not be filter"
                );
                assert!(
                    parsed.template.is_none(),
                    "Input '{input}' should not be template"
                );
            }
            "filter" => {
                assert!(result.is_ok(), "Filter '{input}' should parse");
                let parsed = result.unwrap();
                assert!(parsed.filter.is_some(), "Input '{input}' should be filter");
                // Templates are now added by default for filters
                assert!(
                    parsed.template.is_some(),
                    "Input '{input}' should have a template (default templates are now added to filters)"
                );
                assert!(
                    parsed.field_selector.is_none(),
                    "Input '{input}' should not be field selector"
                );
            }
            "literal_template" => {
                assert!(result.is_ok(), "Literal template '{input}' should parse");
                let parsed = result.unwrap();
                assert!(
                    parsed.template.is_some(),
                    "Input '{input}' should be template"
                );
                assert!(
                    parsed.filter.is_none(),
                    "Input '{input}' should not be filter"
                );
                assert!(
                    parsed.field_selector.is_none(),
                    "Input '{input}' should not be field selector"
                );
                // Check that it's a literal, not a field
                let template = parsed.template.unwrap();
                if template.items.len() == 1 {
                    if let TemplateItem::Literal(_) = &template.items[0] {
                        // ok
                    } else {
                        panic!("Input '{input}' should be literal template, not field");
                    }
                }
            }
            _ => panic!("Unknown expected type: {expected_type}"),
        }
    }
}

/// Test that filter expressions work correctly.
#[test]
fn test_filter_expressions() {
    // Simple comparison
    let result = parse_command(r#"name == "Alice""#).unwrap();
    assert!(result.filter.is_some());
    assert!(result.template.is_some());
    assert!(result.field_selector.is_none());

    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["name"]);
        assert_eq!(op, ComparisonOp::Equal);
        assert_eq!(value, FilterValue::String("Alice".to_string()));
    } else {
        panic!("Expected simple comparison");
    }

    // Numeric comparison
    let result = parse_command("age > 25").unwrap();
    assert!(result.filter.is_some());
    assert!(result.template.is_some());
    assert!(result.field_selector.is_none());
}

/// Test complex boolean expressions.
#[test]
fn test_complex_boolean_expressions() {
    // Test field truthy parsing
    let result = parse_command("active?").unwrap();
    assert!(result.filter.is_some());

    if let Some(FilterExpr::FieldTruthy(field)) = result.filter {
        assert_eq!(field.parts, vec!["active"]);
    } else {
        panic!("Expected field truthy");
    }

    // Test NOT expressions
    let result = parse_command("!active?").unwrap();
    assert!(result.filter.is_some());

    if let Some(FilterExpr::Not(inner)) = result.filter {
        if let FilterExpr::FieldTruthy(field) = inner.as_ref() {
            assert_eq!(field.parts, vec!["active"]);
        } else {
            panic!("Expected NOT of field truthy");
        }
    } else {
        panic!("Expected NOT expression");
    }
}

/// Test nested field access in various contexts.
#[test]
fn test_nested_field_access() {
    // In filters
    let result = parse_command("user.email == \"alice@example.com\"").unwrap();
    if let Some(FilterExpr::Comparison { field, .. }) = result.filter {
        assert_eq!(field.parts, vec!["user", "email"]);
    } else {
        panic!("Expected comparison with nested field");
    }

    // In templates
    let result = parse_command("{${user.name}}").unwrap();
    let template = result.template.unwrap();
    match &template.items[0] {
        TemplateItem::Field(field) => assert_eq!(field.parts, vec!["user", "name"]),
        _ => panic!("Expected nested field"),
    }

    // In field selectors
    let result = parse_command("user.profile.name").unwrap();
    let field = result.field_selector.unwrap();
    assert_eq!(field.parts, vec!["user", "profile", "name"]);
}

/// Test bracketed template syntax.
#[test]
fn test_bracketed_template_syntax() {
    // Test simple bracketed template
    let result = parse_command("[${name}]").unwrap();
    assert!(result.template.is_some());
    assert!(result.filter.is_none());
    assert!(result.field_selector.is_none());

    let template = result.template.unwrap();
    assert_eq!(template.items.len(), 1);
    match &template.items[0] {
        TemplateItem::Field(field) => assert_eq!(field.parts, vec!["name"]),
        _ => panic!("Expected field"),
    }

    // Test mixed bracketed template
    let result = parse_command("[Name: ${name}, Age: ${age}]").unwrap();
    assert!(result.template.is_some());

    let template = result.template.unwrap();
    assert!(template.items.len() >= 3); // At least: literal, field, literal

    // Check that we have the expected content structure
    let mut found_name_field = false;
    let mut found_age_field = false;
    let mut found_literal_content = false;

    for item in &template.items {
        match item {
            TemplateItem::Field(field) => {
                if field.parts == vec!["name"] {
                    found_name_field = true;
                } else if field.parts == vec!["age"] {
                    found_age_field = true;
                }
            }
            TemplateItem::Literal(text) if (text.contains("Name:") || text.contains("Age:")) => {
                found_literal_content = true;
            }
            _ => {}
        }
    }

    assert!(found_name_field, "Should contain name field");
    assert!(found_age_field, "Should contain age field");
    assert!(found_literal_content, "Should contain literal content");
}

/// Test array element selection like users.0.name
#[test]
fn test_array_element_selection() {
    use parsm::filter::FieldPath;
    use serde_json::json;

    // Test array element selection like users.0.name
    let data = json!({
        "users": [
            {"name": "Alice", "age": 30},
            {"name": "Bob", "age": 25}
        ],
        "items": ["apple", "banana", "cherry"]
    });

    // Test users.0.name (nested array access)
    let field_path = FieldPath::new(vec![
        "users".to_string(),
        "0".to_string(),
        "name".to_string(),
    ]);
    let result = field_path.get_value(&data);
    assert_eq!(result, Some(&json!("Alice")));

    // Test users.1.name (second element)
    let field_path = FieldPath::new(vec![
        "users".to_string(),
        "1".to_string(),
        "name".to_string(),
    ]);
    let result = field_path.get_value(&data);
    assert_eq!(result, Some(&json!("Bob")));

    // Test items.0 (simple array access)
    let field_path = FieldPath::new(vec!["items".to_string(), "0".to_string()]);
    let result = field_path.get_value(&data);
    assert_eq!(result, Some(&json!("apple")));

    // Test parsing users.0.name as field selector
    let result = parse_command("users.0.name").unwrap();
    assert!(result.field_selector.is_some());
    assert!(result.filter.is_none());
    assert!(result.template.is_none());

    if let Some(field_selector) = result.field_selector {
        assert_eq!(field_selector.parts, vec!["users", "0", "name"]);
    }
}

/// Test regex matching with ~= operator
#[test]
fn test_regex_matching() {
    // Test regex literal with ~= operator
    let result = parse_command("name ~= /^[A-Z]/");

    match result {
        Ok(parsed) => {
            assert!(parsed.filter.is_some(), "Regex pattern should be filter");

            if let Some(FilterExpr::Comparison { field, op, value }) = parsed.filter {
                assert_eq!(field.parts, vec!["name"]);
                assert!(
                    matches!(op, ComparisonOp::Regex),
                    "Should be regex operator"
                );
                if let FilterValue::Regex { pattern, .. } = value {
                    assert!(pattern.contains("^[A-Z]"), "Should contain regex pattern");
                } else {
                    panic!("Expected regex value for regex pattern");
                }
            } else {
                panic!("Expected comparison expression with regex operator");
            }
        }
        Err(e) => {
            println!("Note: Regex parsing may not be fully implemented: {e}");
            // This test documents the expected behavior even if not fully implemented
        }
    }
}

/// Test all comparison operators in DSL
#[test]
fn test_all_comparison_operators() {
    // Test equality operator (==)
    let result = parse_command(r#"name == "Alice""#).unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["name"]);
        assert_eq!(op, ComparisonOp::Equal);
        assert_eq!(value, FilterValue::String("Alice".to_string()));
    } else {
        panic!("Expected equality comparison");
    }

    // Test not equal operator (!=)
    let result = parse_command(r#"name != "Bob""#).unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["name"]);
        assert_eq!(op, ComparisonOp::NotEqual);
        assert_eq!(value, FilterValue::String("Bob".to_string()));
    } else {
        panic!("Expected not equal comparison");
    }

    // Test less than operator (<)
    let result = parse_command("age < 30").unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["age"]);
        assert_eq!(op, ComparisonOp::LessThan);
        assert_eq!(value, FilterValue::Number(30.0));
    } else {
        panic!("Expected less than comparison");
    }

    // Test less than or equal operator (<=)
    let result = parse_command("age <= 30").unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["age"]);
        assert_eq!(op, ComparisonOp::LessThanOrEqual);
        assert_eq!(value, FilterValue::Number(30.0));
    } else {
        panic!("Expected less than or equal comparison");
    }

    // Test greater than operator (>)
    let result = parse_command("age > 25").unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["age"]);
        assert_eq!(op, ComparisonOp::GreaterThan);
        assert_eq!(value, FilterValue::Number(25.0));
    } else {
        panic!("Expected greater than comparison");
    }

    // Test greater than or equal operator (>=)
    let result = parse_command("age >= 25").unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["age"]);
        assert_eq!(op, ComparisonOp::GreaterThanOrEqual);
        assert_eq!(value, FilterValue::Number(25.0));
    } else {
        panic!("Expected greater than or equal comparison");
    }

    // Test contains operator (*=)
    let result = parse_command(r#"name *= "lic""#).unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["name"]);
        assert_eq!(op, ComparisonOp::Contains);
        assert_eq!(value, FilterValue::String("lic".to_string()));
    } else {
        panic!("Expected contains comparison");
    }

    // Test starts with operator (^=)
    let result = parse_command(r#"name ^= "Al""#).unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["name"]);
        assert_eq!(op, ComparisonOp::StartsWith);
        assert_eq!(value, FilterValue::String("Al".to_string()));
    } else {
        panic!("Expected starts with comparison");
    }

    // Test ends with operator ($=)
    let result = parse_command(r#"name $= "ice""#).unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["name"]);
        assert_eq!(op, ComparisonOp::EndsWith);
        assert_eq!(value, FilterValue::String("ice".to_string()));
    } else {
        panic!("Expected ends with comparison");
    }

    // Test regex operator (~=)
    let result = parse_command(r#"email ~= "@.*\.com$""#).unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["email"]);
        assert_eq!(op, ComparisonOp::Regex);
        assert_eq!(value, FilterValue::String("@.*\\.com$".to_string()));
    } else {
        panic!("Expected regex comparison");
    }
}

/// Test operator parsing with different value types
#[test]
fn test_operators_with_different_value_types() {
    // String values
    let result = parse_command(r#"name == "Alice""#).unwrap();
    assert!(result.filter.is_some());

    // Numeric values
    let result = parse_command("age >= 18").unwrap();
    assert!(result.filter.is_some());

    // Boolean values
    let result = parse_command("active == true").unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["active"]);
        assert_eq!(op, ComparisonOp::Equal);
        assert_eq!(value, FilterValue::Boolean(true));
    } else {
        panic!("Expected boolean comparison");
    }

    let result = parse_command("active != false").unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["active"]);
        assert_eq!(op, ComparisonOp::NotEqual);
        assert_eq!(value, FilterValue::Boolean(false));
    } else {
        panic!("Expected boolean not equal comparison");
    }

    // Decimal numbers
    let result = parse_command("score <= 98.5").unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison { field, op, value }) = result.filter {
        assert_eq!(field.parts, vec!["score"]);
        assert_eq!(op, ComparisonOp::LessThanOrEqual);
        assert_eq!(value, FilterValue::Number(98.5));
    } else {
        panic!("Expected decimal number comparison");
    }
}

/// Test operator precedence and spacing
#[test]
fn test_operator_precedence_and_spacing() {
    // Test that multi-character operators are parsed correctly even without spaces
    let result = parse_command("age>=25").unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison {
        field: _,
        op,
        value: _,
    }) = result.filter
    {
        assert_eq!(op, ComparisonOp::GreaterThanOrEqual);
    } else {
        panic!("Expected >= operator parsing without spaces");
    }

    // Test that <= is parsed correctly
    let result = parse_command("age<=30").unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison {
        field: _,
        op,
        value: _,
    }) = result.filter
    {
        assert_eq!(op, ComparisonOp::LessThanOrEqual);
    } else {
        panic!("Expected <= operator parsing without spaces");
    }

    // Test that != is parsed correctly
    let result = parse_command(r#"name!="Bob""#).unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison {
        field: _,
        op,
        value: _,
    }) = result.filter
    {
        assert_eq!(op, ComparisonOp::NotEqual);
    } else {
        panic!("Expected != operator parsing without spaces");
    }

    // Test single character operators with spaces (required for disambiguation)
    let result = parse_command("age < 30").unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison {
        field: _,
        op,
        value: _,
    }) = result.filter
    {
        assert_eq!(op, ComparisonOp::LessThan);
    } else {
        panic!("Expected < operator with spaces");
    }

    let result = parse_command("age > 25").unwrap();
    assert!(result.filter.is_some());
    if let Some(FilterExpr::Comparison {
        field: _,
        op,
        value: _,
    }) = result.filter
    {
        assert_eq!(op, ComparisonOp::GreaterThan);
    } else {
        panic!("Expected > operator with spaces");
    }
}