automapper-validation 0.2.0

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
//! Format validation helpers for AHB 900-series conditions.
//!
//! These validate the FORMAT of data element values (decimal places, numeric ranges,
//! time patterns, ID formats, etc.). They operate on string values extracted from
//! EDIFACT segments and return `ConditionResult`.

use super::evaluator::ConditionResult;

// Re-export timezone helpers so generated code can use `use crate::eval::format_validators::*`
pub use super::timezone::{dst_transitions_between, is_mesz_utc, is_mez_utc, parse_dtm303};
pub use super::werktag::{
    compute_easter, is_german_holiday, is_werktag, parse_ccyymmdd_prefix, werktage_between,
};

// --- Decimal/digit place validation ---

/// Validate that a numeric string has at most `max` decimal places.
///
/// Returns `True` if the value has <= max decimal places (or no decimal point),
/// `False` if it has more, `Unknown` if the value is empty.
///
/// Example: `validate_max_decimal_places("123.45", 2)` → True
/// Example: `validate_max_decimal_places("123.456", 2)` → False
/// Example: `validate_max_decimal_places("123", 2)` → True (no decimal → 0 places)
pub fn validate_max_decimal_places(value: &str, max: usize) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    let decimal_places = match value.find('.') {
        Some(pos) => value.len() - pos - 1,
        None => 0,
    };
    ConditionResult::from(decimal_places <= max)
}

/// Validate that a numeric string has at most `max` integer digits (before decimal point).
///
/// Ignores leading minus sign.
pub fn validate_max_integer_digits(value: &str, max: usize) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    let s = value.strip_prefix('-').unwrap_or(value);
    let integer_part = match s.find('.') {
        Some(pos) => &s[..pos],
        None => s,
    };
    ConditionResult::from(integer_part.len() <= max)
}

// --- Numeric range validation ---

/// Validate a numeric value against a comparison.
///
/// `op` is one of: "==", "!=", ">", ">=", "<", "<="
/// Returns `Unknown` if the value cannot be parsed as a number.
///
/// Example: `validate_numeric(value, ">=", 0.0)` for "Wert >= 0"
/// Example: `validate_numeric(value, "==", 1.0)` for "Wert = 1"
pub fn validate_numeric(value: &str, op: &str, threshold: f64) -> ConditionResult {
    let parsed = match value.parse::<f64>() {
        Ok(v) => v,
        Err(_) => return ConditionResult::Unknown,
    };
    let result = match op {
        "==" => (parsed - threshold).abs() < f64::EPSILON,
        "!=" => (parsed - threshold).abs() >= f64::EPSILON,
        ">" => parsed > threshold,
        ">=" => parsed >= threshold,
        "<" => parsed < threshold,
        "<=" => parsed <= threshold,
        _ => return ConditionResult::Unknown,
    };
    ConditionResult::from(result)
}

// --- DTM time/timezone validation ---

/// Validate that a DTM value's HHMM portion equals the expected value.
///
/// DTM format 303 is CCYYMMDDHHMM (12 chars) or CCYYMMDDHHMMZZZ (15 chars with timezone).
/// Extracts characters at positions 8..12 (HHMM) for comparison.
///
/// Example: `validate_hhmm_equals("202601012200+00", "2200")` → True
pub fn validate_hhmm_equals(dtm_value: &str, expected_hhmm: &str) -> ConditionResult {
    if dtm_value.len() < 12 {
        // Value too short — no HHMM component present, condition is not met
        return ConditionResult::False;
    }
    ConditionResult::from(&dtm_value[8..12] == expected_hhmm)
}

/// Validate that a DTM value's HHMM portion is within a range (inclusive).
///
/// Example: `validate_hhmm_range("202601011530+00", "0000", "2359")` → True
pub fn validate_hhmm_range(dtm_value: &str, min: &str, max: &str) -> ConditionResult {
    if dtm_value.len() < 12 {
        return ConditionResult::False;
    }
    let hhmm = &dtm_value[8..12];
    ConditionResult::from(hhmm >= min && hhmm <= max)
}

