automapper-validation 0.1.66

AHB condition expression parsing, evaluation, and EDIFACT validation
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
//! Recursive descent parser for condition expressions.
//!
//! Grammar (from lowest to highest precedence):
//!
//! ```text
//! expression  = xor_expr
//! xor_expr    = or_expr (XOR or_expr)*
//! or_expr     = and_expr (OR and_expr)*
//! and_expr    = not_expr ((AND | implicit) not_expr)*
//! not_expr    = NOT not_expr | primary
//! primary     = CONDITION_ID | '(' expression ')'
//! ```
//!
//! Implicit AND: two adjacent condition references or a condition followed by
//! `(` without an intervening operator are treated as AND.

use std::collections::HashMap;

use super::ast::ConditionExpr;
use super::token::{strip_status_prefix, tokenize, SpannedToken, Token};
use crate::error::ParseError;

/// Parser for AHB condition expressions.
pub struct ConditionParser;

impl ConditionParser {
    /// Parse an AHB status string into a condition expression.
    ///
    /// Returns `Ok(None)` if the input contains no condition references
    /// (e.g., bare `"Muss"` or empty string).
    ///
    /// # Examples
    ///
    /// ```
    /// use automapper_validation::expr::ConditionParser;
    /// use automapper_validation::expr::ConditionExpr;
    ///
    /// let expr = ConditionParser::parse("Muss [494]").unwrap().unwrap();
    /// assert_eq!(expr, ConditionExpr::Ref(494));
    /// ```
    pub fn parse(input: &str) -> Result<Option<ConditionExpr>, ParseError> {
        Self::parse_with_ub(input, &HashMap::new())
    }

    /// Parse an AHB status string, expanding UB condition references inline.
    ///
    /// When `[UB1]` is encountered and `ub_definitions` contains "UB1", the
    /// corresponding pre-parsed expression is substituted. Unknown UB references
    /// fall back to the normal `parse_condition_id` behavior.
    pub fn parse_with_ub(
        input: &str,
        ub_definitions: &HashMap<String, ConditionExpr>,
    ) -> Result<Option<ConditionExpr>, ParseError> {
        let input = input.trim();
        if input.is_empty() {
            return Ok(None);
        }

        // AHB_Status can carry alternative branches on separate lines, each with its
        // own status prefix, e.g.
        //     Muss [315] ∧ [707]
        //     Soll [8] ∧ [301] ∧ [707]
        // The branches form a disjunction: the group/field is required if any
        // branch's condition holds. Parse each non-empty line separately and OR
        // the results together. A single-line input behaves identically to the
        // pre-existing single-expression path.
        let lines: Vec<&str> = input
            .lines()
            .map(str::trim)
            .filter(|l| !l.is_empty())
            .collect();

        let mut alternatives: Vec<ConditionExpr> = Vec::new();
        for line in &lines {
            let stripped = strip_status_prefix(line);
            if stripped.is_empty() {
                continue;
            }
            let tokens = tokenize(stripped)?;
            if tokens.is_empty() {
                continue;
            }
            let mut pos = 0;
            if let Some(expr) = parse_expression(&tokens, &mut pos, ub_definitions)? {
                alternatives.push(expr);
            }
        }

        match alternatives.len() {
            0 => Ok(None),
            1 => Ok(Some(alternatives.into_iter().next().unwrap())),
            _ => Ok(Some(ConditionExpr::Or(alternatives))),
        }
    }

    /// Parse an expression that is known to contain conditions (no prefix stripping).
    ///
    /// Returns `Err` if the input cannot be parsed. Returns `Ok(None)` if empty.
    pub fn parse_raw(input: &str) -> Result<Option<ConditionExpr>, ParseError> {
        let input = input.trim();
        if input.is_empty() {
            return Ok(None);
        }

        let tokens = tokenize(input)?;
        if tokens.is_empty() {
            return Ok(None);
        }

        let mut pos = 0;
        let expr = parse_expression(&tokens, &mut pos, &HashMap::new())?;

        Ok(expr)
    }
}

