edifact-rs 0.11.0

Zero-copy EDIFACT parser, writer, serde traits, and extensible validation support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
//! EDIFACT envelope validation — UNB / UNG / UNH / UNT / UNE / UNZ.
//!
//! Validates the full ISO 9735-1 interchange structure including optional
//! functional groups (`UNG`/`UNE`).  The public surface is:
//!
//! - [`validate_envelope`] / [`validate_envelope_from_owned`] — fail-fast strict validation
//! - [`validate_envelope_lenient`] / [`validate_envelope_lenient_from_owned`] — collects all errors
//! - [`parse_unh`] — zero-copy parse of UNH identifier fields
//!
//! # UNZ count semantics (ISO 9735-1 §9.2)
//!
//! `UNZ` DE 0036 (the interchange control count) has dual semantics:
//! - **No functional groups**: counts `UNH`/`UNT` message pairs.
//! - **With functional groups**: counts `UNG`/`UNE` group pairs.
//!
//! `validate_envelope` checks the UNZ count against the appropriate unit
//! (groups when groups are present, messages otherwise) and reports
//! [`EdifactError::MessageCountMismatch`] on any discrepancy.

use crate::{OwnedSegment, error::EdifactError, model::Segment};

// ── Sealed segment-access trait ──────────────────────────────────────────────

pub(crate) trait SegmentReader: sealed::Sealed {
    fn tag(&self) -> &str;
    fn span_start(&self) -> usize;
    fn component(&self, elem_idx: usize, comp_idx: usize) -> Option<&str>;

    fn required_component_field(
        &self,
        elem_idx: usize,
        comp_idx: usize,
    ) -> Result<&str, EdifactError> {
        self.component(elem_idx, comp_idx)
            .filter(|s| !s.is_empty())
            .ok_or_else(|| EdifactError::MissingRequiredComponent {
                tag: self.tag().to_owned(),
                element_index: elem_idx,
                component_index: comp_idx,
            })
    }
}

mod sealed {
    pub trait Sealed {}
    impl Sealed for crate::model::Segment<'_> {}
    impl Sealed for crate::OwnedSegment {}
}

impl SegmentReader for Segment<'_> {
    #[inline]
    fn tag(&self) -> &str {
        self.tag
    }
    #[inline]
    fn span_start(&self) -> usize {
        self.span.start
    }
    #[inline]
    fn component(&self, elem_idx: usize, comp_idx: usize) -> Option<&str> {
        self.get_element(elem_idx)?.get_component(comp_idx)
    }
}

impl SegmentReader for OwnedSegment {
    #[inline]
    fn tag(&self) -> &str {
        &self.tag
    }
    #[inline]
    fn span_start(&self) -> usize {
        self.span.start
    }
    #[inline]
    fn component(&self, elem_idx: usize, comp_idx: usize) -> Option<&str> {
        self.component_str(elem_idx, comp_idx)
    }
}

// ── Public data types ─────────────────────────────────────────────────────────

/// Extracted data from the `UNB` / `UNZ` interchange envelope.
///
/// All standard UNB fields that carry business-relevant information are
/// exposed.  Optional fields that are absent in the source are represented
/// as empty strings (`syntax_version`, qualifiers) or `None` (optional fields).
///
/// UNB element positions (ISO 9735-1 §6.1.1, 0-indexed):
///
/// ```text
/// [0] S001  syntax identifier + version
/// [1] S002  sender id + qualifier + routing
/// [2] S003  recipient id + qualifier + routing
/// [3] S004  date + time
/// [4] 0020  interchange control reference
/// [5] S005  recipient password (DE 0022 comp 0)
/// [6] 0026  application reference
/// [7] 0029  processing priority code
/// [8] 0031  acknowledgement request
/// [9] 0032  communications agreement ID
///[10] 0035  test indicator
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct InterchangeEnvelope {
    /// Syntax identifier, e.g. `"UNOA"` or `"UNOB"` (UNB S001 DE 0001).
    pub syntax_identifier: String,
    /// Syntax version number, e.g. `"3"` (UNB S001 DE 0002).
    ///
    /// Empty string when the UNB omits the version component.
    pub syntax_version: String,
    /// Interchange sender identification (UNB S002 DE 0004).
    pub sender_id: String,
    /// Interchange sender identification code qualifier (UNB S002 DE 0007).
    ///
    /// Common values: `"14"` (EAN/GLN), `"ZZZ"` (mutually defined).
    /// Empty string when no qualifier is present.
    pub sender_qualifier: String,
    /// Interchange sender routing address (UNB S002 DE 0014), if present.
    ///
    /// An optional routing address used by some EDI networks to identify
    /// the sub-entity (division, application) within the sender organisation.
    pub sender_routing_address: Option<String>,
    /// Interchange recipient identification (UNB S003 DE 0010).
    pub recipient_id: String,
    /// Interchange recipient identification code qualifier (UNB S003 DE 0007).
    ///
    /// Same values as `sender_qualifier`.  Empty string when absent.
    pub recipient_qualifier: String,
    /// Interchange recipient routing address (UNB S003 DE 0014), if present.
    ///
    /// Analogous to `sender_routing_address` but for the recipient side.
    pub recipient_routing_address: Option<String>,
    /// Interchange date (UNB S004 DE 0017), e.g. `"230401"` (YYMMDD format).
    pub date: String,
    /// Interchange time (UNB S004 DE 0019), e.g. `"0900"` (HHMM format), if present.
    ///
    /// `None` when the UNB time component (DE 0019) is absent.
    pub time: Option<String>,
    /// Interchange control reference (UNB DE 0020).
    pub control_ref: String,
    /// Recipient's reference/password (UNB S005 DE 0022), if present.
    ///
    /// Used in some EDI networks for basic interchange-level authentication.
    /// Empty S005 in the source yields `None`.
    pub recipient_password: Option<String>,
    /// Recipient's reference/password qualifier (UNB S005 DE 0025), if present.
    ///
    /// Qualifies the type of the `recipient_password`.  Example value: `"AA"` (unencoded).
    /// `None` when DE 0025 is absent or empty.
    pub recipient_password_qualifier: Option<String>,
    /// Application reference (UNB DE 0026, element index 6), if present.
    ///
    /// Identifies the division, department, or section of sender or recipient.
    pub app_ref: Option<String>,
    /// Processing priority code (UNB DE 0029, element index 7), if present.
    ///
    /// Indicates the processing priority requested by the sender.
    /// Rarely used in practice; included here for full ISO 9735-1 §6.1.1 compliance.
    pub processing_priority: Option<String>,
    /// Acknowledgement request flag (UNB DE 0031, element index 8).
    ///
    /// `true` when DE 0031 is `"1"`, indicating that the sender requests a
    /// `CONTRL` functional acknowledgement from the recipient.
    pub acknowledgement_request: bool,
    /// Communications agreement identifier (UNB DE 0032, element index 9), if present.
    ///
    /// Identifies the agreement controlling the interchange, e.g. `"EANCOM"`.
    pub communications_agreement_id: Option<String>,
    /// Test indicator flag (UNB DE 0035, element index 10).
    ///
    /// `true` when DE 0035 is `"1"`.  Test interchanges **must not** be processed
    /// as production data — check [`is_test()`](Self::is_test) before dispatching
    /// messages to business logic, billing, or downstream integrations.
    pub test_indicator: bool,
    /// Interchange unit count declared in `UNZ` DE 0036.
    ///
    /// - When no functional groups are present: count of messages (`UNH`/`UNT` pairs).
    /// - When functional groups are present: count of groups (`UNG`/`UNE` pairs).
    ///
    /// Use [`ValidatedInterchange::messages`] for a flat count of all messages
    /// regardless of group structure.
    pub declared_unit_count: u32,
    /// Actual unit count observed (groups if groups present; messages otherwise).
    pub actual_unit_count: u32,
}

impl InterchangeEnvelope {
    /// Returns `true` when the test indicator (`UNB` DE 0035) is set to `"1"`.
    ///
    /// Production systems must check this flag before dispatching any message
    /// to business logic, billing, or downstream integrations.
    ///
    /// # Example
    ///
    /// ```
    /// // UNB element [10] is the test indicator; "1" means test.
    /// // UNB+UNOA:3+S+R+200101:0900+1++++++1'  ← last element = "1" → is_test() == true
    /// let input = b"UNB+UNOA:3+S+R+200101:0900+CTRL++++++1'\
    ///               UNH+1+ORDERS:D:96A:UN'\
    ///               BGM+220+PO-001+9'\
    ///               UNT+3+1'\
    ///               UNZ+1+CTRL'";
    /// let segs: Vec<_> = edifact_rs::from_bytes(input)
    ///     .collect::<Result<Vec<_>, _>>()
    ///     .unwrap();
    /// let result = edifact_rs::validate_envelope(&segs).unwrap();
    /// assert!(result.interchange.is_test());
    /// ```
    #[inline]
    #[must_use]
    pub fn is_test(&self) -> bool {
        self.test_indicator
    }

    /// Returns `true` when the acknowledgement request flag (UNB DE 0031) is set.
    ///
    /// When `true`, the sender expects a `CONTRL` acknowledgement from the recipient.
    #[inline]
    #[must_use]
    pub fn ack_requested(&self) -> bool {
        self.acknowledgement_request
    }
}

impl std::fmt::Display for InterchangeEnvelope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{sender} -> {recipient} [{ctrl}] ({syntax}:{ver})",
            sender = self.sender_id,
            recipient = self.recipient_id,
            ctrl = self.control_ref,
            syntax = self.syntax_identifier,
            ver = self.syntax_version,
        )
    }
}