/// Validate that a DTM value's MMDDHHMM portion equals the expected value.
///
/// Extracts characters at positions 4..12 for comparison.
///
/// Example: `validate_mmddhhmm_equals("202612312300+00", "12312300")` → True
pub fn validate_mmddhhmm_equals(dtm_value: &str, expected: &str) -> ConditionResult {
    if dtm_value.len() < 12 {
        return ConditionResult::False;
    }
    ConditionResult::from(&dtm_value[4..12] == expected)
}

/// Validate that a DTM value's timezone portion is "+00" (UTC).
///
/// DTM format 303 with timezone: CCYYMMDDHHMM+ZZ or CCYYMMDDHHMM-ZZ (15 chars).
/// Checks that the last 3 characters are "+00".
///
/// Example: `validate_timezone_utc("202601012200+00")` → True
/// Example: `validate_timezone_utc("202601012200+01")` → False
pub fn validate_timezone_utc(dtm_value: &str) -> ConditionResult {
    if dtm_value.len() < 15 {
        // Value too short — no timezone suffix present, condition is not met
        return ConditionResult::False;
    }
    ConditionResult::from(&dtm_value[12..] == "+00")
}

// --- Contact format validation ---

/// Validate email format: must contain both '@' and '.'.
///
/// Example: `validate_email("user@example.com")` → True
pub fn validate_email(value: &str) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    ConditionResult::from(value.contains('@') && value.contains('.'))
}

/// Validate phone format: must start with '+' followed by only digits.
///
/// Example: `validate_phone("+4930123456")` → True
/// Example: `validate_phone("030123456")` → False
pub fn validate_phone(value: &str) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    if !value.starts_with('+') || value.len() < 2 {
        return ConditionResult::from(false);
    }
    ConditionResult::from(value[1..].chars().all(|c| c.is_ascii_digit()))
}

// --- ID format validation ---

/// Validate Marktlokations-ID (MaLo-ID): exactly 11 digits with BDEW check digit.
///
/// This is **not** standard Luhn — per the BDEW "Anwendungshilfe MaLo-ID v1.0" spec
/// and the Hochfrequenz BO4E-dotnet reference implementation
/// (`BO4E/BO/Marktlokation.cs::GetChecksum`), digits 1–10 are numbered left-to-right
/// (1-based), digits at even positions are multiplied by 2 and **added as the full
/// value** (no digit-sum, no mod-by-9 step), digits at odd positions are added as-is.
/// Check digit = `(10 - (sum mod 10)) mod 10`.
///
/// Example: `"51238696781"` — odd (1,3,5,7,9): 5+2+8+9+7=31; even doubled
/// (2,4,6,8,10): 2*(1+3+6+6+8)=48; sum=79; check = (10-79%10)%10 = 1 ✓.
pub fn validate_malo_id(value: &str) -> ConditionResult {
    if value.len() != 11 {
        return ConditionResult::from(false);
    }
    if !value.chars().all(|c| c.is_ascii_digit()) {
        return ConditionResult::from(false);
    }
    let digits: Vec<u32> = value.chars().filter_map(|c| c.to_digit(10)).collect();
    let check = digits[10];
    let mut sum = 0u32;
    for (i, &d) in digits[..10].iter().enumerate() {
        // 1-based position is i+1; even positions are doubled, odd positions as-is.
        if (i + 1) % 2 == 0 {
            sum += 2 * d;
        } else {
            sum += d;
        }
    }
    let expected = (10 - (sum % 10)) % 10;
    ConditionResult::from(check == expected)
}

/// Validate Transaktionsreferenz-ID (TR-ID): 1-35 alphanumeric characters.
pub fn validate_tr_id(value: &str) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    ConditionResult::from(value.len() <= 35 && value.chars().all(|c| c.is_ascii_alphanumeric()))
}