/// Parse a full expression (entry point for precedence climbing).
fn parse_expression(
    tokens: &[SpannedToken],
    pos: &mut usize,
    ub_definitions: &HashMap<String, ConditionExpr>,
) -> Result<Option<ConditionExpr>, ParseError> {
    parse_xor(tokens, pos, ub_definitions)
}

/// XOR has the lowest precedence.
fn parse_xor(
    tokens: &[SpannedToken],
    pos: &mut usize,
    ub_definitions: &HashMap<String, ConditionExpr>,
) -> Result<Option<ConditionExpr>, ParseError> {
    let mut left = match parse_or(tokens, pos, ub_definitions)? {
        Some(expr) => expr,
        None => return Ok(None),
    };

    while *pos < tokens.len() && tokens[*pos].token == Token::Xor {
        *pos += 1; // consume XOR
        let right = match parse_or(tokens, pos, ub_definitions)? {
            Some(expr) => expr,
            None => return Ok(Some(left)),
        };
        left = ConditionExpr::Xor(Box::new(left), Box::new(right));
    }

    Ok(Some(left))
}

/// OR has middle-low precedence.
fn parse_or(
    tokens: &[SpannedToken],
    pos: &mut usize,
    ub_definitions: &HashMap<String, ConditionExpr>,
) -> Result<Option<ConditionExpr>, ParseError> {
    let mut left = match parse_and(tokens, pos, ub_definitions)? {
        Some(expr) => expr,
        None => return Ok(None),
    };

    while *pos < tokens.len() && tokens[*pos].token == Token::Or {
        *pos += 1; // consume OR
        let right = match parse_and(tokens, pos, ub_definitions)? {
            Some(expr) => expr,
            None => return Ok(Some(left)),
        };
        // Flatten nested ORs into a single Or(vec![...])
        left = match left {
            ConditionExpr::Or(mut exprs) => {
                exprs.push(right);
                ConditionExpr::Or(exprs)
            }
            _ => ConditionExpr::Or(vec![left, right]),
        };
    }

    Ok(Some(left))
}

/// AND has middle-high precedence. Also handles implicit AND between adjacent
/// conditions or parenthesized groups.
fn parse_and(
    tokens: &[SpannedToken],
    pos: &mut usize,
    ub_definitions: &HashMap<String, ConditionExpr>,
) -> Result<Option<ConditionExpr>, ParseError> {
    let mut left = match parse_not(tokens, pos, ub_definitions)? {
        Some(expr) => expr,
        None => return Ok(None),
    };

    while *pos < tokens.len() {
        if tokens[*pos].token == Token::And {
            *pos += 1; // consume explicit AND
            let right = match parse_not(tokens, pos, ub_definitions)? {
                Some(expr) => expr,
                None => return Ok(Some(left)),
            };
            left = flatten_and(left, right);
        } else if matches!(
            tokens[*pos].token,
            Token::ConditionId(_) | Token::LeftParen | Token::Not
        ) {
            // Implicit AND: adjacent condition, paren, or NOT without operator
            let right = match parse_not(tokens, pos, ub_definitions)? {
                Some(expr) => expr,
                None => return Ok(Some(left)),
            };
            left = flatten_and(left, right);
        } else {
            break;
        }
    }

    Ok(Some(left))
}

/// Flatten nested ANDs into a single And(vec![...]).
fn flatten_and(left: ConditionExpr, right: ConditionExpr) -> ConditionExpr {
    match left {
        ConditionExpr::And(mut exprs) => {
            exprs.push(right);
            ConditionExpr::And(exprs)
        }
        _ => ConditionExpr::And(vec![left, right]),
    }
}