/// Extracted data from a single `UNH` / `UNT` message envelope.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MessageEnvelope {
    /// Message reference from `UNH` element 0.
    pub message_ref: String,
    /// EDIFACT message type, e.g. `"ORDERS"`.
    pub message_type: String,
    /// Version number, e.g. `"D"`.
    pub version: String,
    /// Release number, e.g. `"11A"`.
    pub release: String,
    /// Controlling agency code, e.g. `"UN"`.
    pub controlling_agency: String,
    /// Association assigned code (MIG version), e.g. `"FV2510"`.
    pub association_code: String,
    /// Common access reference (UNH DE 0068, element index 2), if present.
    ///
    /// A reference shared across related messages or exchanges on the same network
    /// path.  Used by some EDI network profiles (e.g. certain gas-market MIGs) to
    /// correlate messages that belong to a single business transaction.
    /// `None` when element \[2\] is absent or empty.
    pub common_access_ref: Option<String>,
    /// Sequence of transfers (UNH S010 DE 0070, element index 3), if present.
    ///
    /// When a large message is split across multiple interchanges, this is the
    /// 1-based index of this segment within the sequence.  `None` when the message
    /// is not split (element \[3\] absent).
    pub sequence_of_transfers: Option<u32>,
    /// Transfer position indicator (UNH S010 DE 0073, element index 3 comp 1), if present.
    ///
    /// Values per ISO 9735-1 §6.2.3: `"C"` = continuation, `"F"` = first, `"L"` = last.
    /// `None` when element \[3\] is absent.
    pub transfer_position: Option<String>,
    /// Declared segment count from `UNT`.
    pub declared_segment_count: u32,
    /// Actual segment count between this `UNH` and its `UNT`.
    pub actual_segment_count: u32,
}

impl std::fmt::Display for MessageEnvelope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{msg_type}:{ver}:{rel} ref={msg_ref} seg={actual}/{declared}",
            msg_type = self.message_type,
            ver = self.version,
            rel = self.release,
            msg_ref = self.message_ref,
            actual = self.actual_segment_count,
            declared = self.declared_segment_count,
        )
    }
}

/// Extracted data from a single `UNG` / `UNE` functional group envelope.
///
/// ISO 9735-1 §8 defines optional functional groups that may wrap one or more
/// `UNH`/`UNT` message pairs.  This type carries the parsed fields from both
/// the `UNG` header and its matching `UNE` trailer, plus the validated messages.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FunctionalGroupEnvelope {
    /// Functional group identification (UNG DE 0038), e.g. `"ORDERS"`.
    pub group_id: String,
    /// Application sender's identification (UNG S006 DE 0040).
    pub app_sender: String,
    /// Application sender identification code qualifier (UNG S006 DE 0007).
    ///
    /// Empty string when no qualifier is present.
    pub app_sender_qualifier: String,
    /// Application recipient's identification (UNG S007 DE 0044).
    pub app_recipient: String,
    /// Application recipient identification code qualifier (UNG S007 DE 0007).
    ///
    /// Empty string when no qualifier is present.
    pub app_recipient_qualifier: String,
    /// Date of preparation (UNG S004 DE 0017), e.g. `"200101"` (YYMMDD format).
    pub date: String,
    /// Time of preparation (UNG S004 DE 0019), e.g. `"0900"` (HHMM format), if present.
    pub time: Option<String>,
    /// Functional group reference number (UNG DE 0048). Must match `UNE` DE 0048.
    pub group_ref: String,
    /// Controlling agency, coded (UNG DE 0051), e.g. `"UN"`.
    pub controlling_agency: String,
    /// Message version number, e.g. `"D"`.
    pub version: String,
    /// Message release number, e.g. `"96A"`.
    pub release: String,
    /// Declared message count from `UNE` DE 0060.
    pub declared_message_count: u32,
    /// Actual number of `UNH`/`UNT` pairs found within this group.
    pub actual_message_count: u32,
    /// Messages contained within this functional group.
    pub messages: Vec<MessageEnvelope>,
}

/// Fully validated interchange structure returned by [`validate_envelope`].
///
/// Provides both hierarchical (group → message) and flat (all messages) access
/// so that callers who do not care about group boundaries can use
/// [`messages`](Self::messages) directly.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ValidatedInterchange {
    /// Interchange-level envelope data (from `UNB`/`UNZ`).
    pub interchange: InterchangeEnvelope,
    /// Functional groups, when the interchange uses `UNG`/`UNE` wrappers.
    ///
    /// Empty when messages appear directly under the interchange (the common
    /// case for BDEW MaKo and most modern EDIFACT implementations).
    pub functional_groups: Vec<FunctionalGroupEnvelope>,
    /// Flat list of all messages in the interchange.
    ///
    /// When functional groups are present this contains the same messages as
    /// the nested `messages` fields inside each [`FunctionalGroupEnvelope`].
    pub messages: Vec<MessageEnvelope>,
}

impl ValidatedInterchange {
    /// Returns `true` if this interchange uses `UNG`/`UNE` functional group wrappers.
    #[inline]
    #[must_use]
    pub fn has_functional_groups(&self) -> bool {
        !self.functional_groups.is_empty()
    }

    /// Total number of `UNH`/`UNT` message pairs across all groups.
    ///
    /// Equivalent to `self.messages.len()` but communicates intent clearly.
    #[inline]
    #[must_use]
    pub fn message_count(&self) -> usize {
        self.messages.len()
    }

    /// Iterate over all messages in the interchange.
    ///
    /// Equivalent to `self.messages.iter()` but communicates intent clearly
    /// and is stable regardless of future internal layout changes.
    #[inline]
    #[must_use]
    pub fn iter_messages(&self) -> impl Iterator<Item = &MessageEnvelope> {
        self.messages.iter()
    }

    /// Find the first message whose `message_ref` equals `reference`.
    ///
    /// Useful for locating a specific message in an interchange with multiple
    /// messages after calling `validate_envelope`.
    ///
    /// Returns `None` if no message with that reference exists.
    #[inline]
    #[must_use]
    pub fn find_message(&self, reference: &str) -> Option<&MessageEnvelope> {
        self.messages.iter().find(|m| m.message_ref == reference)
    }

    /// Collect all messages of a given type (e.g. `"ORDERS"`, `"INVOIC"`).
    ///
    /// Returns a `Vec` of references to matching messages in document order.
    /// Returns an empty `Vec` when the interchange contains no messages of
    /// the requested type.
    ///
    /// Prefer [`iter_messages_by_type`](Self::iter_messages_by_type) in tight loops
    /// to avoid the allocation.
    #[must_use]
    pub fn messages_by_type(&self, message_type: &str) -> Vec<&MessageEnvelope> {
        self.messages
            .iter()
            .filter(|m| m.message_type == message_type)
            .collect()
    }

    /// Iterate over all messages of a given type without allocating.
    ///
    /// Zero-allocation alternative to [`messages_by_type`](Self::messages_by_type).
    ///
    /// The bound `'q: 's` means the `message_type` string reference must outlive the
    /// borrow of `self`.  In practice this is always satisfied when passing a string
    /// literal (`&'static str`) or any string whose lifetime is at least as long as
    /// the `ValidatedInterchange` reference.  For short-lived computed strings, use
    /// [`messages_by_type`](Self::messages_by_type) which collects eagerly and releases the string reference
    /// immediately.
    #[inline]
    #[must_use]
    pub fn iter_messages_by_type<'s, 'q: 's>(
        &'s self,
        message_type: &'q str,
    ) -> impl Iterator<Item = &'s MessageEnvelope> + 's {
        self.messages
            .iter()
            .filter(move |m| m.message_type == message_type)
    }
}

impl std::fmt::Display for ValidatedInterchange {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{ic} messages={n}",
            ic = self.interchange,
            n = self.messages.len(),
        )
    }
}

impl std::fmt::Display for FunctionalGroupEnvelope {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{gid} sender={sender} recipient={recip} [{gref}] ({agency}) msgs={actual}/{declared}",
            gid = self.group_id,
            sender = self.app_sender,
            recip = self.app_recipient,
            gref = self.group_ref,
            agency = self.controlling_agency,
            actual = self.actual_message_count,
            declared = self.declared_message_count,
        )
    }
}

/// Parsed identifier fields from a `UNH` segment.
///
/// All string slices borrow from the input bytes so they live as long as the
/// original byte buffer.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct MessageIdentifier<'a> {
    /// Message reference number (UNH DE 0062, element index 0).
    pub message_ref: &'a str,
    pub message_type: &'a str,
    pub version: &'a str,
    pub release: &'a str,
    pub controlling_agency: &'a str,
    /// Association assigned code (UNH S009 DE 0057).
    ///
    /// Matches `MessageEnvelope::association_code` for the same message.
    pub association_code: &'a str,
}

// ── Public API ────────────────────────────────────────────────────────────────

/// Extract identifier fields from a `UNH` segment (zero allocation).
pub fn parse_unh<'a>(unh: &'a Segment<'a>) -> Result<MessageIdentifier<'a>, EdifactError> {
    // Element [0]: DE 0062 — message reference number (required, simple DE)
    let message_ref = unh
        .get_element(0)
        .and_then(|e| e.get_component(0))
        .filter(|s| !s.is_empty())
        .ok_or_else(|| EdifactError::MissingRequiredComponent {
            tag: "UNH".to_owned(),
            element_index: 0,
            component_index: 0,
        })?;
    // Element [1]: S009 composite — message type, version, release, agency, association
    let elem = unh
        .get_element(1)
        .ok_or_else(|| EdifactError::MissingRequiredElement {
            tag: "UNH".to_owned(),
            element_index: 1,
        })?;
    let message_type =
        elem.get_component(0)
            .ok_or_else(|| EdifactError::MissingRequiredComponent {
                tag: "UNH".to_owned(),
                element_index: 1,
                component_index: 0,
            })?;
    Ok(MessageIdentifier {
        message_ref,
        message_type,
        version: elem.get_component(1).unwrap_or(""),
        release: elem.get_component(2).unwrap_or(""),
        controlling_agency: elem.get_component(3).unwrap_or(""),
        association_code: elem.get_component(4).unwrap_or(""),
    })
}