/// Validate Steuerbare-Ressource-ID (SR-ID): same format as MaLo-ID (11 digits, Luhn check).
pub fn validate_sr_id(value: &str) -> ConditionResult {
    validate_malo_id(value)
}

// --- OBIS code pattern matching ---

/// Parse an OBIS code of the form `A-B:C.D.E[*F]` and return `(C, D)`.
///
/// OBIS structure (IEC 62056-61, BDEW/DVGW usage):
/// - `A` — medium (1 = electricity, 7 = gas, 6 = heat, …)
/// - `B` — channel
/// - `C` — measurement type (1 = +A active energy import, 2 = -A active energy
///   export, 3 = +R reactive import, 4 = -R reactive export, …)
/// - `D` — measurement mode (8 = total time integral, 9 = billing-period
///   integral, 29 = previous-billing-period partial value for interval
///   measurements, 5 = actual/instantaneous value, …)
/// - `E` — rate/tariff
/// - `F` — optional billing period marker
///
/// Returns `None` when the value doesn't fit the shape. Whitespace-tolerant.
pub fn parse_obis(value: &str) -> Option<(u32, u32)> {
    let value = value.trim();
    // Split at the colon between `A-B` and `C.D.E`.
    let (_ab, cde) = value.split_once(':')?;
    // Drop optional `*F` suffix.
    let cde = cde.split('*').next()?;
    let mut parts = cde.split('.');
    let c = parts.next()?.parse::<u32>().ok()?;
    let d = parts.next()?.parse::<u32>().ok()?;
    Some((c, d))
}

/// Is the OBIS code "Wirkarbeit kumuliert" — active energy as a cumulated
/// time integral (total or per billing period)?
///
/// Matches BDEW convention: `C ∈ {1, 2}` (active energy import/export) and
/// `D ∈ {8, 9}` (total time integral / billing-period integral).
pub fn is_obis_wirkarbeit_kumuliert(value: &str) -> bool {
    matches!(parse_obis(value), Some((1 | 2, 8 | 9)))
}

/// Is the OBIS code "Wirkarbeit 1/4 Stunde" — active energy 15-minute
/// interval (Lastgang) measurement?
///
/// Matches BDEW convention for quarter-hour Lastgang: `C ∈ {1, 2}` and
/// `D = 29` (partial value for previous billing period, the standard marker
/// for interval-measured energy in German energy market MSCONS/UTILMD).
pub fn is_obis_wirkarbeit_quarter_hour(value: &str) -> bool {
    matches!(parse_obis(value), Some((1 | 2, 29)))
}

/// Validate an X.509 certificate body per BSI TR-03109-4.
///
/// In EDIFACT messages (e.g. ORDERS/REQOTE for Smartmeter gateway config) the
/// certificate body is transmitted as base64-encoded DER — the PEM armoring
/// (`-----BEGIN CERTIFICATE-----` / `-----END CERTIFICATE-----` lines) may or
/// may not be present depending on the profile.
///
/// This validator performs a structural check only:
/// - non-empty
/// - composed exclusively of base64 characters (`A-Za-z0-9+/=`) plus
///   whitespace (`\n\r\t` and space — PEM lines wrap at 64 chars)
/// - decoded length plausible for a DER-encoded X.509 certificate (we allow a
///   loose lower bound — a minimal self-signed cert is ~400 bytes, so the
///   base64 form is ≥ ~540 chars; we use 100 as a sanity floor)
///
/// Cryptographic validation (signature, CA chain, TR-03109 certificate
/// extensions) is out of scope for static AHB validation — those require a
/// trust store and runtime context.
pub fn validate_x509_cert_body(value: &str) -> ConditionResult {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return ConditionResult::Unknown;
    }
    // Strip optional PEM armoring so the charset check operates on the
    // encoded body alone.
    let body = trimmed
        .trim_start_matches("-----BEGIN CERTIFICATE-----")
        .trim_end_matches("-----END CERTIFICATE-----")
        .trim();
    let chars_ok = body.chars().all(|c| {
        c.is_ascii_alphanumeric() || matches!(c, '+' | '/' | '=' | '\n' | '\r' | '\t' | ' ')
    });
    // Minimum plausible length for a base64-encoded X.509 body. Shorter
    // values are almost certainly not a real certificate.
    let len_ok = body.chars().filter(|c| !c.is_whitespace()).count() >= 100;
    ConditionResult::from(chars_ok && len_ok)
}