/// NOT has the highest precedence (unary prefix).
fn parse_not(
    tokens: &[SpannedToken],
    pos: &mut usize,
    ub_definitions: &HashMap<String, ConditionExpr>,
) -> Result<Option<ConditionExpr>, ParseError> {
    if *pos < tokens.len() && tokens[*pos].token == Token::Not {
        *pos += 1; // consume NOT
        let inner = match parse_not(tokens, pos, ub_definitions)? {
            Some(expr) => expr,
            None => {
                return Err(ParseError::UnexpectedToken {
                    position: if *pos < tokens.len() {
                        tokens[*pos].position
                    } else {
                        0
                    },
                    expected: "expression after NOT".to_string(),
                    found: "end of input".to_string(),
                });
            }
        };
        return Ok(Some(ConditionExpr::Not(Box::new(inner))));
    }
    parse_primary(tokens, pos, ub_definitions)
}

/// Primary: a condition reference or a parenthesized expression.
///
/// When a `ConditionId` matches a key in `ub_definitions`, the pre-parsed
/// UB expression is substituted inline instead of calling `parse_condition_id`.
fn parse_primary(
    tokens: &[SpannedToken],
    pos: &mut usize,
    ub_definitions: &HashMap<String, ConditionExpr>,
) -> Result<Option<ConditionExpr>, ParseError> {
    if *pos >= tokens.len() {
        return Ok(None);
    }

    match &tokens[*pos].token {
        Token::ConditionId(id) => {
            *pos += 1;
            // Check for UB expansion before falling back to parse_condition_id
            if let Some(ub_expr) = ub_definitions.get(id.as_str()) {
                return Ok(Some(ub_expr.clone()));
            }
            Ok(Some(parse_condition_id(id)))
        }
        Token::LeftParen => {
            *pos += 1; // consume (
            let expr = parse_expression(tokens, pos, ub_definitions)?;
            // Consume closing paren if present (graceful handling of missing)
            if *pos < tokens.len() && tokens[*pos].token == Token::RightParen {
                *pos += 1;
            }
            Ok(expr)
        }
        _ => Ok(None),
    }
}

/// Parse a condition ID string into a ConditionExpr.
///
/// Numeric IDs become `Ref(n)`. Non-numeric IDs (like `UB1`, `10P1..5`)
/// are kept as-is by extracting numeric portions. For the Rust port,
/// pure numeric IDs use `Ref(u32)`. Non-numeric IDs extract leading
/// digits if present, otherwise use 0 as a sentinel.
fn parse_condition_id(id: &str) -> ConditionExpr {
    // Try pure numeric ID first
    if let Ok(num) = id.parse::<u32>() {
        return ConditionExpr::Ref(num);
    }

    // Check for package condition: NP or NPmin..max
    if let Some(p_pos) = id.find('P') {
        let num_part = &id[..p_pos];
        let range_part = &id[p_pos + 1..];
        if let Ok(pkg_id) = num_part.parse::<u32>() {
            let (min, max) = parse_package_range(range_part);
            return ConditionExpr::Package {
                id: pkg_id,
                min,
                max,
            };
        }
    }

    // For non-numeric, non-package IDs (e.g., "UB1"), extract leading digits
    let numeric_part: String = id.chars().take_while(|c| c.is_ascii_digit()).collect();
    if let Ok(num) = numeric_part.parse::<u32>() {
        ConditionExpr::Ref(num)
    } else {
        ConditionExpr::Ref(0)
    }
}