/// Parsed identifier fields from a `UNG` segment.
///
/// All string slices borrow from the input bytes so they live as long as the
/// original byte buffer.  Use this for zero-allocation group routing in streaming
/// scenarios where you need to inspect group identity without full validation.
///
/// # UNG element positions (ISO 9735-1 §8, 0-indexed)
///
/// ```text
/// [0] DE 0038  functional group identification
/// [1] S006     application sender id + qualifier (comp 0 / comp 1)
/// [2] S007     application recipient id + qualifier (comp 0 / comp 1)
/// [3] S004     date + time (comp 0 / comp 1)
/// [4] DE 0048  group reference number
/// [5] DE 0051  controlling agency
/// [6] S008     version + release (comp 0 / comp 1)
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct GroupIdentifier<'a> {
    /// Functional group identification (UNG DE 0038), e.g. `"ORDERS"`.
    pub group_id: &'a str,
    /// Application sender identification (UNG S006 DE 0040).
    pub app_sender: &'a str,
    /// Application sender identification code qualifier (UNG S006 DE 0007).
    pub app_sender_qualifier: &'a str,
    /// Application recipient identification (UNG S007 DE 0044).
    pub app_recipient: &'a str,
    /// Application recipient identification code qualifier (UNG S007 DE 0007).
    pub app_recipient_qualifier: &'a str,
    /// Group reference number (UNG DE 0048).
    pub group_ref: &'a str,
    /// Controlling agency (UNG DE 0051), e.g. `"UN"`.
    pub controlling_agency: &'a str,
    /// Message version number from S008 (UNG DE 0052), e.g. `"D"`.
    pub version: &'a str,
    /// Message release number from S008 (UNG DE 0054), e.g. `"96A"`.
    pub release: &'a str,
}

/// Extract identifier fields from a `UNG` segment (zero allocation).
///
/// The symmetric counterpart to [`parse_unh`] for streaming scenarios that need
/// to inspect or route functional groups before full validation.
pub fn parse_ung<'a>(ung: &'a Segment<'a>) -> Result<GroupIdentifier<'a>, EdifactError> {
    let group_id = ung
        .get_element(0)
        .and_then(|e| e.get_component(0))
        .unwrap_or("");
    let app_sender = ung
        .get_element(1)
        .and_then(|e| e.get_component(0))
        .unwrap_or("");
    let app_sender_qualifier = ung
        .get_element(1)
        .and_then(|e| e.get_component(1))
        .unwrap_or("");
    let app_recipient = ung
        .get_element(2)
        .and_then(|e| e.get_component(0))
        .unwrap_or("");
    let app_recipient_qualifier = ung
        .get_element(2)
        .and_then(|e| e.get_component(1))
        .unwrap_or("");
    let group_ref = ung
        .get_element(4)
        .and_then(|e| e.get_component(0))
        .ok_or_else(|| EdifactError::MissingRequiredComponent {
            tag: "UNG".to_owned(),
            element_index: 4,
            component_index: 0,
        })?;
    let controlling_agency = ung
        .get_element(5)
        .and_then(|e| e.get_component(0))
        .unwrap_or("");
    let s008 = ung.get_element(6);
    let version = s008.as_ref().and_then(|e| e.get_component(0)).unwrap_or("");
    let release = s008.as_ref().and_then(|e| e.get_component(1)).unwrap_or("");
    Ok(GroupIdentifier {
        group_id,
        app_sender,
        app_sender_qualifier,
        app_recipient,
        app_recipient_qualifier,
        group_ref,
        controlling_agency,
        version,
        release,
    })
}