/// Validate Zahlpunktbezeichnung: exactly 33 alphanumeric characters.
pub fn validate_zahlpunkt(value: &str) -> ConditionResult {
    if value.len() != 33 {
        return ConditionResult::from(false);
    }
    ConditionResult::from(value.chars().all(|c| c.is_ascii_alphanumeric()))
}

/// Validate either MaLo-ID or Zahlpunktbezeichnung format.
pub fn validate_malo_or_zahlpunkt(value: &str) -> ConditionResult {
    if value.len() == 11 && validate_malo_id(value).is_true() {
        return ConditionResult::True;
    }
    if value.len() == 33 && validate_zahlpunkt(value).is_true() {
        return ConditionResult::True;
    }
    ConditionResult::False
}

// --- Artikelnummer pattern validation ---

/// Validate a dash-separated digit pattern like "n1-n2-n1-n3".
///
/// `segment_lengths` defines expected digit counts per dash-separated segment.
///
/// Example: `validate_artikel_pattern("1-23-4-567", &[1, 2, 1, 3])` → True
/// Example: `validate_artikel_pattern("1-23-4", &[1, 2, 1])` → True
pub fn validate_artikel_pattern(value: &str, segment_lengths: &[usize]) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    let parts: Vec<&str> = value.split('-').collect();
    if parts.len() != segment_lengths.len() {
        return ConditionResult::from(false);
    }
    let valid = parts
        .iter()
        .zip(segment_lengths.iter())
        .all(|(part, &expected_len)| {
            part.len() == expected_len && part.chars().all(|c| c.is_ascii_digit())
        });
    ConditionResult::from(valid)
}

// --- General string validation ---

/// Validate exact character length.
pub fn validate_exact_length(value: &str, expected: usize) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    ConditionResult::from(value.len() == expected)
}

/// Validate maximum character length.
pub fn validate_max_length(value: &str, max: usize) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    ConditionResult::from(value.len() <= max)
}

/// Validate that a string contains only digits (positive integer check).
pub fn validate_all_digits(value: &str) -> ConditionResult {
    if value.is_empty() {
        return ConditionResult::Unknown;
    }
    ConditionResult::from(value.chars().all(|c| c.is_ascii_digit()))
}