/// Parse the range part of a package condition: `"0..1"` → `(0, 1)`, `""` → `(0, MAX)`.
fn parse_package_range(range: &str) -> (u32, u32) {
    if range.is_empty() {
        return (0, u32::MAX);
    }
    if let Some((min_str, max_str)) = range.split_once("..") {
        let min = min_str.parse::<u32>().unwrap_or(0);
        let max = max_str.parse::<u32>().unwrap_or(u32::MAX);
        (min, max)
    } else {
        let n = range.parse::<u32>().unwrap_or(0);
        (n, n)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use pretty_assertions::assert_eq;

    // === Basic parsing ===

    #[test]
    fn test_parse_single_condition() {
        let result = ConditionParser::parse("[931]").unwrap().unwrap();
        assert_eq!(result, ConditionExpr::Ref(931));
    }

    #[test]
    fn test_parse_with_muss_prefix() {
        let result = ConditionParser::parse("Muss [494]").unwrap().unwrap();
        assert_eq!(result, ConditionExpr::Ref(494));
    }

    #[test]
    fn test_parse_with_soll_prefix() {
        let result = ConditionParser::parse("Soll [494]").unwrap().unwrap();
        assert_eq!(result, ConditionExpr::Ref(494));
    }

    #[test]
    fn test_parse_with_kann_prefix() {
        let result = ConditionParser::parse("Kann [182]").unwrap().unwrap();
        assert_eq!(result, ConditionExpr::Ref(182));
    }

    #[test]
    fn test_parse_with_x_prefix() {
        let result = ConditionParser::parse("X [567]").unwrap().unwrap();
        assert_eq!(result, ConditionExpr::Ref(567));
    }

    // === Binary operators ===

    #[test]
    fn test_parse_simple_and() {
        let result = ConditionParser::parse("[182] ∧ [152]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::And(vec![ConditionExpr::Ref(182), ConditionExpr::Ref(152)])
        );
    }

    #[test]
    fn test_parse_simple_or() {
        let result = ConditionParser::parse("[1] ∨ [2]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::Or(vec![ConditionExpr::Ref(1), ConditionExpr::Ref(2)])
        );
    }

    #[test]
    fn test_parse_simple_xor() {
        let result = ConditionParser::parse("[1] ⊻ [2]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::Xor(
                Box::new(ConditionExpr::Ref(1)),
                Box::new(ConditionExpr::Ref(2)),
            )
        );
    }

    // === Chained operators ===

    #[test]
    fn test_parse_three_way_and() {
        let result = ConditionParser::parse("[1] ∧ [2] ∧ [3]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::And(vec![
                ConditionExpr::Ref(1),
                ConditionExpr::Ref(2),
                ConditionExpr::Ref(3),
            ])
        );
    }

    #[test]
    fn test_parse_three_way_and_with_prefix() {
        let result = ConditionParser::parse("Kann [182] ∧ [6] ∧ [570]")
            .unwrap()
            .unwrap();
        assert_eq!(
            result,
            ConditionExpr::And(vec![
                ConditionExpr::Ref(182),
                ConditionExpr::Ref(6),
                ConditionExpr::Ref(570),
            ])
        );
        assert_eq!(result.condition_ids(), [6, 182, 570].into());
    }

    #[test]
    fn test_parse_multiple_xor() {
        let result = ConditionParser::parse("[1] ⊻ [2] ⊻ [3] ⊻ [4]")
            .unwrap()
            .unwrap();
        assert_eq!(result.condition_ids(), [1, 2, 3, 4].into());
    }

    // === Parentheses ===

    #[test]
    fn test_parse_parenthesized_expression() {
        let result = ConditionParser::parse("([1] ∨ [2]) ∧ [3]")
            .unwrap()
            .unwrap();
        assert_eq!(
            result,
            ConditionExpr::And(vec![
                ConditionExpr::Or(vec![ConditionExpr::Ref(1), ConditionExpr::Ref(2)]),
                ConditionExpr::Ref(3),
            ])
        );
    }

    #[test]
    fn test_parse_nested_parentheses() {
        // (([1] ∧ [2]) ∨ ([3] ∧ [4])) ∧ [5]
        let result = ConditionParser::parse("(([1] ∧ [2]) ∨ ([3] ∧ [4])) ∧ [5]")
            .unwrap()
            .unwrap();
        assert_eq!(result.condition_ids(), [1, 2, 3, 4, 5].into());
        // Outer is AND
        match &result {
            ConditionExpr::And(exprs) => {
                assert_eq!(exprs.len(), 2);
                assert!(matches!(&exprs[0], ConditionExpr::Or(_)));
                assert_eq!(exprs[1], ConditionExpr::Ref(5));
            }
            other => panic!("Expected And, got {other:?}"),
        }
    }

    // === Operator precedence ===

    #[test]
    fn test_and_has_higher_precedence_than_or() {
        // [1] ∨ [2] ∧ [3] should parse as [1] ∨ ([2] ∧ [3])
        let result = ConditionParser::parse("[1] ∨ [2] ∧ [3]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::Or(vec![
                ConditionExpr::Ref(1),
                ConditionExpr::And(vec![ConditionExpr::Ref(2), ConditionExpr::Ref(3)]),
            ])
        );
    }

    #[test]
    fn test_or_has_higher_precedence_than_xor() {
        // [1] ⊻ [2] ∨ [3] should parse as [1] ⊻ ([2] ∨ [3])
        let result = ConditionParser::parse("[1] ⊻ [2] ∨ [3]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::Xor(
                Box::new(ConditionExpr::Ref(1)),
                Box::new(ConditionExpr::Or(vec![
                    ConditionExpr::Ref(2),
                    ConditionExpr::Ref(3),
                ])),
            )
        );
    }

    // === Implicit AND ===

    #[test]
    fn test_adjacent_conditions_implicit_and() {
        // "[1] [2]" is equivalent to "[1] ∧ [2]"
        let result = ConditionParser::parse("[1] [2]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::And(vec![ConditionExpr::Ref(1), ConditionExpr::Ref(2)])
        );
    }

    #[test]
    fn test_adjacent_conditions_no_space_implicit_and() {
        // "[939][14]" from real AHB XML
        let result = ConditionParser::parse("[939][14]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::And(vec![ConditionExpr::Ref(939), ConditionExpr::Ref(14)])
        );
    }

    // === NOT operator ===

    #[test]
    fn test_parse_not() {
        let result = ConditionParser::parse("NOT [1]").unwrap().unwrap();
        assert_eq!(result, ConditionExpr::Not(Box::new(ConditionExpr::Ref(1))));
    }

    #[test]
    fn test_parse_not_with_and() {
        // NOT [1] ∧ [2] should parse as (NOT [1]) ∧ [2] because NOT has highest precedence
        let result = ConditionParser::parse("NOT [1] ∧ [2]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::And(vec![
                ConditionExpr::Not(Box::new(ConditionExpr::Ref(1))),
                ConditionExpr::Ref(2),
            ])
        );
    }

    // === Real-world AHB expressions ===

    #[test]
    fn test_real_world_orders_expression() {
        // From ORDERS AHB: "X (([939] [147]) ∨ ([940] [148])) ∧ [567]"
        let result = ConditionParser::parse("X (([939] [147]) ∨ ([940] [148])) ∧ [567]")
            .unwrap()
            .unwrap();
        assert_eq!(result.condition_ids(), [147, 148, 567, 939, 940].into());
    }

    #[test]
    fn test_real_world_xor_expression() {
        // "Muss ([102] ∧ [2006]) ⊻ ([103] ∧ [2005])"
        let result = ConditionParser::parse("Muss ([102] ∧ [2006]) ⊻ ([103] ∧ [2005])")
            .unwrap()
            .unwrap();
        assert!(matches!(result, ConditionExpr::Xor(_, _)));
        assert_eq!(result.condition_ids(), [102, 103, 2005, 2006].into());
    }

    #[test]
    fn test_real_world_complex_nested_with_implicit_and() {
        // "([939][14]) ∨ ([940][15])"
        let result = ConditionParser::parse("([939][14]) ∨ ([940][15])")
            .unwrap()
            .unwrap();
        assert!(matches!(result, ConditionExpr::Or(_)));
        assert_eq!(result.condition_ids(), [14, 15, 939, 940].into());
    }

    // === Edge cases ===

    #[test]
    fn test_parse_empty_string() {
        assert!(ConditionParser::parse("").unwrap().is_none());
    }

    #[test]
    fn test_parse_whitespace_only() {
        assert!(ConditionParser::parse("   \t  ").unwrap().is_none());
    }

    #[test]
    fn test_parse_bare_muss() {
        assert!(ConditionParser::parse("Muss").unwrap().is_none());
    }

    #[test]
    fn test_parse_bare_x() {
        // "X" alone has no conditions after it
        assert!(ConditionParser::parse("X").unwrap().is_none());
    }

    #[test]
    fn test_parse_unmatched_open_paren_graceful() {
        // ([1] ∧ [2] — missing closing paren
        let result = ConditionParser::parse("([1] ∧ [2]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::And(vec![ConditionExpr::Ref(1), ConditionExpr::Ref(2)])
        );
    }

    #[test]
    fn test_parse_text_and_operator() {
        let result = ConditionParser::parse("[1] AND [2]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::And(vec![ConditionExpr::Ref(1), ConditionExpr::Ref(2)])
        );
    }

    #[test]
    fn test_parse_text_or_operator() {
        let result = ConditionParser::parse("[1] OR [2]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::Or(vec![ConditionExpr::Ref(1), ConditionExpr::Ref(2)])
        );
    }

    #[test]
    fn test_parse_text_xor_operator() {
        let result = ConditionParser::parse("[1] XOR [2]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::Xor(
                Box::new(ConditionExpr::Ref(1)),
                Box::new(ConditionExpr::Ref(2)),
            )
        );
    }

    #[test]
    fn test_parse_mixed_unicode_and_text_operators() {
        let result = ConditionParser::parse("[1] ∧ [2] OR [3]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::Or(vec![
                ConditionExpr::And(vec![ConditionExpr::Ref(1), ConditionExpr::Ref(2)]),
                ConditionExpr::Ref(3),
            ])
        );
    }

    #[test]
    fn test_parse_deeply_nested() {
        // ((([1])))
        let result = ConditionParser::parse("((([1])))").unwrap().unwrap();
        assert_eq!(result, ConditionExpr::Ref(1));
    }

    // === Package conditions ===

    #[test]
    fn test_parse_package_condition_0_1() {
        let result = ConditionParser::parse("[4P0..1]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::Package {
                id: 4,
                min: 0,
                max: 1
            }
        );
    }

    #[test]
    fn test_parse_package_condition_1_5() {
        let result = ConditionParser::parse("[10P1..5]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::Package {
                id: 10,
                min: 1,
                max: 5
            }
        );
    }

    #[test]
    fn test_parse_package_in_expression() {
        let result = ConditionParser::parse("X [4P0..1] ⊻ [5P0..1]")
            .unwrap()
            .unwrap();
        assert_eq!(
            result,
            ConditionExpr::Xor(
                Box::new(ConditionExpr::Package {
                    id: 4,
                    min: 0,
                    max: 1
                }),
                Box::new(ConditionExpr::Package {
                    id: 5,
                    min: 0,
                    max: 1
                }),
            )
        );
    }

    #[test]
    fn test_parse_package_bare_p() {
        let result = ConditionParser::parse("[1P]").unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::Package {
                id: 1,
                min: 0,
                max: u32::MAX
            }
        );
    }

    #[test]
    fn test_condition_ids_extraction_full() {
        let result = ConditionParser::parse("Muss ([102] ∧ [2006]) ⊻ ([103] ∧ [2005])")
            .unwrap()
            .unwrap();
        let ids = result.condition_ids();
        assert!(ids.contains(&102));
        assert!(ids.contains(&103));
        assert!(ids.contains(&2005));
        assert!(ids.contains(&2006));
        assert_eq!(ids.len(), 4);
    }

    // === UB inline expansion ===

    #[test]
    fn test_parse_ub_inline_expansion() {
        let ub1_expr = ConditionParser::parse("[931] ∧ [932]").unwrap().unwrap();
        let mut ub_map = HashMap::new();
        ub_map.insert("UB1".to_string(), ub1_expr.clone());

        let result = ConditionParser::parse_with_ub("X [UB1]", &ub_map)
            .unwrap()
            .unwrap();
        assert_eq!(result, ub1_expr);
    }

    #[test]
    fn test_parse_ub_unknown_falls_back() {
        let ub_map = HashMap::new();
        let result = ConditionParser::parse_with_ub("[UB99]", &ub_map)
            .unwrap()
            .unwrap();
        assert_eq!(result, ConditionExpr::Ref(0));
    }

    #[test]
    fn test_parse_with_ub_empty_map_same_as_parse() {
        let ub_map = HashMap::new();
        // Normal conditions should work unchanged
        let result = ConditionParser::parse_with_ub("X [931] ∧ [932]", &ub_map)
            .unwrap()
            .unwrap();
        let expected = ConditionParser::parse("X [931] ∧ [932]").unwrap().unwrap();
        assert_eq!(result, expected);
    }

    #[test]
    fn test_parse_ub_in_complex_expression() {
        // UB expands inside a larger expression
        let ub1_expr = ConditionParser::parse("[931] ∧ [932]").unwrap().unwrap();
        let mut ub_map = HashMap::new();
        ub_map.insert("UB1".to_string(), ub1_expr);

        let result = ConditionParser::parse_with_ub("X [UB1] ∨ [100]", &ub_map)
            .unwrap()
            .unwrap();
        // Should be: ([931] ∧ [932]) ∨ [100]
        assert_eq!(
            result,
            ConditionExpr::Or(vec![
                ConditionExpr::And(vec![ConditionExpr::Ref(931), ConditionExpr::Ref(932)]),
                ConditionExpr::Ref(100),
            ])
        );
    }

    #[test]
    fn test_parse_ub_multiple_references() {
        // Two different UB references in one expression
        let ub1_expr = ConditionParser::parse("[931]").unwrap().unwrap();
        let ub2_expr = ConditionParser::parse("[932]").unwrap().unwrap();
        let mut ub_map = HashMap::new();
        ub_map.insert("UB1".to_string(), ub1_expr);
        ub_map.insert("UB2".to_string(), ub2_expr);

        let result = ConditionParser::parse_with_ub("X [UB1] ∧ [UB2]", &ub_map)
            .unwrap()
            .unwrap();
        assert_eq!(
            result,
            ConditionExpr::And(vec![ConditionExpr::Ref(931), ConditionExpr::Ref(932)])
        );
    }

    #[test]
    fn test_parse_multi_line_alternatives_are_or() {
        // AHB_Status with alternative branches on separate lines, each with its
        // own status prefix. Branches form a disjunction (at least one must hold).
        let status = "Muss [315] ∧ [707]\nSoll [8] ∧ [301] ∧ [707]";
        let result = ConditionParser::parse(status).unwrap().unwrap();
        assert_eq!(
            result,
            ConditionExpr::Or(vec![
                ConditionExpr::And(vec![ConditionExpr::Ref(315), ConditionExpr::Ref(707)]),
                ConditionExpr::And(vec![
                    ConditionExpr::Ref(8),
                    ConditionExpr::Ref(301),
                    ConditionExpr::Ref(707),
                ]),
            ])
        );
    }

    #[test]
    fn test_parse_multi_line_with_crlf() {
        // XML parsing produces \r\n line endings for multi-line AHB_Status values.
        let result = ConditionParser::parse("Muss [10]\r\nSoll [20]")
            .unwrap()
            .unwrap();
        assert_eq!(
            result,
            ConditionExpr::Or(vec![ConditionExpr::Ref(10), ConditionExpr::Ref(20)])
        );
    }

    #[test]
    fn test_parse_single_line_unchanged() {
        // Single-line inputs continue to produce a bare expression (not wrapped in Or).
        let result = ConditionParser::parse("Muss [315] ∧ [707]")
            .unwrap()
            .unwrap();
        assert_eq!(
            result,
            ConditionExpr::And(vec![ConditionExpr::Ref(315), ConditionExpr::Ref(707)])
        );
    }
}