/// Validate the EDIFACT interchange envelope (fail-fast, borrowed-segment path).
///
/// Supports direct-message interchanges and functional-group interchanges
/// (ISO 9735-1 §8).  Returns [`ValidatedInterchange`] on success.
pub fn validate_envelope(segments: &[Segment<'_>]) -> Result<ValidatedInterchange, EdifactError> {
    validate_envelope_impl(segments)
}

/// Validate the EDIFACT interchange envelope (fail-fast, owned-segment path).
pub fn validate_envelope_from_owned(
    segments: &[OwnedSegment],
) -> Result<ValidatedInterchange, EdifactError> {
    validate_envelope_impl(segments)
}

/// Result of a lenient envelope validation — carries both a (possibly partial)
/// interchange and the full list of collected errors.
///
/// Returned by [`validate_envelope_lenient`] and [`validate_envelope_lenient_from_owned`].
///
/// # Semantics
///
/// | Condition | `interchange` | `errors` |
/// |-----------|---------------|----------|
/// | Structurally valid, all counts correct | `Some(result)` | empty |
/// | Structurally parseable but count violations | `Some(partial)` | non-empty |
/// | Missing `UNB`/`UNZ`, stray segments, etc. | `None` | non-empty |
#[derive(Debug)]
#[non_exhaustive]
pub struct LenientResult {
    /// The parsed interchange, if extraction was structurally possible.
    pub interchange: Option<ValidatedInterchange>,
    /// All errors collected during validation, in discovery order.
    pub errors: Vec<EdifactError>,
}

impl LenientResult {
    /// Returns `true` if no errors were detected and the interchange is fully valid.
    #[inline]
    #[must_use]
    pub fn is_valid(&self) -> bool {
        self.errors.is_empty()
    }

    /// Returns `true` if one or more errors were collected.
    ///
    /// The readable inverse of [`is_valid`](Self::is_valid).
    /// A partial interchange may still be present even when `has_errors()` returns `true`.
    #[inline]
    #[must_use]
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Convert into a `Result`, returning the interchange on success or the errors on failure.
    ///
    /// The partial interchange (when present alongside errors) is discarded on the
    /// `Err` path.  Use the fields directly when you need both simultaneously.
    #[must_use]
    pub fn into_strict(self) -> Result<ValidatedInterchange, Vec<EdifactError>> {
        if self.errors.is_empty() {
            Ok(self.interchange.expect(
                "LenientResult: no errors but interchange is None — this is a bug in edifact-rs",
            ))
        } else {
            Err(self.errors)
        }
    }
}

/// Validate the EDIFACT envelope and collect **all** errors rather than stopping
/// at the first failure (borrowed-segment path).
///
/// Returns a [`LenientResult`] whose `interchange` field is:
///
/// - `Some(result)` with empty `errors` when fully valid.
/// - `Some(partial)` with non-empty `errors` when only count violations were found —
///   lets diagnostic tooling display the actual interchange structure.
/// - `None` when the interchange is structurally broken beyond recovery
///   (missing `UNB`/`UNZ`, stray segments, etc.).
pub fn validate_envelope_lenient(segments: &[Segment<'_>]) -> LenientResult {
    validate_envelope_lenient_impl(segments)
}

/// Lenient validation over an owned-segment slice — collects all errors.
///
/// See [`validate_envelope_lenient`] for full semantics.
pub fn validate_envelope_lenient_from_owned(segments: &[OwnedSegment]) -> LenientResult {
    validate_envelope_lenient_impl(segments)
}

// ── Core implementation ───────────────────────────────────────────────────────

fn validate_envelope_impl<S: SegmentReader>(
    segments: &[S],
) -> Result<ValidatedInterchange, EdifactError> {
    let mut interchange_env = extract_interchange(segments)?;

    let inner = if segments.len() >= 2 {
        &segments[1..segments.len() - 1]
    } else {
        &[]
    };

    let (functional_groups, messages) = extract_content(inner)?;

    // UNZ unit count semantics (ISO 9735-1 §9.2):
    //   with groups    → counts groups
    //   without groups → counts messages
    let actual_unit_count = if functional_groups.is_empty() {
        messages.len()
    } else {
        functional_groups.len()
    };
    interchange_env.actual_unit_count =
        u32::try_from(actual_unit_count).map_err(|_| EdifactError::InterchangeTooLarge {
            count: actual_unit_count as u64,
        })?;

    if interchange_env.declared_unit_count != interchange_env.actual_unit_count {
        return Err(EdifactError::MessageCountMismatch {
            expected: interchange_env.declared_unit_count,
            actual: interchange_env.actual_unit_count,
        });
    }

    for msg in &messages {
        if msg.declared_segment_count != msg.actual_segment_count {
            return Err(EdifactError::SegmentCountMismatch {
                expected: msg.declared_segment_count,
                actual: msg.actual_segment_count,
                message_ref: msg.message_ref.clone(),
            });
        }
    }

    Ok(ValidatedInterchange {
        interchange: interchange_env,
        functional_groups,
        messages,
    })
}

fn validate_envelope_lenient_impl<S: SegmentReader>(segments: &[S]) -> LenientResult {
    // Fast path: if strict validation passes there is nothing more to do.
    match validate_envelope_impl(segments) {
        Ok(result) => {
            return LenientResult {
                interchange: Some(result),
                errors: Vec::new(),
            };
        }
        Err(_) => {}
    }

    // Structural extraction: if UNB/UNZ are missing or unreadable we cannot
    // build any useful result.
    let mut ie = match extract_interchange(segments) {
        Ok(ie) => ie,
        Err(e) => {
            return LenientResult {
                interchange: None,
                errors: vec![e],
            };
        }
    };

    let inner = if segments.len() >= 2 {
        &segments[1..segments.len() - 1]
    } else {
        &[]
    };

    // Content extraction: structural errors (missing UNH/UNT, stray segments,
    // etc.) mean we cannot build a usable interchange either.
    let (functional_groups, messages) = match extract_content(inner) {
        Ok(pair) => pair,
        Err(e) => {
            return LenientResult {
                interchange: None,
                errors: vec![e],
            };
        }
    };

    // From here we have a parseable structure.  Collect count violations as
    // errors but still return the (partial) interchange so that diagnostic
    // tooling can display what was actually found.
    let mut errors: Vec<EdifactError> = Vec::new();

    let actual_unit_count = if functional_groups.is_empty() {
        messages.len()
    } else {
        functional_groups.len()
    };
    ie.actual_unit_count = u32::try_from(actual_unit_count).unwrap_or(u32::MAX);

    if ie.declared_unit_count != ie.actual_unit_count {
        errors.push(EdifactError::MessageCountMismatch {
            expected: ie.declared_unit_count,
            actual: ie.actual_unit_count,
        });
    }

    for msg in &messages {
        if msg.declared_segment_count != msg.actual_segment_count {
            errors.push(EdifactError::SegmentCountMismatch {
                expected: msg.declared_segment_count,
                actual: msg.actual_segment_count,
                message_ref: msg.message_ref.clone(),
            });
        }
    }

    let result = ValidatedInterchange {
        interchange: ie,
        functional_groups,
        messages,
    };
    LenientResult {
        interchange: Some(result),
        errors,
    }
}

// ── Interchange extraction ────────────────────────────────────────────────────

fn extract_interchange<S: SegmentReader>(
    segments: &[S],
) -> Result<InterchangeEnvelope, EdifactError> {
    if segments.first().map(|s| s.tag()) != Some("UNB") {
        return Err(EdifactError::MissingSegment {
            tag: "UNB".to_owned(),
            expected_position: "first segment of interchange".to_owned(),
        });
    }
    if segments.last().map(|s| s.tag()) != Some("UNZ") {
        return Err(EdifactError::MissingSegment {
            tag: "UNZ".to_owned(),
            expected_position: "last segment of interchange".to_owned(),
        });
    }

    let unb = &segments[0];
    let unz = &segments[segments.len() - 1];

    let syntax_identifier = unb.required_component_field(0, 0)?.to_owned();
    let syntax_version = unb.component(0, 1).unwrap_or("").to_owned();

    // Validate DE 0001 against the ISO 9735-1 §3.1 list of defined syntax identifiers.
    const VALID_SYNTAX_IDS: &[&str] = &["UNOA", "UNOB", "UNOC", "UNOD", "UNOE", "UNOF", "KECA"];
    if !VALID_SYNTAX_IDS.contains(&syntax_identifier.as_str()) {
        return Err(EdifactError::UnrecognisedSyntaxIdentifier(
            syntax_identifier,
        ));
    }

    let sender_id = unb.required_component_field(1, 0)?.to_owned();
    let sender_qualifier = unb.component(1, 1).unwrap_or("").to_owned();
    // UNB S002 comp[2]: DE 0014 — sender routing address
    let sender_routing_address = unb
        .component(1, 2)
        .filter(|s| !s.is_empty())
        .map(str::to_owned);

    let recipient_id = unb.required_component_field(2, 0)?.to_owned();
    let recipient_qualifier = unb.component(2, 1).unwrap_or("").to_owned();
    // UNB S003 comp[2]: DE 0014 — recipient routing address
    let recipient_routing_address = unb
        .component(2, 2)
        .filter(|s| !s.is_empty())
        .map(str::to_owned);

    let date = unb.required_component_field(3, 0)?.to_owned();
    let time_raw = unb.component(3, 1).unwrap_or("");
    let time = if time_raw.is_empty() {
        None
    } else {
        Some(time_raw.to_owned())
    };

    let control_ref = unb.required_component_field(4, 0)?.to_owned();

    // UNB element [5]: S005 — recipient's reference/password (DE 0022, comp 0) + qualifier (DE 0025, comp 1)
    let recipient_password = unb
        .component(5, 0)
        .filter(|s| !s.is_empty())
        .map(str::to_owned);
    let recipient_password_qualifier = unb
        .component(5, 1)
        .filter(|s| !s.is_empty())
        .map(str::to_owned);
    // UNB element [6]: DE 0026 — application reference
    let app_ref = unb
        .component(6, 0)
        .filter(|s| !s.is_empty())
        .map(str::to_owned);
    // UNB element [7]: DE 0029 — processing priority code
    let processing_priority = unb
        .component(7, 0)
        .filter(|s| !s.is_empty())
        .map(str::to_owned);
    // UNB element [8]: DE 0031 — acknowledgement request ("1" = requested)
    let acknowledgement_request = unb.component(8, 0).map_or(false, |v| v == "1");
    // UNB element [9]: DE 0032 — communications agreement ID
    let communications_agreement_id = unb
        .component(9, 0)
        .filter(|s| !s.is_empty())
        .map(str::to_owned);
    // UNB element [10]: DE 0035 — test indicator ("1" = test)
    let test_indicator = unb.component(10, 0).map_or(false, |v| v == "1");

    let unz_control_ref = unz.required_component_field(1, 0)?;
    if unz_control_ref != control_ref {
        return Err(EdifactError::QualifierMismatch {
            tag: "UNZ".to_owned(),
            actual: unz_control_ref.to_owned(),
            expected: control_ref,
            offset: unz.span_start(),
        });
    }

    let declared_unit_count: u32 =
        unz.required_component_field(0, 0)?
            .parse()
            .map_err(|_| EdifactError::InvalidText {
                offset: unz.span_start(),
            })?;

    Ok(InterchangeEnvelope {
        syntax_identifier,
        syntax_version,
        sender_id,
        sender_qualifier,
        sender_routing_address,
        recipient_id,
        recipient_qualifier,
        recipient_routing_address,
        date,
        time,
        control_ref,
        recipient_password,
        recipient_password_qualifier,
        app_ref,
        processing_priority,
        acknowledgement_request,
        communications_agreement_id,
        test_indicator,
        declared_unit_count,
        actual_unit_count: 0,
    })
}

// ── Content extraction ────────────────────────────────────────────────────────

fn extract_content<S: SegmentReader>(
    inner: &[S],
) -> Result<(Vec<FunctionalGroupEnvelope>, Vec<MessageEnvelope>), EdifactError> {
    // A UNG as the first inner segment means the interchange uses functional groups.
    // Checking only the first tag is O(1) and correct: if UNG is present it must
    // always be first; a stray UNE without a preceding UNG is caught downstream.
    if inner.first().map_or(false, |s| s.tag() == "UNG") {
        let groups = extract_with_groups(inner)?;
        let messages = groups
            .iter()
            .flat_map(|g| g.messages.iter().cloned())
            .collect();
        Ok((groups, messages))
    } else {
        let messages = extract_messages_flat(inner)?;
        Ok((vec![], messages))
    }
}

/// Find the index of the `UNE` that closes the `UNG` opened just before `start`.
fn find_matching_une<S: SegmentReader>(
    segments: &[S],
    start: usize,
) -> Result<usize, EdifactError> {
    for i in start..segments.len() {
        match segments[i].tag() {
            "UNE" => return Ok(i),
            "UNG" => {
                return Err(EdifactError::InvalidSegmentForMessage {
                    tag: "UNG".to_owned(),
                    message_type: "ENVELOPE".to_owned(),
                    offset: segments[i].span_start(),
                });
            }
            _ => {}
        }
    }
    Err(EdifactError::MissingSegment {
        tag: "UNE".to_owned(),
        expected_position: "end of functional group".to_owned(),
    })
}

fn extract_with_groups<S: SegmentReader>(
    inner: &[S],
) -> Result<Vec<FunctionalGroupEnvelope>, EdifactError> {
    let mut groups: Vec<FunctionalGroupEnvelope> = Vec::new();
    let mut i = 0;

    while i < inner.len() {
        let seg = &inner[i];
        match seg.tag() {
            "UNG" => {
                let ung_idx = i;
                let une_idx = find_matching_une(inner, ung_idx + 1)?;

                let ung = &inner[ung_idx];
                let group_id = ung.component(0, 0).unwrap_or("").to_owned();
                let app_sender = ung.component(1, 0).unwrap_or("").to_owned();
                let app_sender_qualifier = ung.component(1, 1).unwrap_or("").to_owned();
                let app_recipient = ung.component(2, 0).unwrap_or("").to_owned();
                let app_recipient_qualifier = ung.component(2, 1).unwrap_or("").to_owned();
                let date = ung.component(3, 0).unwrap_or("").to_owned();
                let time_raw = ung.component(3, 1).unwrap_or("");
                let time = if time_raw.is_empty() {
                    None
                } else {
                    Some(time_raw.to_owned())
                };
                // UNG DE 0048 — group reference number (mandatory per ISO 9735-1 §8)
                let group_ref = ung.required_component_field(4, 0)?.to_owned();
                let controlling_agency = ung.component(5, 0).unwrap_or("").to_owned();
                // UNG S008 — version (DE 0052, comp 0) + release (DE 0054, comp 1)
                // S008 is always at element index [6]; there is no element [7] in ISO 9735-1 §8.
                let version = ung.component(6, 0).unwrap_or("").to_owned();
                let release = ung.component(6, 1).unwrap_or("").to_owned();

                let une = &inner[une_idx];
                let declared_str = une.required_component_field(0, 0)?;
                let declared_message_count: u32 =
                    declared_str
                        .parse()
                        .map_err(|_| EdifactError::InvalidText {
                            offset: une.span_start(),
                        })?;
                let une_ref = une.required_component_field(1, 0)?;
                if une_ref != group_ref {
                    return Err(EdifactError::QualifierMismatch {
                        tag: "UNE".to_owned(),
                        actual: une_ref.to_owned(),
                        expected: group_ref.clone(),
                        offset: une.span_start(),
                    });
                }

                let group_content = &inner[ung_idx + 1..une_idx];
                let messages = extract_messages_flat(group_content)?;
                let actual_message_count = u32::try_from(messages.len()).map_err(|_| {
                    EdifactError::InterchangeTooLarge {
                        count: messages.len() as u64,
                    }
                })?;

                if declared_message_count != actual_message_count {
                    return Err(EdifactError::MessageCountMismatch {
                        expected: declared_message_count,
                        actual: actual_message_count,
                    });
                }

                groups.push(FunctionalGroupEnvelope {
                    group_id,
                    app_sender,
                    app_sender_qualifier,
                    app_recipient,
                    app_recipient_qualifier,
                    date,
                    time,
                    group_ref,
                    controlling_agency,
                    version,
                    release,
                    declared_message_count,
                    actual_message_count,
                    messages,
                });
                i = une_idx + 1;
            }
            "UNE" => {
                return Err(EdifactError::InvalidSegmentForMessage {
                    tag: "UNE".to_owned(),
                    message_type: "ENVELOPE".to_owned(),
                    offset: seg.span_start(),
                });
            }
            "UNH" => {
                // Mixing direct messages with functional groups is invalid.
                return Err(EdifactError::InvalidSegmentForMessage {
                    tag: "UNH".to_owned(),
                    message_type: "ENVELOPE".to_owned(),
                    offset: seg.span_start(),
                });
            }
            _ => {
                return Err(EdifactError::InvalidSegmentForMessage {
                    tag: seg.tag().to_owned(),
                    message_type: "ENVELOPE".to_owned(),
                    offset: seg.span_start(),
                });
            }
        }
    }

    Ok(groups)
}

/// Extract `UNH`/`UNT` message pairs from a flat slice (no UNB/UNZ/UNG/UNE expected).
fn extract_messages_flat<S: SegmentReader>(
    segments: &[S],
) -> Result<Vec<MessageEnvelope>, EdifactError> {
    let mut messages: Vec<MessageEnvelope> = Vec::new();
    let mut in_message = false;
    let mut msg_start_idx: usize = 0;
    let mut unh_idx: Option<usize> = None;

    for (i, seg) in segments.iter().enumerate() {
        match seg.tag() {
            "UNH" => {
                if in_message {
                    return Err(EdifactError::InvalidSegmentForMessage {
                        tag: "UNH".to_owned(),
                        message_type: "ENVELOPE".to_owned(),
                        offset: seg.span_start(),
                    });
                }
                in_message = true;
                msg_start_idx = i;
                unh_idx = Some(i);
            }
            "UNT" if in_message => {
                let u_idx = unh_idx.take().unwrap();
                let unh = &segments[u_idx];

                let message_ref = unh.required_component_field(0, 0)?.to_owned();
                let message_type = unh.required_component_field(1, 0)?.to_owned();
                let version = unh.required_component_field(1, 1)?.to_owned();
                let release = unh.required_component_field(1, 2)?.to_owned();
                let controlling_agency = unh.required_component_field(1, 3)?.to_owned();
                let association_code = unh.component(1, 4).unwrap_or("").to_owned();
                // UNH element [2]: DE 0068 — common access reference (optional)
                let common_access_ref = unh
                    .component(2, 0)
                    .filter(|s| !s.is_empty())
                    .map(str::to_owned);
                // UNH element [3]: S010 composite — sequence of transfers (optional)
                // comp[0] = DE 0070 (sequence number), comp[1] = DE 0073 (position indicator)
                let sequence_of_transfers = unh
                    .component(3, 0)
                    .filter(|s| !s.is_empty())
                    .and_then(|s| s.parse::<u32>().ok());
                let transfer_position = unh
                    .component(3, 1)
                    .filter(|s| !s.is_empty())
                    .map(str::to_owned);

                let declared_segment_count: u32 = seg
                    .required_component_field(0, 0)?
                    .parse()
                    .map_err(|_| EdifactError::InvalidText {
                        offset: seg.span_start(),
                    })?;
                let unt_ref = seg.required_component_field(1, 0)?;
                if unt_ref != message_ref {
                    return Err(EdifactError::QualifierMismatch {
                        tag: "UNT".to_owned(),
                        actual: unt_ref.to_owned(),
                        expected: message_ref.clone(),
                        offset: seg.span_start(),
                    });
                }

                let actual_segment_count = u32::try_from(i - msg_start_idx + 1).map_err(|_| {
                    EdifactError::InterchangeTooLarge {
                        count: u64::try_from(i - msg_start_idx + 1).unwrap_or(u64::MAX),
                    }
                })?;

                in_message = false;
                messages.push(MessageEnvelope {
                    message_ref,
                    message_type,
                    version,
                    release,
                    controlling_agency,
                    association_code,
                    common_access_ref,
                    sequence_of_transfers,
                    transfer_position,
                    declared_segment_count,
                    actual_segment_count,
                });
            }
            "UNT" => {
                return Err(EdifactError::InvalidSegmentForMessage {
                    tag: "UNT".to_owned(),
                    message_type: "ENVELOPE".to_owned(),
                    offset: seg.span_start(),
                });
            }
            "UNB" | "UNZ" | "UNG" | "UNE" if in_message => {
                return Err(EdifactError::InvalidSegmentForMessage {
                    tag: seg.tag().to_owned(),
                    message_type: "ENVELOPE".to_owned(),
                    offset: seg.span_start(),
                });
            }
            _ if !in_message => {
                return Err(EdifactError::InvalidSegmentForMessage {
                    tag: seg.tag().to_owned(),
                    message_type: "ENVELOPE".to_owned(),
                    offset: seg.span_start(),
                });
            }
            _ => {}
        }
    }

    if in_message {
        return Err(EdifactError::MissingSegment {
            tag: "UNT".to_owned(),
            expected_position: "end of message group".to_owned(),
        });
    }

    Ok(messages)
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    fn parse(input: &[u8]) -> Vec<crate::OwnedSegment> {
        crate::from_reader_collect(std::io::Cursor::new(input)).expect("parse failed")
    }

    fn parse_and_validate(input: &[u8]) -> Result<ValidatedInterchange, EdifactError> {
        let owned = parse(input);
        let segs: Vec<Segment<'_>> = owned.iter().map(crate::OwnedSegment::as_borrowed).collect();
        validate_envelope(&segs)
    }

    fn parse_and_validate_owned(input: &[u8]) -> Result<ValidatedInterchange, EdifactError> {
        validate_envelope_from_owned(&parse(input))
    }

    const VALID_INTERCHANGE: &[u8] =
        b"UNA:+.? 'UNB+UNOA:3+SENDER::293+RECEIVER::293+230401:0900+00001'UNH+00001+ORDERS:D:11A:UN:EAN010'BGM+220+PO-4711+9'DTM+137:20230401:102'UNT+4+00001'UNZ+1+00001'";

    #[test]
    fn valid_envelope_parses_ok() {
        let result = parse_and_validate(VALID_INTERCHANGE).expect("envelope should be valid");
        assert_eq!(result.interchange.sender_id, "SENDER");
        assert_eq!(result.interchange.sender_qualifier, ""); // no qualifier in fixture
        assert_eq!(result.interchange.recipient_id, "RECEIVER");
        assert_eq!(result.interchange.recipient_qualifier, "");
        assert_eq!(result.interchange.syntax_identifier, "UNOA");
        assert_eq!(result.interchange.syntax_version, "3");
        assert_eq!(result.interchange.control_ref, "00001");
        assert_eq!(result.interchange.declared_unit_count, 1);
        assert_eq!(result.interchange.actual_unit_count, 1);
        assert!(!result.interchange.is_test());
        assert!(!result.has_functional_groups());
        assert_eq!(result.message_count(), 1);
        assert_eq!(result.messages[0].message_type, "ORDERS");
        assert_eq!(result.messages[0].association_code, "EAN010");
        assert_eq!(result.messages[0].declared_segment_count, 4);
        assert_eq!(result.messages[0].actual_segment_count, 4);
    }

    #[test]
    fn valid_envelope_parses_ok_owned_path() {
        let result = parse_and_validate_owned(VALID_INTERCHANGE).expect("envelope should be valid");
        assert_eq!(result.interchange.sender_id, "SENDER");
        assert_eq!(result.interchange.actual_unit_count, 1);
        assert_eq!(result.messages[0].declared_segment_count, 4);
    }

    #[test]
    fn unt_count_mismatch_returns_err() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'UNH+1+ORDERS:D:11A:UN:EAN010'BGM+220+PO-1+9'DTM+137:20200101:102'UNT+99+1'UNZ+1+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(
                result,
                Err(EdifactError::SegmentCountMismatch { expected: 99, .. })
            ),
            "expected SegmentCountMismatch, got {result:?}"
        );
    }

    #[test]
    fn unz_count_mismatch_returns_err() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'UNH+1+ORDERS:D:11A:UN:EAN010'BGM+220+PO-1+9'UNT+3+1'UNZ+2+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(
                result,
                Err(EdifactError::MessageCountMismatch {
                    expected: 2,
                    actual: 1
                })
            ),
            "expected MessageCountMismatch(2,1), got {result:?}"
        );
    }

    #[test]
    fn missing_unb_returns_err() {
        let input = b"UNH+1+ORDERS:D:11A:UN:EAN010'BGM+220+PO-1+9'UNT+3+1'UNZ+1+1'";
        assert!(parse_and_validate(input).is_err());
    }

    #[test]
    fn extracts_una_interchange_correctly() {
        let result = parse_and_validate(VALID_INTERCHANGE).unwrap();
        assert_eq!(result.interchange.syntax_identifier, "UNOA");
        assert_eq!(result.interchange.syntax_version, "3");
        assert_eq!(result.interchange.date, "230401");
        assert_eq!(result.interchange.time.as_deref(), Some("0900"));
    }

    #[test]
    fn sender_and_recipient_qualifiers_extracted() {
        // GLN-qualified partners: 1234567890123:14 — qualifier at S002 comp 1
        let input = b"UNB+UNOA:3+1234567890123:14+9876543210987:14+200101:0900+1'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("GLN-qualified UNB must parse ok");
        assert_eq!(r.interchange.sender_id, "1234567890123");
        assert_eq!(r.interchange.sender_qualifier, "14");
        assert_eq!(r.interchange.recipient_id, "9876543210987");
        assert_eq!(r.interchange.recipient_qualifier, "14");
    }

    // UNB DE 0026 (app_ref) is at element index 6 (ISO 9735-1 §6.1.1):
    // [4]=control_ref [5]=S005/password [6]=0026/app_ref [7]=0029 [8]=0031/ack [9]=0032/comms [10]=0035/test

    #[test]
    fn test_indicator_parsed_from_unb() {
        // DE 0035 (test indicator) is at element index 10 (ISO 9735-1).
        // UNB+...+1 (ctrl) + (S005) + (0026) + (0029) + (0031) + (0032) + 1 (0035)
        //                    [5]       [6]       [7]       [8]       [9]     [10]
        let input = b"UNB+UNOA:3+S+R+200101:0900+1++++++1'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("test-flagged UNB must parse ok");
        assert!(
            r.interchange.test_indicator,
            "test_indicator should be true"
        );
        assert!(r.interchange.is_test(), "is_test() convenience must agree");
    }

    #[test]
    fn no_test_indicator_defaults_false() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        assert!(!r.interchange.test_indicator);
        assert!(!r.interchange.is_test());
    }

    #[test]
    fn app_ref_extracted_when_present() {
        // DE 0026 (app_ref) is at element index 6; element [5] (S005 password) is empty.
        let input = b"UNB+UNOA:3+S+R+200101:0900+1++MYAPP'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("UNB with app_ref must parse ok");
        assert_eq!(r.interchange.app_ref.as_deref(), Some("MYAPP"));
    }

    #[test]
    fn app_ref_is_none_when_absent() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        assert!(r.interchange.app_ref.is_none());
    }

    #[test]
    fn recipient_password_extracted_when_present() {
        // DE 0022 (recipient password) is at element index 5 (S005 comp 0).
        let input = b"UNB+UNOA:3+S+R+200101:0900+1+MYPASS'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("UNB with password must parse ok");
        assert_eq!(r.interchange.recipient_password.as_deref(), Some("MYPASS"));
    }

    #[test]
    fn recipient_password_is_none_when_absent() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        assert!(r.interchange.recipient_password.is_none());
    }

    #[test]
    fn acknowledgement_request_flag_parsed() {
        // DE 0031 (ack request) at element index 8; set to "1".
        // Elements: [5]S005="" [6]0026="" [7]0029="" [8]0031="1"
        let input = b"UNB+UNOA:3+S+R+200101:0900+1++++1'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("UNB with ack-request must parse ok");
        assert!(r.interchange.acknowledgement_request);
        assert!(r.interchange.ack_requested());
    }

    #[test]
    fn acknowledgement_request_defaults_false() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        assert!(!r.interchange.acknowledgement_request);
        assert!(!r.interchange.ack_requested());
    }

    #[test]
    fn communications_agreement_id_extracted() {
        // DE 0032 at element index 9; elements [5]-[8] empty.
        let input = b"UNB+UNOA:3+S+R+200101:0900+1+++++EANCOM'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("UNB with comms-agreement must parse ok");
        assert_eq!(
            r.interchange.communications_agreement_id.as_deref(),
            Some("EANCOM")
        );
    }

    #[test]
    fn dangling_unh_without_unt_returns_err() {
        let input =
            b"UNB+UNOA:3+S+R+200101:0900+1'UNH+1+ORDERS:D:11A:UN:EAN010'BGM+220+PO-1+9'UNZ+1+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(result, Err(EdifactError::MissingSegment { ref tag, .. }) if tag == "UNT")
        );
    }

    #[test]
    fn stray_segment_outside_message_returns_err() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'UNH+1+ORDERS:D:11A:UN:EAN010'BGM+220+PO-1+9'UNT+3+1'BGM+999+PO-2+9'UNZ+1+1'";
        assert!(matches!(
            parse_and_validate(input),
            Err(EdifactError::InvalidSegmentForMessage { .. })
        ));
    }

    #[test]
    fn missing_unb_sender_component_returns_err() {
        let input = b"UNB+UNOA:3++R+200101:0900+1'UNH+1+ORDERS:D:11A:UN:EAN010'BGM+220+PO-1+9'UNT+3+1'UNZ+1+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(result, Err(EdifactError::MissingRequiredComponent { ref tag, element_index: 1, component_index: 0 }) if tag == "UNB"),
            "expected MissingRequiredComponent for empty sender, got: {result:?}"
        );
    }

    #[test]
    fn nested_unh_without_closing_previous_message_returns_err() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'UNH+1+ORDERS:D:11A:UN:EAN010'BGM+220+PO-1+9'UNH+2+ORDERS:D:11A:UN:EAN010'UNT+3+2'UNZ+1+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(result, Err(EdifactError::InvalidSegmentForMessage { ref tag, .. }) if tag == "UNH"),
            "expected InvalidSegmentForMessage(UNH), got {result:?}"
        );
    }

    #[test]
    fn unt_message_reference_must_match_unh() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'UNH+1+ORDERS:D:11A:UN:EAN010'BGM+220+PO-1+9'UNT+3+999'UNZ+1+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(result, Err(EdifactError::QualifierMismatch { ref tag, .. }) if tag == "UNT")
        );
    }

    #[test]
    fn unz_control_reference_must_match_unb() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'UNH+1+ORDERS:D:11A:UN:EAN010'BGM+220+PO-1+9'UNT+3+1'UNZ+1+999'";
        let result = parse_and_validate(input);
        assert!(
            matches!(result, Err(EdifactError::QualifierMismatch { ref tag, .. }) if tag == "UNZ")
        );
    }

    #[test]
    fn missing_unh_message_type_components_return_err() {
        let input =
            b"UNB+UNOA:3+S+R+200101:0900+1'UNH+1+ORDERS:D:11A'BGM+220+PO-1+9'UNT+3+1'UNZ+1+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(result, Err(EdifactError::MissingRequiredComponent { ref tag, element_index: 1, component_index: 3 }) if tag == "UNH"),
            "got: {result:?}"
        );
    }

    #[test]
    fn nested_unz_inside_message_returns_err() {
        let input =
            b"UNB+UNOA:3+S+R+200101:0900+1'UNH+1+ORDERS:D:11A:UN:EAN010'UNZ+1+1'UNT+2+1'UNZ+1+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(result, Err(EdifactError::InvalidSegmentForMessage { ref tag, .. }) if tag == "UNZ")
        );
    }

    #[test]
    fn lenient_returns_partial_result_on_count_mismatch() {
        // UNZ says 2 but only 1 message — lenient mode must return Some(partial)
        // along with the error, not None.
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'UNH+1+ORDERS:D:11A:UN:EAN010'BGM+220+PO-1+9'UNT+3+1'UNZ+2+1'";
        let owned = parse(input);
        let segs: Vec<Segment<'_>> = owned.iter().map(crate::OwnedSegment::as_borrowed).collect();
        let lenient = validate_envelope_lenient(&segs);
        let result = lenient.interchange;
        let errors = lenient.errors;
        assert!(
            result.is_some(),
            "lenient mode must return Some even on count mismatch"
        );
        assert_eq!(errors.len(), 1);
        assert!(
            matches!(
                &errors[0],
                EdifactError::MessageCountMismatch {
                    expected: 2,
                    actual: 1
                }
            ),
            "expected MessageCountMismatch(2,1), got {:?}",
            errors[0]
        );
        let partial = result.unwrap();
        assert_eq!(partial.messages.len(), 1);
        assert_eq!(partial.interchange.actual_unit_count, 1);
        assert_eq!(partial.interchange.declared_unit_count, 2);
    }

    #[test]
    fn lenient_returns_none_on_structural_error() {
        // Missing UNB — no structure at all, expect None
        let input = b"UNH+1+ORDERS:D:11A:UN:EAN010'BGM+220+PO-1+9'UNT+3+1'UNZ+1+1'";
        let owned = parse(input);
        let segs: Vec<Segment<'_>> = owned.iter().map(crate::OwnedSegment::as_borrowed).collect();
        let lenient = validate_envelope_lenient(&segs);
        let result = lenient.interchange;
        let errors = lenient.errors;
        assert!(result.is_none(), "missing UNB must yield None");
        assert!(!errors.is_empty());
    }

    #[test]
    fn message_count_convenience_method() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        assert_eq!(r.message_count(), r.messages.len());
        assert_eq!(r.message_count(), 1);
    }

    #[test]
    fn interchange_with_single_functional_group_parses_ok() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNG+ORDERS+S+R+200101:0900+1+UN+D:96A'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNE+1+1'\
                      UNZ+1+1'";
        let result = parse_and_validate(input).expect("single-group interchange must parse ok");
        assert!(result.has_functional_groups());
        assert_eq!(result.functional_groups.len(), 1);
        let g = &result.functional_groups[0];
        assert_eq!(g.group_id, "ORDERS");
        assert_eq!(g.group_ref, "1");
        assert_eq!(g.controlling_agency, "UN");
        assert_eq!(g.declared_message_count, 1);
        assert_eq!(g.actual_message_count, 1);
        assert_eq!(result.messages.len(), 1);
        assert_eq!(result.messages[0].message_type, "ORDERS");
        assert_eq!(result.interchange.declared_unit_count, 1);
        assert_eq!(result.interchange.actual_unit_count, 1);
    }

    #[test]
    fn interchange_with_multi_message_group_parses_ok() {
        // One group containing 2 messages — UNZ = 1 group, UNE = 2 messages.
        // This is the key case that strip_functional_group_segments breaks.
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNG+ORDERS+S+R+200101:0900+1+UN+D:96A'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNH+2+ORDERS:D:96A:UN'\
                      BGM+220+PO-002+9'\
                      UNT+3+2'\
                      UNE+2+1'\
                      UNZ+1+1'";
        let result = parse_and_validate(input).expect("multi-message group must parse ok");
        assert!(result.has_functional_groups());
        assert_eq!(result.functional_groups.len(), 1);
        assert_eq!(result.functional_groups[0].actual_message_count, 2);
        assert_eq!(result.messages.len(), 2);
        // UNZ = 1 group (not 2 messages): ISO 9735-1 §9.2
        assert_eq!(result.interchange.actual_unit_count, 1);
        assert_eq!(result.interchange.declared_unit_count, 1);
    }

    #[test]
    fn interchange_with_multiple_groups_parses_ok() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+2'\
                      UNG+ORDERS+S+R+200101:0900+1+UN+D:96A'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNE+1+1'\
                      UNG+INVOIC+S+R+200101:0900+2+UN+D:96A'\
                      UNH+2+INVOIC:D:96A:UN'\
                      BGM+380+INV-001+9'\
                      UNT+3+2'\
                      UNE+1+2'\
                      UNZ+2+2'";
        let result = parse_and_validate(input).expect("multi-group interchange must parse ok");
        assert_eq!(result.functional_groups.len(), 2);
        assert_eq!(result.functional_groups[0].group_id, "ORDERS");
        assert_eq!(result.functional_groups[1].group_id, "INVOIC");
        assert_eq!(result.messages.len(), 2);
        assert_eq!(result.interchange.declared_unit_count, 2);
        assert_eq!(result.interchange.actual_unit_count, 2);
    }

    #[test]
    fn ung_une_count_mismatch_returns_err() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNG+ORDERS+S+R+200101:0900+1+UN+D:96A'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNE+2+1'\
                      UNZ+1+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(
                result,
                Err(EdifactError::MessageCountMismatch {
                    expected: 2,
                    actual: 1
                })
            ),
            "expected MessageCountMismatch(2,1), got {result:?}"
        );
    }

    #[test]
    fn une_without_ung_returns_err() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNE+1+1'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(result, Err(EdifactError::InvalidSegmentForMessage { ref tag, .. }) if tag == "UNE"),
            "expected InvalidSegmentForMessage(UNE), got {result:?}"
        );
    }

    #[test]
    fn ung_without_une_returns_err() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNG+ORDERS+S+R+200101:0900+1+UN+D:96A'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(result, Err(EdifactError::MissingSegment { ref tag, .. }) if tag == "UNE"),
            "expected MissingSegment(UNE), got {result:?}"
        );
    }

    #[test]
    fn une_group_ref_must_match_ung() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNG+ORDERS+S+R+200101:0900+1+UN+D:96A'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNE+1+999'\
                      UNZ+1+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(result, Err(EdifactError::QualifierMismatch { ref tag, .. }) if tag == "UNE"),
            "expected QualifierMismatch(UNE), got {result:?}"
        );
    }

    // ── New-field tests (ISO 9735-1 completeness) ─────────────────────────────

    #[test]
    fn processing_priority_extracted_when_present() {
        // DE 0029 at element index 7: [5]=S005="" [6]=0026="" [7]=0029="A"
        let input = b"UNB+UNOA:3+S+R+200101:0900+1+++A'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("UNB with processing_priority must parse ok");
        assert_eq!(r.interchange.processing_priority.as_deref(), Some("A"));
    }

    #[test]
    fn processing_priority_is_none_when_absent() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        assert!(r.interchange.processing_priority.is_none());
    }

    #[test]
    fn sender_routing_address_extracted_when_present() {
        // S002: sender_id:qualifier:routing  → comp[2] = routing address
        let input = b"UNB+UNOA:3+SENDER:14:ROUTEA+RECIP+200101:0900+1'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("UNB with sender routing must parse ok");
        assert_eq!(
            r.interchange.sender_routing_address.as_deref(),
            Some("ROUTEA")
        );
        assert!(r.interchange.recipient_routing_address.is_none());
    }

    #[test]
    fn recipient_routing_address_extracted_when_present() {
        // S003: recipient_id:qualifier:routing → comp[2] = routing address
        let input = b"UNB+UNOA:3+SENDER+RECIP:14:ROUTEB+200101:0900+1'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("UNB with recipient routing must parse ok");
        assert!(r.interchange.sender_routing_address.is_none());
        assert_eq!(
            r.interchange.recipient_routing_address.as_deref(),
            Some("ROUTEB")
        );
    }

    #[test]
    fn routing_address_is_none_when_absent() {
        // Plain S+R without sub-components — no routing addresses in S002/S003
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).unwrap();
        assert!(r.interchange.sender_routing_address.is_none());
        assert!(r.interchange.recipient_routing_address.is_none());
    }

    #[test]
    fn common_access_ref_extracted_when_present() {
        // UNH element [2] (DE 0068): common access reference
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNH+1+ORDERS:D:96A:UN+COMREF1'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("UNH with common_access_ref must parse ok");
        assert_eq!(r.messages[0].common_access_ref.as_deref(), Some("COMREF1"));
    }

    #[test]
    fn common_access_ref_is_none_when_absent() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        assert!(r.messages[0].common_access_ref.is_none());
    }

    #[test]
    fn parse_unh_includes_message_ref() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNH+REF42+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+REF42'\
                      UNZ+1+1'";
        // Validate the high-level API which exercises parse_unh internally;
        // the message_ref field on MessageEnvelope should equal the UNH DE 0062 value.
        let r = parse_and_validate(input).expect("must parse ok");
        assert_eq!(r.messages[0].message_ref, "REF42");
        assert_eq!(r.messages[0].message_type, "ORDERS");
    }

    #[test]
    fn iter_messages_by_type_returns_matching_messages() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+CTRL2'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNH+2+INVOIC:D:96A:UN'\
                      BGM+380+INV-001+9'\
                      UNT+3+2'\
                      UNZ+2+CTRL2'";
        let r = parse_and_validate(input).expect("two-message interchange must parse ok");
        let orders: Vec<_> = r.iter_messages_by_type("ORDERS").collect();
        assert_eq!(orders.len(), 1);
        assert_eq!(orders[0].message_ref, "1");
        let invoices: Vec<_> = r.iter_messages_by_type("INVOIC").collect();
        assert_eq!(invoices.len(), 1);
        assert_eq!(invoices[0].message_ref, "2");
        let none: Vec<_> = r.iter_messages_by_type("DESADV").collect();
        assert!(none.is_empty());
    }

    #[test]
    fn display_interchange_envelope() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        let s = r.interchange.to_string();
        assert!(s.contains("SENDER"), "Display must include sender_id");
        assert!(s.contains("UNOA"), "Display must include syntax_identifier");
    }

    #[test]
    fn display_message_envelope() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        let s = r.messages[0].to_string();
        assert!(s.contains("ORDERS"), "Display must include message_type");
        assert!(s.contains("ref="), "Display must include message ref label");
    }

    #[test]
    fn display_validated_interchange() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        let s = r.to_string();
        assert!(
            s.contains("messages="),
            "Display must include message count label"
        );
    }

    // ── DE 0001 syntax identifier validation ─────────────────────────────────

    #[test]
    fn unrecognised_syntax_identifier_returns_err() {
        // DE 0001 "XXXX" is not in the ISO 9735-1 §3.1 defined list.
        let input = b"UNB+XXXX:3+S+R+200101:0900+1'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(result, Err(EdifactError::UnrecognisedSyntaxIdentifier(ref id)) if id == "XXXX"),
            "expected UnrecognisedSyntaxIdentifier(\"XXXX\"), got {result:?}"
        );
    }

    #[test]
    fn all_valid_syntax_identifiers_accepted() {
        for id in &["UNOA", "UNOB", "UNOC", "UNOD", "UNOE", "UNOF", "KECA"] {
            let input = format!(
                "UNB+{id}:3+S+R+200101:0900+1'UNH+1+ORDERS:D:96A:UN'BGM+220+PO-001+9'UNT+3+1'UNZ+1+1'"
            );
            let result = parse_and_validate(input.as_bytes());
            assert!(
                result.is_ok(),
                "syntax id '{id}' should be accepted, got {result:?}"
            );
        }
    }

    // ── UNB S005 password qualifier ───────────────────────────────────────────

    #[test]
    fn recipient_password_qualifier_extracted_when_present() {
        // S005: MYPASS:AA — comp[0]=password, comp[1]=qualifier (DE 0025)
        let input = b"UNB+UNOA:3+S+R+200101:0900+1+MYPASS:AA'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("UNB with password+qualifier must parse ok");
        assert_eq!(r.interchange.recipient_password.as_deref(), Some("MYPASS"));
        assert_eq!(
            r.interchange.recipient_password_qualifier.as_deref(),
            Some("AA")
        );
    }

    #[test]
    fn recipient_password_qualifier_is_none_when_absent() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        assert!(r.interchange.recipient_password_qualifier.is_none());
    }

    // ── UNH S010 sequence-of-transfers ───────────────────────────────────────

    #[test]
    fn sequence_of_transfers_extracted_when_present() {
        // UNH element [2] = common access ref, element [3] = S010 (seq:position)
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNH+1+ORDERS:D:96A:UN++2:C'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("UNH with S010 must parse ok");
        assert_eq!(r.messages[0].sequence_of_transfers, Some(2));
        assert_eq!(r.messages[0].transfer_position.as_deref(), Some("C"));
    }

    #[test]
    fn sequence_of_transfers_none_when_absent() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        assert!(r.messages[0].sequence_of_transfers.is_none());
        assert!(r.messages[0].transfer_position.is_none());
    }

    // ── UNG S006/S007 application qualifiers ─────────────────────────────────

    #[test]
    fn ung_app_sender_and_recipient_qualifiers_extracted() {
        // UNG: group_id + S006(app_sender:qualifier) + S007(app_recip:qualifier) + ...
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNG+ORDERS+APPSEND:ZZZ+APPRECV:14+200101:0900+1+UN+D:96A'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNE+1+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("UNG with qualifiers must parse ok");
        let g = &r.functional_groups[0];
        assert_eq!(g.app_sender, "APPSEND");
        assert_eq!(g.app_sender_qualifier, "ZZZ");
        assert_eq!(g.app_recipient, "APPRECV");
        assert_eq!(g.app_recipient_qualifier, "14");
    }

    #[test]
    fn ung_qualifiers_empty_when_absent() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNG+ORDERS+S+R+200101:0900+1+UN+D:96A'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNE+1+1'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).unwrap();
        let g = &r.functional_groups[0];
        assert_eq!(g.app_sender_qualifier, "");
        assert_eq!(g.app_recipient_qualifier, "");
    }

    // ── LenientResult methods ─────────────────────────────────────────────────

    #[test]
    fn lenient_result_is_valid_true_on_clean_interchange() {
        let owned = parse(VALID_INTERCHANGE);
        let segs: Vec<Segment<'_>> = owned.iter().map(crate::OwnedSegment::as_borrowed).collect();
        let r = validate_envelope_lenient(&segs);
        assert!(r.is_valid());
        assert!(r.errors.is_empty());
        assert!(r.interchange.is_some());
    }

    #[test]
    fn lenient_result_into_strict_ok_path() {
        let owned = parse(VALID_INTERCHANGE);
        let segs: Vec<Segment<'_>> = owned.iter().map(crate::OwnedSegment::as_borrowed).collect();
        let r = validate_envelope_lenient(&segs);
        let strict = r.into_strict();
        assert!(
            strict.is_ok(),
            "into_strict() should succeed for valid interchange"
        );
        assert_eq!(strict.unwrap().messages.len(), 1);
    }

    #[test]
    fn lenient_result_into_strict_err_path() {
        // Count mismatch → into_strict() returns Err with the error
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'UNH+1+ORDERS:D:11A:UN:EAN010'BGM+220+PO-1+9'UNT+3+1'UNZ+2+1'";
        let owned = parse(input);
        let segs: Vec<Segment<'_>> = owned.iter().map(crate::OwnedSegment::as_borrowed).collect();
        let r = validate_envelope_lenient(&segs);
        assert!(!r.is_valid());
        let strict = r.into_strict();
        assert!(strict.is_err());
        let errors = strict.unwrap_err();
        assert_eq!(errors.len(), 1);
        assert!(matches!(
            &errors[0],
            EdifactError::MessageCountMismatch {
                expected: 2,
                actual: 1
            }
        ));
    }

    // ── Direct parse_unh / parse_ung API ─────────────────────────────────────

    #[test]
    fn parse_unh_direct_extracts_all_s009_fields() {
        // parse_unh is called internally by extract_messages_flat; all S009 fields
        // it extracts surface in the resulting MessageEnvelope.  We verify them here
        // rather than calling parse_unh(&seg) from a Vec<Segment<'_>>, which would
        // conflict with the SmallVec-based Element drop-check (see API docs).
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNH+REF99+ORDERS:D:96A:UN:EAN010'\
                      BGM+220+PO-001+9'\
                      UNT+3+REF99'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("must parse ok");
        let msg = &r.messages[0];
        assert_eq!(msg.message_ref, "REF99");
        assert_eq!(msg.message_type, "ORDERS");
        assert_eq!(msg.version, "D");
        assert_eq!(msg.release, "96A");
        assert_eq!(msg.controlling_agency, "UN");
        assert_eq!(msg.association_code, "EAN010");
    }

    #[test]
    fn parse_ung_direct_extracts_identifier_fields() {
        // parse_ung fields surface via the FunctionalGroupEnvelope returned by validation.
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNG+ORDERS+APPSEND:ZZZ+APPRECV:14+200101:0900+GRP01+UN+D:96A'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNE+1+GRP01'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("must parse ok");
        let g = &r.functional_groups[0];
        assert_eq!(g.group_id, "ORDERS");
        assert_eq!(g.app_sender, "APPSEND");
        assert_eq!(g.app_sender_qualifier, "ZZZ");
        assert_eq!(g.app_recipient, "APPRECV");
        assert_eq!(g.app_recipient_qualifier, "14");
        assert_eq!(g.group_ref, "GRP01");
        assert_eq!(g.controlling_agency, "UN");
        assert_eq!(g.version, "D");
        assert_eq!(g.release, "96A");
    }

    // ── find_message convenience method ──────────────────────────────────────

    #[test]
    fn find_message_returns_correct_message_by_ref() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+CTRL2'\
                      UNH+REF-A+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+REF-A'\
                      UNH+REF-B+INVOIC:D:96A:UN'\
                      BGM+380+INV-001+9'\
                      UNT+3+REF-B'\
                      UNZ+2+CTRL2'";
        let r = parse_and_validate(input).expect("two-message interchange must parse ok");
        let msg_a = r.find_message("REF-A");
        assert!(msg_a.is_some());
        assert_eq!(msg_a.unwrap().message_type, "ORDERS");
        let msg_b = r.find_message("REF-B");
        assert!(msg_b.is_some());
        assert_eq!(msg_b.unwrap().message_type, "INVOIC");
        assert!(r.find_message("MISSING").is_none());
    }

    // ── UNG missing mandatory group_ref ──────────────────────────────────────

    #[test]
    fn ung_missing_group_ref_returns_err() {
        // UNG with element [4] (group ref) empty — must error, not silently use ""
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNG+ORDERS+S+R+200101:0900++UN+D:96A'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNE+1+'\
                      UNZ+1+1'";
        let result = parse_and_validate(input);
        assert!(
            matches!(result,
                Err(EdifactError::MissingRequiredComponent { ref tag, element_index: 4, component_index: 0 })
                if tag == "UNG"
            ),
            "expected MissingRequiredComponent for empty UNG group_ref, got {result:?}"
        );
    }

    // ── Edge case and ergonomics tests ────────────────────────────────────────

    #[test]
    fn empty_segment_list_returns_missing_unb() {
        // Contract: validate_envelope(&[]) must return MissingSegment{UNB},
        // not panic or return Ok.
        let result = validate_envelope(&[]);
        assert!(
            matches!(result, Err(EdifactError::MissingSegment { ref tag, .. }) if tag == "UNB"),
            "expected MissingSegment(UNB) for empty input, got {result:?}"
        );
    }

    #[test]
    fn single_segment_only_unb_returns_missing_unz() {
        // Only UNB, no UNZ — should fail with MissingSegment{UNZ}.
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'";
        let owned = parse(input);
        let segs: Vec<Segment<'_>> = owned.iter().map(crate::OwnedSegment::as_borrowed).collect();
        let result = validate_envelope(&segs);
        assert!(
            matches!(result, Err(EdifactError::MissingSegment { ref tag, .. }) if tag == "UNZ"),
            "expected MissingSegment(UNZ) for UNB-only input, got {result:?}"
        );
    }

    #[test]
    fn display_validated_interchange_includes_count() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        let s = r.to_string();
        // Must include the numeric count, not just the label
        assert!(
            s.contains("messages=1"),
            "Display must include count '1': {s}"
        );
    }

    #[test]
    fn display_interchange_envelope_contains_arrow() {
        let r = parse_and_validate(VALID_INTERCHANGE).unwrap();
        let s = r.interchange.to_string();
        // Must use ASCII arrow, not Unicode →
        assert!(s.contains("->"), "Display must use ASCII '->' arrow: {s}");
        assert!(
            !s.contains('\u{2192}'),
            "Display must not use Unicode → arrow: {s}"
        );
    }

    #[test]
    fn display_functional_group_envelope() {
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'\
                      UNG+ORDERS+APPSEND+APPRECV+200101:0900+GRP01+UN+D:96A'\
                      UNH+1+ORDERS:D:96A:UN'\
                      BGM+220+PO-001+9'\
                      UNT+3+1'\
                      UNE+1+GRP01'\
                      UNZ+1+1'";
        let r = parse_and_validate(input).expect("must parse ok");
        let g = &r.functional_groups[0];
        let s = g.to_string();
        assert!(s.contains("ORDERS"), "Display must include group_id: {s}");
        assert!(
            s.contains("APPSEND"),
            "Display must include app_sender: {s}"
        );
        assert!(
            s.contains("APPRECV"),
            "Display must include app_recipient: {s}"
        );
        assert!(s.contains("GRP01"), "Display must include group_ref: {s}");
        assert!(
            s.contains("msgs="),
            "Display must include message count label: {s}"
        );
        assert!(
            s.contains("1/1"),
            "Display must include actual/declared counts: {s}"
        );
    }

    #[test]
    fn lenient_has_errors_is_inverse_of_is_valid() {
        let owned = parse(VALID_INTERCHANGE);
        let segs: Vec<Segment<'_>> = owned.iter().map(crate::OwnedSegment::as_borrowed).collect();
        let valid = validate_envelope_lenient(&segs);
        assert!(valid.is_valid());
        assert!(!valid.has_errors());

        // Count mismatch: is_valid() == false, has_errors() == true
        let input = b"UNB+UNOA:3+S+R+200101:0900+1'UNH+1+ORDERS:D:11A:UN:EAN010'BGM+220+PO-1+9'UNT+3+1'UNZ+2+1'";
        let owned2 = parse(input);
        let segs2: Vec<Segment<'_>> = owned2
            .iter()
            .map(crate::OwnedSegment::as_borrowed)
            .collect();
        let invalid = validate_envelope_lenient(&segs2);
        assert!(!invalid.is_valid());
        assert!(invalid.has_errors());
    }
}