/// Current UTC date+time as a CCYYMMDDHHMM string (12 chars).
pub fn utc_now_ccyymmddhhmm() -> String {
    chrono::Utc::now().format("%Y%m%d%H%M").to_string()
}

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

    // --- Decimal places ---

    #[test]
    fn test_max_decimal_places() {
        assert_eq!(
            validate_max_decimal_places("123.45", 2),
            ConditionResult::True
        );
        assert_eq!(
            validate_max_decimal_places("123.456", 2),
            ConditionResult::False
        );
        assert_eq!(validate_max_decimal_places("123", 2), ConditionResult::True);
        assert_eq!(validate_max_decimal_places("0.1", 3), ConditionResult::True);
        assert_eq!(validate_max_decimal_places("", 2), ConditionResult::Unknown);
    }

    #[test]
    fn test_no_decimal_places() {
        assert_eq!(validate_max_decimal_places("100", 0), ConditionResult::True);
        assert_eq!(
            validate_max_decimal_places("100.5", 0),
            ConditionResult::False
        );
    }

    #[test]
    fn test_max_integer_digits() {
        assert_eq!(
            validate_max_integer_digits("1234", 4),
            ConditionResult::True
        );
        assert_eq!(
            validate_max_integer_digits("12345", 4),
            ConditionResult::False
        );
        assert_eq!(
            validate_max_integer_digits("-123.45", 4),
            ConditionResult::True
        );
        assert_eq!(validate_max_integer_digits("", 4), ConditionResult::Unknown);
    }

    // --- Numeric range ---

    #[test]
    fn test_validate_numeric() {
        assert_eq!(validate_numeric("5.0", ">=", 0.0), ConditionResult::True);
        assert_eq!(validate_numeric("-1.0", ">=", 0.0), ConditionResult::False);
        assert_eq!(validate_numeric("1", "==", 1.0), ConditionResult::True);
        assert_eq!(validate_numeric("2", "==", 1.0), ConditionResult::False);
        assert_eq!(validate_numeric("0", ">", 0.0), ConditionResult::False);
        assert_eq!(validate_numeric("1", ">", 0.0), ConditionResult::True);
        assert_eq!(validate_numeric("abc", ">=", 0.0), ConditionResult::Unknown);
    }

    // --- DTM validation ---

    #[test]
    fn test_hhmm_equals() {
        assert_eq!(
            validate_hhmm_equals("202601012200+00", "2200"),
            ConditionResult::True
        );
        assert_eq!(
            validate_hhmm_equals("202601012300+00", "2200"),
            ConditionResult::False
        );
        assert_eq!(
            validate_hhmm_equals("short", "2200"),
            ConditionResult::False
        );
    }

    #[test]
    fn test_hhmm_range() {
        assert_eq!(
            validate_hhmm_range("202601011530+00", "0000", "2359"),
            ConditionResult::True
        );
        assert_eq!(
            validate_hhmm_range("202601010000+00", "0000", "2359"),
            ConditionResult::True
        );
        assert_eq!(
            validate_hhmm_range("202601012359+00", "0000", "2359"),
            ConditionResult::True
        );
    }

    #[test]
    fn test_mmddhhmm_equals() {
        assert_eq!(
            validate_mmddhhmm_equals("202612312300+00", "12312300"),
            ConditionResult::True
        );
        assert_eq!(
            validate_mmddhhmm_equals("202601012200+00", "12312300"),
            ConditionResult::False
        );
    }

    #[test]
    fn test_timezone_utc() {
        assert_eq!(
            validate_timezone_utc("202601012200+00"),
            ConditionResult::True
        );
        assert_eq!(
            validate_timezone_utc("202601012200+01"),
            ConditionResult::False
        );
        assert_eq!(
            validate_timezone_utc("202601012200"),
            ConditionResult::False
        );
    }

    // --- Contact validation ---

    #[test]
    fn test_email() {
        assert_eq!(validate_email("user@example.com"), ConditionResult::True);
        assert_eq!(validate_email("nope"), ConditionResult::False);
        assert_eq!(validate_email("has@but-no-dot"), ConditionResult::False);
        assert_eq!(validate_email(""), ConditionResult::Unknown);
    }

    #[test]
    fn test_phone() {
        assert_eq!(validate_phone("+4930123456"), ConditionResult::True);
        assert_eq!(validate_phone("030123456"), ConditionResult::False);
        assert_eq!(validate_phone("+"), ConditionResult::False);
        assert_eq!(validate_phone("+49 30 123"), ConditionResult::False); // spaces not allowed
        assert_eq!(validate_phone(""), ConditionResult::Unknown);
    }

    // --- ID validation ---

    #[test]
    fn test_malo_id() {
        // Valid MaLo-IDs — taken directly from the BO4E-dotnet reference test
        // suite (TestBO4E/TestMaLoMeLoId.cs), which uses the BDEW MaLo-ID spec
        // (no digit-sum on doubled products; see `validate_malo_id` docstring).
        assert_eq!(validate_malo_id("51238696781"), ConditionResult::True);
        assert_eq!(validate_malo_id("41373559241"), ConditionResult::True);
        assert_eq!(validate_malo_id("56789012345"), ConditionResult::True);
        assert_eq!(validate_malo_id("52935155442"), ConditionResult::True);

        // Negative cases from the same reference tests.
        assert_eq!(validate_malo_id("41373559240"), ConditionResult::False); // wrong check digit
        assert_eq!(validate_malo_id("512386967890"), ConditionResult::False); // 12 digits
        assert_eq!(validate_malo_id("1234567890"), ConditionResult::False); // too short
        assert_eq!(validate_malo_id("abcdefghijk"), ConditionResult::False); // not digits
    }

    #[test]
    fn test_zahlpunkt() {
        let valid = "DE0001234567890123456789012345678";
        assert_eq!(valid.len(), 33);
        assert_eq!(validate_zahlpunkt(valid), ConditionResult::True);
        assert_eq!(validate_zahlpunkt("tooshort"), ConditionResult::False);
    }

    // --- Artikelnummer pattern ---

    #[test]
    fn test_artikel_pattern() {
        assert_eq!(
            validate_artikel_pattern("1-23-4", &[1, 2, 1]),
            ConditionResult::True
        );
        assert_eq!(
            validate_artikel_pattern("1-23-4-567", &[1, 2, 1, 3]),
            ConditionResult::True
        );
        assert_eq!(
            validate_artikel_pattern("1-23-4-56", &[1, 2, 1, 3]),
            ConditionResult::False
        );
        assert_eq!(
            validate_artikel_pattern("1-AB-4", &[1, 2, 1]),
            ConditionResult::False
        );
        assert_eq!(
            validate_artikel_pattern("", &[1, 2, 1]),
            ConditionResult::Unknown
        );
    }

    // --- TR-ID / SR-ID validation ---

    #[test]
    fn test_tr_id() {
        assert_eq!(validate_tr_id("ABC123"), ConditionResult::True);
        assert_eq!(validate_tr_id("A"), ConditionResult::True);
        assert_eq!(validate_tr_id(&"A".repeat(35)), ConditionResult::True);
        assert_eq!(validate_tr_id(&"A".repeat(36)), ConditionResult::False);
        assert_eq!(validate_tr_id("has spaces"), ConditionResult::False);
        assert_eq!(validate_tr_id("has-dash"), ConditionResult::False);
        assert_eq!(validate_tr_id(""), ConditionResult::Unknown);
    }

    #[test]
    fn test_parse_obis() {
        assert_eq!(parse_obis("1-1:1.8.0"), Some((1, 8)));
        assert_eq!(parse_obis("1-1:2.29.0"), Some((2, 29)));
        assert_eq!(parse_obis("1-0:1.8.0*255"), Some((1, 8))); // star suffix
        assert_eq!(parse_obis(" 1-1:1.8.0 "), Some((1, 8))); // whitespace
        assert_eq!(parse_obis("no-colon"), None);
        assert_eq!(parse_obis("1-1:abc.8.0"), None);
        assert_eq!(parse_obis(""), None);
    }

    #[test]
    fn test_obis_wirkarbeit_kumuliert() {
        // Active energy import/export, total or billing-period integral.
        assert!(is_obis_wirkarbeit_kumuliert("1-1:1.8.0"));
        assert!(is_obis_wirkarbeit_kumuliert("1-1:2.8.0"));
        assert!(is_obis_wirkarbeit_kumuliert("1-1:1.9.0"));
        assert!(is_obis_wirkarbeit_kumuliert("1-1:2.9.0"));
        assert!(is_obis_wirkarbeit_kumuliert("1-0:1.8.0*255"));
        // Reactive energy — not Wirkarbeit.
        assert!(!is_obis_wirkarbeit_kumuliert("1-1:3.8.0"));
        assert!(!is_obis_wirkarbeit_kumuliert("1-1:4.8.0"));
        // 15-min partial value — not kumuliert.
        assert!(!is_obis_wirkarbeit_kumuliert("1-1:1.29.0"));
        // Actual value — not kumuliert.
        assert!(!is_obis_wirkarbeit_kumuliert("1-1:1.5.0"));
    }

    #[test]
    fn test_obis_wirkarbeit_quarter_hour() {
        // Active energy 15-min Lastgang.
        assert!(is_obis_wirkarbeit_quarter_hour("1-1:1.29.0"));
        assert!(is_obis_wirkarbeit_quarter_hour("1-1:2.29.0"));
        assert!(is_obis_wirkarbeit_quarter_hour("1-0:1.29.0*255"));
        // Cumulated — not 1/4h.
        assert!(!is_obis_wirkarbeit_quarter_hour("1-1:1.8.0"));
        assert!(!is_obis_wirkarbeit_quarter_hour("1-1:1.9.0"));
        // Reactive.
        assert!(!is_obis_wirkarbeit_quarter_hour("1-1:3.29.0"));
    }

    #[test]
    fn test_x509_cert_body() {
        // Valid: 600-char base64 body (well above 100-char floor).
        let body = "A".repeat(600);
        assert_eq!(validate_x509_cert_body(&body), ConditionResult::True);

        // Valid with base64 padding and newlines (PEM-style wrapping).
        let pem_body = "A".repeat(64) + "\n" + &"B".repeat(64) + "\n" + &"C".repeat(64);
        assert_eq!(validate_x509_cert_body(&pem_body), ConditionResult::True);

        // Valid with explicit PEM armoring — stripped before charset check.
        let armored = format!(
            "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----",
            "A".repeat(200)
        );
        assert_eq!(validate_x509_cert_body(&armored), ConditionResult::True);

        // Valid: base64 chars include +, /, =
        let with_punct = "AB+/==".to_string() + &"A".repeat(200);
        assert_eq!(validate_x509_cert_body(&with_punct), ConditionResult::True);

        // Too short — not a plausible cert.
        assert_eq!(validate_x509_cert_body("QUJD"), ConditionResult::False);

        // Non-base64 characters.
        let invalid_chars = "A".repeat(200) + "!@#";
        assert_eq!(
            validate_x509_cert_body(&invalid_chars),
            ConditionResult::False
        );

        // Empty is Unknown (consistent with other format validators).
        assert_eq!(validate_x509_cert_body(""), ConditionResult::Unknown);
        assert_eq!(validate_x509_cert_body("   \n  "), ConditionResult::Unknown);
    }

    #[test]
    fn test_sr_id() {
        // SR-ID uses the same BDEW 11-digit check format as MaLo-ID; reuse
        // the reference-suite valid example from BO4E-dotnet tests.
        assert_eq!(validate_sr_id("51238696781"), ConditionResult::True);
        assert_eq!(validate_sr_id("41373559240"), ConditionResult::False);
        assert_eq!(validate_sr_id("1234567890"), ConditionResult::False);
        assert_eq!(validate_sr_id(""), ConditionResult::False);
    }

    // --- String validation ---

    #[test]
    fn test_exact_length() {
        assert_eq!(
            validate_exact_length("1234567890123456", 16),
            ConditionResult::True
        );
        assert_eq!(validate_exact_length("123", 16), ConditionResult::False);
        assert_eq!(validate_exact_length("", 16), ConditionResult::Unknown);
    }

    #[test]
    fn test_all_digits() {
        assert_eq!(validate_all_digits("12345"), ConditionResult::True);
        assert_eq!(validate_all_digits("123a5"), ConditionResult::False);
        assert_eq!(validate_all_digits(""), ConditionResult::Unknown);
    }
}