hl7v2 1.5.0

HL7 v2 message parser and processor for Rust
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
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
//! Profile validation for HL7 v2 messages.
//!
//! This module provides functionality for loading and applying
//! conformance profiles to HL7 v2 messages. It builds on
//! `hl7v2::conformance::validation` for core validation logic.

#![expect(
    clippy::collapsible_if,
    clippy::arithmetic_side_effects,
    clippy::indexing_slicing,
    clippy::manual_let_else,
    clippy::map_err_ignore,
    clippy::missing_errors_doc,
    clippy::string_slice,
    clippy::uninlined_format_args,
    reason = "Pre-existing profile implementation debt moved from hl7v2-prof; cleanup is separate from this behavior-preserving module collapse."
)]
//!
//! # Features
//!
//! - Profile loading from YAML
//! - Profile inheritance and merging
//! - Profile-based message validation
//! - Cross-field validation rules
//! - Temporal validation rules
//! - Contextual validation rules
//!
//! # Example
//!
//! ```ignore
//! use hl7v2::{load_profile, validate, Profile};
//!
//! let yaml = r#"
//! message_structure: ADT_A01
//! version: "2.5.1"
//! segments:
//!   - id: MSH
//! constraints:
//!   - path: MSH.9
//!     required: true
//! "#;
//!
//! let profile = load_profile(yaml)?;
//! let issues = validate(&message, &profile);
//! ```

// Re-export validation types for compatibility with the old profile facade.
pub use super::validation::{
    Issue, ParsedTimestamp, RuleAction, RuleCondition, Severity, TimestampPrecision,
    ValidationResult, Validator, check_rule_condition, compare_timestamps_for_before, get_nonempty,
    is_coded_value, is_date, is_email, is_extended_id, is_formatted_text, is_hierarchic_designator,
    is_identifier, is_numeric, is_person_name, is_phone_number, is_sequence_id, is_ssn, is_string,
    is_text_data, is_time, is_timestamp, is_valid_age_range, is_valid_birth_date, is_within_range,
    matches_complex_pattern, matches_format, parse_datetime, parse_hl7_ts,
    parse_hl7_ts_with_precision, truncate_to_precision, validate_checksum, validate_data_type,
    validate_luhn_checksum, validate_mathematical_relationship, validate_mod10_checksum,
};

use crate::model::{Error, Message};
use crate::parser::parse;
use regex::Regex;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::cmp::Ordering;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fs;
use std::io;
use std::path::{Path, PathBuf};

/// Profile loading error types.
///
/// These errors provide detailed information about profile loading failures,
/// making it easier to diagnose configuration and parsing issues.
#[derive(Debug, thiserror::Error)]
pub enum ProfileLoadError {
    /// YAML syntax error during parsing.
    #[error("YAML parse error: {0}")]
    YamlParse(String),

    /// Required field is missing from the profile.
    #[error("Missing required field: {field}")]
    MissingField {
        /// The name of the missing field.
        field: String,
    },

    /// Invalid field value in the profile.
    #[error("Invalid value for field '{field}': {details}")]
    InvalidValue {
        /// The name of the field with an invalid value.
        field: String,
        /// Details about why the value is invalid.
        details: String,
    },

    /// IO error during profile file reading.
    #[error("IO error: {0}")]
    Io(String),

    /// Profile inheritance cycle detected.
    #[error("Profile inheritance cycle detected: {0}")]
    InheritanceCycle(String),

    /// Parent profile not found.
    #[error("Parent profile not found: {0}")]
    ParentNotFound(String),

    /// Network error during remote profile loading.
    #[error("Network error: {0}")]
    Network(#[from] reqwest::Error),

    /// Profile not found in cache or local filesystem.
    #[error("Profile not found: {0}")]
    NotFound(String),

    /// Invalid URL scheme for remote loading.
    #[error("Invalid URL scheme: {0}. Only http and https are supported.")]
    InvalidScheme(String),

    /// Cache operation failed.
    #[error("Cache error: {0}")]
    Cache(String),

    /// Core HL7 library error.
    #[error("Core error: {0}")]
    Core(String),
}

impl From<serde_yaml::Error> for ProfileLoadError {
    fn from(err: serde_yaml::Error) -> Self {
        ProfileLoadError::YamlParse(err.to_string())
    }
}

impl From<std::io::Error> for ProfileLoadError {
    fn from(err: std::io::Error) -> Self {
        ProfileLoadError::Io(err.to_string())
    }
}

impl From<Error> for ProfileLoadError {
    fn from(err: Error) -> Self {
        ProfileLoadError::Core(err.to_string())
    }
}

/// A conformance profile
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Profile {
    /// HL7 message structure name (for example, `ADT_A01`).
    pub message_structure: String,
    /// HL7 version string (for example, `2.5.1`).
    pub version: String,
    /// Optional message type override.
    #[serde(default)]
    pub message_type: Option<String>,
    /// Reference to parent profile by name for profile inheritance.
    #[serde(default)]
    pub parent: Option<String>,
    /// Segment specifications for this profile.
    pub segments: Vec<SegmentSpec>,
    /// Field and primitive constraints.
    #[serde(default)]
    pub constraints: Vec<Constraint>,
    /// Field length constraints.
    #[serde(default)]
    pub lengths: Vec<LengthConstraint>,
    /// HL7 value sets referenced by the profile.
    #[serde(default)]
    pub valuesets: Vec<ValueSet>,
    /// Simple datatype constraints.
    #[serde(default)]
    pub datatypes: Vec<DataTypeConstraint>,
    /// Advanced datatype constraints for richer checks.
    #[serde(default)]
    pub advanced_datatypes: Vec<AdvancedDataTypeConstraint>,
    /// Cross-field validation rules.
    #[serde(default)]
    pub cross_field_rules: Vec<CrossFieldRule>,
    /// Temporal validation rules for date/time comparisons.
    #[serde(default)]
    pub temporal_rules: Vec<TemporalRule>,
    /// Contextual validation rules based on message context.
    #[serde(default)]
    pub contextual_rules: Vec<ContextualRule>,
    /// Custom extension validation rules.
    #[serde(default)]
    pub custom_rules: Vec<CustomRule>,
    /// HL7 table definitions used by value-set checks.
    #[serde(default)]
    pub hl7_tables: Vec<HL7Table>,
    /// Table precedence order - defines the order in which tables should be checked
    /// when multiple tables could apply to a field
    #[serde(default)]
    pub table_precedence: Vec<String>,
    /// Expression guardrails - rules that limit how expressions can be used in profiles
    #[serde(default)]
    pub expression_guardrails: ExpressionGuardrails,
}

/// Specification for a segment in a profile
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SegmentSpec {
    /// Segment identifier (for example, `MSH`).
    pub id: String,
}

/// Constraint on a field path
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Constraint {
    /// Path of the constrained field.
    pub path: String,
    /// Whether the field is mandatory.
    #[serde(default)]
    pub required: bool,
    /// Optional component-level constraint.
    #[serde(default)]
    pub components: Option<ComponentConstraint>,
    /// Allowed literal values.
    #[serde(default)]
    pub r#in: Option<Vec<String>>,
    /// Condition under which this constraint is active.
    #[serde(default)]
    pub when: Option<Condition>,
    /// Regex pattern that the field value must match.
    #[serde(default)]
    pub pattern: Option<String>,
}

/// Component constraint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComponentConstraint {
    /// Minimum number of values/components.
    pub min: Option<usize>,
    /// Maximum number of values/components.
    pub max: Option<usize>,
}

/// Conditional constraint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Condition {
    /// Match exactly one of these values.
    #[serde(default)]
    pub eq: Option<Vec<String>>,
    /// Match when any nested condition is satisfied.
    #[serde(default)]
    pub any: Option<Vec<Condition>>,
}

/// Length constraint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LengthConstraint {
    /// Path to the constrained field.
    pub path: String,
    /// Optional maximum length.
    pub max: Option<usize>,
    /// Truncation policy (`no-truncate` or `may-truncate`).
    pub policy: Option<String>,
}

/// Value set constraint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValueSet {
    /// Field path where this value set applies.
    pub path: String,
    /// Name of the value set.
    pub name: String,
    /// Codes can be defined inline OR reference an HL7 table by name
    #[serde(default)]
    pub codes: Vec<String>,
}

/// Data type constraint
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DataTypeConstraint {
    /// Field path constrained by datatype.
    pub path: String,
    /// HL7 datatype identifier (for example, `ST`, `ID`, `DT`).
    pub r#type: String,
}

/// Advanced data type constraint with complex validation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdvancedDataTypeConstraint {
    /// Field path constrained by advanced datatype rules.
    pub path: String,
    /// HL7 datatype identifier (for example, `ST`, `ID`, `DT`).
    pub r#type: String,
    /// Optional regex pattern to validate the field.
    #[serde(default)]
    pub pattern: Option<String>,
    /// Minimum length constraint.
    #[serde(default)]
    pub min_length: Option<usize>,
    /// Maximum length constraint.
    #[serde(default)]
    pub max_length: Option<usize>,
    /// Optional format hint (for example, `YYYY-MM-DD`).
    #[serde(default)]
    pub format: Option<String>,
    /// Optional checksum algorithm name.
    #[serde(default)]
    pub checksum: Option<String>,
}

/// Temporal validation rule for date/time relationships
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemporalRule {
    /// Rule identifier.
    pub id: String,
    /// Human-readable description.
    pub description: String,
    /// Path expected to be earlier than `after`.
    pub before: String,
    /// Path expected to be later than `before`.
    pub after: String,
    /// Whether equal timestamps are allowed.
    #[serde(default)]
    pub allow_equal: bool,
    /// Optional tolerance for comparison.
    #[serde(default)]
    pub tolerance: Option<String>,
}

/// Contextual validation rule based on message context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ContextualRule {
    /// Rule identifier.
    pub id: String,
    /// Human-readable description.
    pub description: String,
    /// Field used to determine applicability.
    pub context_field: String,
    /// Required field value to activate this rule.
    pub context_value: String,
    /// Field validated when the context matches.
    pub target_field: String,
    /// Validation type to execute.
    pub validation_type: String,
    /// Parameters passed to the validator.
    #[serde(default)]
    pub parameters: std::collections::HashMap<String, String>,
}

/// HL7 Table definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HL7Table {
    /// HL7 table identifier (for example, `HL70001`).
    pub id: String,
    /// Table display name.
    pub name: String,
    /// Table version.
    pub version: String,
    /// Table values.
    pub codes: Vec<HL7TableEntry>,
}

/// Entry in an HL7 table
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HL7TableEntry {
    /// Code value.
    pub value: String,
    /// Code description.
    pub description: String,
    /// Entry status (`A` active, `D` deprecated, `R` restricted).
    #[serde(default)]
    pub status: String,
}

/// Cross-field validation rule
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CrossFieldRule {
    /// Rule identifier.
    pub id: String,
    /// Human-readable description.
    pub description: String,
    /// Validation mode: "conditional" (default) or "assert"
    /// - "conditional": If conditions are met, execute actions
    /// - "assert": Conditions must be true, fail otherwise
    #[serde(default = "default_validation_mode")]
    pub validation_mode: String,
    /// Conditions that gate this rule.
    pub conditions: Vec<RuleCondition>,
    /// Actions produced when conditions pass.
    pub actions: Vec<RuleAction>,
}

fn default_validation_mode() -> String {
    "conditional".to_string()
}

/// Custom validation rule
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CustomRule {
    /// Rule identifier.
    pub id: String,
    /// Human-readable description.
    pub description: String,
    /// Rule script or reference to external logic.
    pub script: String,
}

/// Expression guardrails - rules that limit how expressions can be used in profiles
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct ExpressionGuardrails {
    /// Maximum depth of nested expressions
    #[serde(default)]
    pub max_depth: Option<usize>,
    /// Maximum length of expression strings
    #[serde(default)]
    pub max_length: Option<usize>,
    /// Whether to allow custom scripts
    #[serde(default)]
    pub allow_custom_scripts: bool,
}

/// Result of linting a profile definition.
///
/// Profile linting checks the profile as configuration, before it is applied to
/// a message. It reports YAML/load failures plus structural issues that the
/// runtime validator would otherwise ignore or only reveal during validation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileLintReport {
    /// Whether the profile has no lint errors.
    pub valid: bool,
    /// Number of errors in `issues`.
    pub error_count: usize,
    /// Number of warnings in `issues`.
    pub warning_count: usize,
    /// Total number of issues.
    pub issue_count: usize,
    /// Lint findings.
    pub issues: Vec<ProfileLintIssue>,
}

impl ProfileLintReport {
    fn from_issues(issues: Vec<ProfileLintIssue>) -> Self {
        let error_count = issues
            .iter()
            .filter(|issue| issue.severity == ProfileLintSeverity::Error)
            .count();
        let warning_count = issues
            .iter()
            .filter(|issue| issue.severity == ProfileLintSeverity::Warning)
            .count();
        Self {
            valid: error_count == 0,
            error_count,
            warning_count,
            issue_count: issues.len(),
            issues,
        }
    }

    /// Convert this v1 lint report into the explicit v2 evidence contract shape.
    ///
    /// This preserves the default serialized form of [`ProfileLintReport`].
    /// Producers opt into v2 when they are ready to emit embedded provenance.
    #[must_use]
    pub fn to_v2(
        &self,
        tool_name: impl Into<String>,
        tool_version: impl Into<String>,
    ) -> ProfileLintReportV2 {
        ProfileLintReportV2 {
            schema_version: "2".to_string(),
            tool_name: tool_name.into(),
            tool_version: tool_version.into(),
            report: self.clone(),
        }
    }
}

/// Profile lint report v2 with embedded evidence provenance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileLintReportV2 {
    /// Evidence artifact schema version.
    pub schema_version: String,
    /// Producer surface that generated this profile lint report.
    pub tool_name: String,
    /// Producer package version.
    pub tool_version: String,
    /// V1 profile lint report fields.
    #[serde(flatten)]
    pub report: ProfileLintReport,
}

/// Structured explanation of a loaded profile contract.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainReport {
    /// Profile identifier supplied by the producer, usually a relative path.
    pub profile: String,
    /// SHA-256 of the source profile YAML.
    pub profile_sha256: String,
    /// HL7 message structure declared by the profile.
    pub message_structure: String,
    /// HL7 version declared by the profile.
    pub version: String,
    /// Message type declared by the profile, when present.
    pub message_type: Option<String>,
    /// Parent profile declared by the profile, when present.
    pub parent: Option<String>,
    /// Count summary for the profile contents.
    pub summary: ProfileExplainSummary,
    /// Declared segments.
    pub segments: Vec<ProfileExplainSegment>,
    /// Required field constraints.
    pub required_fields: Vec<ProfileExplainRequiredField>,
    /// Field-level constraints.
    pub field_constraints: Vec<ProfileExplainConstraint>,
    /// Length rules.
    pub length_rules: Vec<ProfileExplainLengthRule>,
    /// Datatype rules.
    pub datatype_rules: Vec<ProfileExplainDatatypeRule>,
    /// Value set references.
    pub value_sets: Vec<ProfileExplainValueSet>,
    /// Advanced rule groups.
    pub rules: ProfileExplainRules,
    /// Embedded HL7 tables.
    pub hl7_tables: Vec<ProfileExplainTable>,
    /// Table precedence configured by the profile.
    pub table_precedence: Vec<String>,
    /// Expression guardrail settings.
    pub expression_guardrails: ProfileExplainExpressionGuardrails,
    /// Lint summary folded into the explain report.
    pub lint: ProfileExplainLintSummary,
}

impl ProfileExplainReport {
    /// Convert this v1 profile explain report into the explicit v2 evidence
    /// contract shape.
    ///
    /// This preserves the default serialized form of [`ProfileExplainReport`].
    /// Producers opt into v2 when they are ready to emit embedded provenance.
    #[must_use]
    pub fn to_v2(
        &self,
        tool_name: impl Into<String>,
        tool_version: impl Into<String>,
    ) -> ProfileExplainReportV2 {
        ProfileExplainReportV2 {
            schema_version: "2".to_string(),
            tool_name: tool_name.into(),
            tool_version: tool_version.into(),
            report: self.clone(),
        }
    }
}

/// Profile explain report v2 with embedded evidence provenance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainReportV2 {
    /// Evidence artifact schema version.
    pub schema_version: String,
    /// Producer surface that generated this profile explain report.
    pub tool_name: String,
    /// Producer package version.
    pub tool_version: String,
    /// V1 profile explain report fields.
    #[serde(flatten)]
    pub report: ProfileExplainReport,
}

/// Count summary for a profile explain report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainSummary {
    /// Number of declared segments.
    pub segment_count: usize,
    /// Number of required field constraints.
    pub required_field_count: usize,
    /// Number of field constraints.
    pub field_constraint_count: usize,
    /// Number of length rules.
    pub length_rule_count: usize,
    /// Number of simple datatype rules.
    pub datatype_rule_count: usize,
    /// Number of advanced datatype rules.
    pub advanced_datatype_rule_count: usize,
    /// Number of value sets.
    pub value_set_count: usize,
    /// Number of cross-field rules.
    pub cross_field_rule_count: usize,
    /// Number of temporal rules.
    pub temporal_rule_count: usize,
    /// Number of contextual rules.
    pub contextual_rule_count: usize,
    /// Number of custom rules.
    pub custom_rule_count: usize,
    /// Number of embedded HL7 tables.
    pub hl7_table_count: usize,
}

/// A segment declared by a profile.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainSegment {
    /// Segment identifier, such as `MSH` or `PID`.
    pub id: String,
}

/// A required field recorded in a profile explain report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainRequiredField {
    /// HL7 path for the required field.
    pub path: String,
    /// Whether the requirement is conditional.
    pub conditional: bool,
}

/// A field constraint recorded in a profile explain report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainConstraint {
    /// HL7 path for the constraint.
    pub path: String,
    /// Whether the field is required.
    pub required: bool,
    /// Whether the constraint is conditional.
    pub conditional: bool,
    /// Minimum component cardinality, when configured.
    pub component_min: Option<usize>,
    /// Maximum component cardinality, when configured.
    pub component_max: Option<usize>,
    /// Count of inline allowed values.
    pub allowed_value_count: usize,
    /// Inline allowed values.
    pub allowed_values: Vec<String>,
    /// Regex pattern constraint, when configured.
    pub pattern: Option<String>,
}

/// A length rule recorded in a profile explain report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainLengthRule {
    /// HL7 path for the length rule.
    pub path: String,
    /// Maximum length, when configured.
    pub max: Option<usize>,
    /// Enforcement policy, when configured.
    pub policy: Option<String>,
}

/// A datatype rule recorded in a profile explain report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainDatatypeRule {
    /// HL7 path for the datatype rule.
    pub path: String,
    /// Datatype name.
    pub datatype: String,
    /// Rule kind, such as `simple` or `advanced`.
    pub kind: String,
    /// Regex pattern, when configured.
    pub pattern: Option<String>,
    /// Minimum length, when configured.
    pub min_length: Option<usize>,
    /// Maximum length, when configured.
    pub max_length: Option<usize>,
    /// Format rule, when configured.
    pub format: Option<String>,
    /// Checksum rule, when configured.
    pub checksum: Option<String>,
}

/// A value-set reference recorded in a profile explain report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainValueSet {
    /// Value-set name.
    pub name: String,
    /// HL7 path constrained by this value set.
    pub path: String,
    /// Source category, such as `inline`, `hl7_table`, or `empty`.
    pub source: String,
    /// Number of inline codes.
    pub inline_code_count: usize,
    /// Number of table codes.
    pub table_code_count: usize,
}

/// Advanced rule groups recorded in a profile explain report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainRules {
    /// Cross-field rules.
    pub cross_field: Vec<ProfileExplainRule>,
    /// Temporal rules.
    pub temporal: Vec<ProfileExplainRule>,
    /// Contextual rules.
    pub contextual: Vec<ProfileExplainRule>,
    /// Custom rules.
    pub custom: Vec<ProfileExplainRule>,
}

/// A named profile rule.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainRule {
    /// Rule identifier.
    pub id: String,
    /// Human-readable rule description.
    pub description: String,
}

/// An embedded HL7 table recorded in a profile explain report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainTable {
    /// Table identifier.
    pub id: String,
    /// Table name.
    pub name: String,
    /// Table version.
    pub version: String,
    /// Number of codes in the table.
    pub code_count: usize,
}

/// Expression guardrail settings recorded in a profile explain report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainExpressionGuardrails {
    /// Maximum expression depth, when configured.
    pub max_depth: Option<usize>,
    /// Maximum expression length, when configured.
    pub max_length: Option<usize>,
    /// Whether custom scripts are allowed.
    pub allow_custom_scripts: bool,
}

/// Lint summary embedded in a profile explain report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileExplainLintSummary {
    /// Whether linting reported no errors.
    pub valid: bool,
    /// Number of lint errors.
    pub error_count: usize,
    /// Number of lint warnings.
    pub warning_count: usize,
    /// Total lint issue count.
    pub issue_count: usize,
    /// Ignored or unsupported configuration warnings.
    pub ignored_or_unsupported: Vec<ProfileLintIssue>,
}

/// Machine-readable report for profile fixture tests.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileTestReport {
    /// Profile identifier supplied by the producer, usually a path.
    pub profile: String,
    /// Fixture root identifier supplied by the producer, usually a path.
    pub fixtures: String,
    /// Whether all fixture cases passed.
    pub valid: bool,
    /// Number of fixture cases.
    pub case_count: usize,
    /// Number of passing fixture cases.
    pub passed_count: usize,
    /// Number of failing fixture cases.
    pub failed_count: usize,
    /// Per-fixture results.
    pub cases: Vec<ProfileTestCaseReport>,
}

impl ProfileTestReport {
    /// Convert this v1 profile test report into the explicit v2 evidence
    /// contract shape.
    ///
    /// This preserves the default serialized form of [`ProfileTestReport`].
    /// Producers opt into v2 when they are ready to emit embedded provenance.
    #[must_use]
    pub fn to_v2(
        &self,
        tool_name: impl Into<String>,
        tool_version: impl Into<String>,
    ) -> ProfileTestReportV2 {
        ProfileTestReportV2 {
            schema_version: "2".to_string(),
            tool_name: tool_name.into(),
            tool_version: tool_version.into(),
            report: self.clone(),
        }
    }
}

/// Profile test report v2 with embedded evidence provenance.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileTestReportV2 {
    /// Evidence artifact schema version.
    pub schema_version: String,
    /// Producer surface that generated this profile test report.
    pub tool_name: String,
    /// Producer package version.
    pub tool_version: String,
    /// V1 profile test report fields.
    #[serde(flatten)]
    pub report: ProfileTestReport,
}

/// A single profile fixture test result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileTestCaseReport {
    /// Fixture name, usually relative to the fixture root.
    pub name: String,
    /// Fixture path label supplied by the producer.
    pub path: String,
    /// Expected fixture outcome.
    pub expectation: ProfileFixtureExpectation,
    /// Whether the fixture satisfied its expectation.
    pub passed: bool,
    /// Human-readable fixture result.
    pub message: String,
    /// Validation report generated for the fixture, when available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub validation_report: Option<super::validation::ValidationReport>,
    /// Expected report comparison result, when an expected report was supplied.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expected_report: Option<ExpectedReportComparison>,
}

/// Expected fixture outcome.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProfileFixtureExpectation {
    /// Fixture is expected to validate successfully.
    Valid,
    /// Fixture is expected to fail validation.
    Invalid,
}

impl ProfileFixtureExpectation {
    /// Return the lowercase expectation string used by text output.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Valid => "valid",
            Self::Invalid => "invalid",
        }
    }
}

/// Result of comparing a generated validation report to an expected report.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExpectedReportComparison {
    /// Expected report path label supplied by the producer.
    pub path: String,
    /// Whether the expected report matched.
    pub matched: bool,
    /// Optional mismatch detail.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub message: Option<String>,
}

enum ExpectedReportCandidate {
    File(PathBuf),
    Ambiguous(PathBuf),
}

/// A single profile lint finding.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileLintIssue {
    /// Stable lint code.
    pub code: String,
    /// Finding severity.
    pub severity: ProfileLintSeverity,
    /// Profile path or YAML location, when available.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /// Human-readable explanation.
    pub message: String,
}

impl ProfileLintIssue {
    fn error(code: &str, path: Option<String>, message: String) -> Self {
        Self {
            code: code.to_string(),
            severity: ProfileLintSeverity::Error,
            path,
            message,
        }
    }

    fn warning(code: &str, path: Option<String>, message: String) -> Self {
        Self {
            code: code.to_string(),
            severity: ProfileLintSeverity::Warning,
            path,
            message,
        }
    }
}

/// Profile lint finding severity.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProfileLintSeverity {
    /// Profile should not be used until fixed.
    Error,
    /// Profile loads, but contains surprising or ignored configuration.
    Warning,
}

impl ProfileLintSeverity {
    /// Return the lowercase severity string used by text output.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Error => "error",
            Self::Warning => "warning",
        }
    }
}

/// Run profile fixture tests from a fixture directory.
///
/// The fixture root follows the CLI layout: `valid/*.hl7` fixtures must
/// validate, `invalid/*.hl7` fixtures must fail validation, and optional
/// `expected/*.report.json` files are compared as JSON subsets against the
/// generated validation reports.
pub fn run_profile_fixture_tests(
    profile_path: impl AsRef<Path>,
    fixtures: impl AsRef<Path>,
    profile: &Profile,
) -> io::Result<ProfileTestReport> {
    let profile_path = profile_path.as_ref();
    let fixtures = fixtures.as_ref();
    let valid_root = fixtures.join("valid");
    let invalid_root = fixtures.join("invalid");
    let expected_root = fixtures.join("expected");
    let valid_files = collect_hl7_fixture_files(&valid_root)?;
    let invalid_files = collect_hl7_fixture_files(&invalid_root)?;
    let expected_reports =
        build_expected_report_lookup(fixtures, &expected_root, [&valid_files, &invalid_files]);

    let mut cases = Vec::new();
    cases.extend(run_profile_fixture_group(
        profile_path,
        fixtures,
        &valid_files,
        &expected_reports,
        ProfileFixtureExpectation::Valid,
        profile,
    ));
    cases.extend(run_profile_fixture_group(
        profile_path,
        fixtures,
        &invalid_files,
        &expected_reports,
        ProfileFixtureExpectation::Invalid,
        profile,
    ));

    if cases.is_empty() {
        return Err(io::Error::other(format!(
            "no .hl7 fixtures found under {}",
            fixtures.display()
        )));
    }

    let passed_count = cases.iter().filter(|case| case.passed).count();
    let case_count = cases.len();
    let failed_count = case_count.saturating_sub(passed_count);

    Ok(ProfileTestReport {
        profile: profile_path.to_string_lossy().to_string(),
        fixtures: fixtures.to_string_lossy().to_string(),
        valid: failed_count == 0,
        case_count,
        passed_count,
        failed_count,
        cases,
    })
}

fn run_profile_fixture_group(
    profile_path: &Path,
    fixture_root: &Path,
    files: &[PathBuf],
    expected_reports: &BTreeMap<PathBuf, ExpectedReportCandidate>,
    expectation: ProfileFixtureExpectation,
    profile: &Profile,
) -> Vec<ProfileTestCaseReport> {
    files
        .iter()
        .map(|path| {
            run_profile_fixture_case(
                profile_path,
                fixture_root,
                expected_reports,
                path,
                expectation,
                profile,
            )
        })
        .collect()
}

fn run_profile_fixture_case(
    profile_path: &Path,
    fixture_root: &Path,
    expected_reports: &BTreeMap<PathBuf, ExpectedReportCandidate>,
    path: &Path,
    expectation: ProfileFixtureExpectation,
    profile: &Profile,
) -> ProfileTestCaseReport {
    let name = relative_display_path(fixture_root, path);

    let contents = match fs::read(path) {
        Ok(contents) => contents,
        Err(err) => {
            return ProfileTestCaseReport {
                name,
                path: path.to_string_lossy().to_string(),
                expectation,
                passed: false,
                message: format!("fixture could not be read: {err}"),
                validation_report: None,
                expected_report: None,
            };
        }
    };

    let message = match parse(&contents) {
        Ok(message) => message,
        Err(err) => {
            return ProfileTestCaseReport {
                name,
                path: path.to_string_lossy().to_string(),
                expectation,
                passed: false,
                message: format!("fixture did not parse as HL7: {err}"),
                validation_report: None,
                expected_report: None,
            };
        }
    };

    let issues = validate(&message, profile);
    let validation_report = super::validation::ValidationReport::from_issues(
        &message,
        Some(profile_path.to_string_lossy().to_string()),
        issues,
    );
    let expected_valid = expectation == ProfileFixtureExpectation::Valid;
    let mut passed = validation_report.valid == expected_valid;
    let mut message = if passed {
        format!(
            "expected {} and report was {}",
            expectation.as_str(),
            if validation_report.valid {
                "valid"
            } else {
                "invalid"
            }
        )
    } else {
        format!(
            "expected {} but report was {}",
            expectation.as_str(),
            if validation_report.valid {
                "valid"
            } else {
                "invalid"
            }
        )
    };

    let expected_report = expected_reports
        .get(path)
        .map(|candidate| compare_expected_report_candidate(candidate, &validation_report));
    if let Some(comparison) = &expected_report {
        if comparison.matched {
            message.push_str("; expected report matched");
        } else {
            passed = false;
            let detail = comparison
                .message
                .as_deref()
                .unwrap_or("expected report did not match");
            message.push_str(&format!("; {detail}"));
        }
    }

    ProfileTestCaseReport {
        name,
        path: path.to_string_lossy().to_string(),
        expectation,
        passed,
        message,
        validation_report: Some(validation_report),
        expected_report,
    }
}

fn collect_hl7_fixture_files(root: &Path) -> io::Result<Vec<PathBuf>> {
    let mut files = Vec::new();
    if !root.exists() {
        return Ok(files);
    }

    collect_hl7_fixture_files_recursive(root, &mut files)?;
    files.sort_by(|left, right| compare_paths_case_stable(left, right));
    Ok(files)
}

fn compare_paths_case_stable(left: &Path, right: &Path) -> Ordering {
    let left_display = left.to_string_lossy();
    let right_display = right.to_string_lossy();
    left_display
        .to_lowercase()
        .cmp(&right_display.to_lowercase())
        .then_with(|| left_display.cmp(&right_display))
}

fn collect_hl7_fixture_files_recursive(root: &Path, files: &mut Vec<PathBuf>) -> io::Result<()> {
    for entry in fs::read_dir(root)? {
        let entry = entry?;
        let path = entry.path();
        let file_type = entry.file_type()?;
        if file_type.is_dir() {
            collect_hl7_fixture_files_recursive(&path, files)?;
        } else if file_type.is_file()
            && path
                .extension()
                .and_then(|extension| extension.to_str())
                .is_some_and(|extension| extension.eq_ignore_ascii_case("hl7"))
        {
            files.push(path);
        }
    }
    Ok(())
}

fn build_expected_report_lookup<'a>(
    fixture_root: &Path,
    expected_root: &Path,
    fixture_groups: impl IntoIterator<Item = &'a Vec<PathBuf>>,
) -> BTreeMap<PathBuf, ExpectedReportCandidate> {
    let fixtures: Vec<&PathBuf> = fixture_groups
        .into_iter()
        .flat_map(|group| group.iter())
        .collect();
    let mut fallback_counts = BTreeMap::new();
    for fixture_path in &fixtures {
        let fallback = fallback_expected_report_path(expected_root, fixture_path);
        if fallback.exists() {
            let count = fallback_counts.entry(fallback).or_insert(0_usize);
            *count = count.saturating_add(1);
        }
    }

    let mut lookup = BTreeMap::new();
    for fixture_path in fixtures {
        let primary = primary_expected_report_path(expected_root, fixture_root, fixture_path);
        if primary.exists() {
            lookup.insert(fixture_path.clone(), ExpectedReportCandidate::File(primary));
            continue;
        }

        let fallback = fallback_expected_report_path(expected_root, fixture_path);
        match fallback_counts.get(&fallback).copied() {
            Some(1) => {
                lookup.insert(
                    fixture_path.clone(),
                    ExpectedReportCandidate::File(fallback),
                );
            }
            Some(_) => {
                lookup.insert(
                    fixture_path.clone(),
                    ExpectedReportCandidate::Ambiguous(fallback),
                );
            }
            None => {}
        }
    }
    lookup
}

fn primary_expected_report_path(
    expected_root: &Path,
    fixture_root: &Path,
    fixture_path: &Path,
) -> PathBuf {
    let relative = fixture_path
        .strip_prefix(fixture_root)
        .unwrap_or(fixture_path);
    let mut path = expected_root.join(relative);
    path.set_extension("report.json");
    path
}

fn fallback_expected_report_path(expected_root: &Path, fixture_path: &Path) -> PathBuf {
    let stem = fixture_path
        .file_stem()
        .and_then(|stem| stem.to_str())
        .unwrap_or("fixture");
    expected_root.join(format!("{stem}.report.json"))
}

fn compare_expected_report_candidate(
    candidate: &ExpectedReportCandidate,
    actual_report: &super::validation::ValidationReport,
) -> ExpectedReportComparison {
    match candidate {
        ExpectedReportCandidate::File(path) => {
            compare_expected_report(path, actual_report).unwrap_or_else(|| {
                ExpectedReportComparison {
                    path: path.to_string_lossy().to_string(),
                    matched: false,
                    message: Some(
                        "expected report path was registered but no longer exists".to_string(),
                    ),
                }
            })
        }
        ExpectedReportCandidate::Ambiguous(path) => ExpectedReportComparison {
            path: path.to_string_lossy().to_string(),
            matched: false,
            message: Some(
                "ambiguous basename expected report; use expected/valid/... or expected/invalid/..."
                    .to_string(),
            ),
        },
    }
}

fn compare_expected_report(
    expected_path: &Path,
    actual_report: &super::validation::ValidationReport,
) -> Option<ExpectedReportComparison> {
    if !expected_path.exists() {
        return None;
    }

    let path = expected_path.to_string_lossy().to_string();
    let expected = match fs::read_to_string(expected_path)
        .map_err(|err| format!("expected report could not be read: {err}"))
        .and_then(|contents| {
            serde_json::from_str::<serde_json::Value>(&contents)
                .map_err(|err| format!("expected report is not valid JSON: {err}"))
        }) {
        Ok(expected) => expected,
        Err(message) => {
            return Some(ExpectedReportComparison {
                path,
                matched: false,
                message: Some(message),
            });
        }
    };

    let actual = match serde_json::to_value(actual_report) {
        Ok(actual) => actual,
        Err(err) => {
            return Some(ExpectedReportComparison {
                path,
                matched: false,
                message: Some(format!("actual report could not be serialized: {err}")),
            });
        }
    };

    match json_subset_matches(&expected, &actual, "$") {
        Ok(()) => Some(ExpectedReportComparison {
            path,
            matched: true,
            message: None,
        }),
        Err(message) => Some(ExpectedReportComparison {
            path,
            matched: false,
            message: Some(message),
        }),
    }
}

fn json_subset_matches(
    expected: &serde_json::Value,
    actual: &serde_json::Value,
    path: &str,
) -> Result<(), String> {
    match (expected, actual) {
        (serde_json::Value::Object(expected), serde_json::Value::Object(actual)) => {
            for (key, expected_value) in expected {
                let actual_value = actual
                    .get(key)
                    .ok_or_else(|| format!("{path}.{key} was missing from actual report"))?;
                json_subset_matches(expected_value, actual_value, &format!("{path}.{key}"))?;
            }
            Ok(())
        }
        (serde_json::Value::Array(expected), serde_json::Value::Array(actual)) => {
            for (index, expected_value) in expected.iter().enumerate() {
                let matched = actual.iter().any(|actual_value| {
                    json_subset_matches(expected_value, actual_value, &format!("{path}[{index}]"))
                        .is_ok()
                });
                if !matched {
                    return Err(format!(
                        "{path}[{index}] did not match any actual report item"
                    ));
                }
            }
            Ok(())
        }
        _ if expected == actual => Ok(()),
        _ => Err(format!(
            "{path} expected {} but actual report had {}",
            expected, actual
        )),
    }
}

fn relative_display_path(root: &Path, path: &Path) -> String {
    path.strip_prefix(root)
        .unwrap_or(path)
        .components()
        .map(|component| component.as_os_str().to_string_lossy())
        .collect::<Vec<_>>()
        .join("/")
}

/// Lint a profile YAML document.
///
/// This function is intentionally stricter than `load_profile_checked`: it
/// catches ignored keys, malformed paths, invalid regex patterns, unsupported
/// rule strings, and dangling value-set/table references.
pub fn lint_profile_yaml(yaml: &str) -> ProfileLintReport {
    let root = match serde_yaml::from_str::<serde_yaml::Value>(yaml) {
        Ok(root) => root,
        Err(err) => {
            return ProfileLintReport::from_issues(vec![ProfileLintIssue::error(
                "yaml_parse_error",
                None,
                profile_lint_yaml_error_message("profile YAML could not be parsed", err.location()),
            )]);
        }
    };

    let mut issues = Vec::new();
    lint_unknown_profile_keys(&root, &mut issues);

    let profile = match serde_yaml::from_value::<Profile>(root) {
        Ok(profile) => profile,
        Err(err) => {
            issues.push(ProfileLintIssue::error(
                "profile_load_error",
                None,
                profile_lint_yaml_error_message(
                    "profile YAML could not be loaded as a profile",
                    err.location(),
                ),
            ));
            return ProfileLintReport::from_issues(issues);
        }
    };

    lint_profile(&profile, &mut issues);
    ProfileLintReport::from_issues(issues)
}

fn profile_lint_yaml_error_message(
    summary: &'static str,
    location: Option<serde_yaml::Location>,
) -> String {
    match location {
        Some(location) => format!(
            "{summary} at line {}, column {}",
            location.line(),
            location.column()
        ),
        None => summary.to_string(),
    }
}

/// Build a structured explanation report for a loaded profile.
///
/// `profile_name` is recorded in the report as producer-supplied identity,
/// typically a relative path or display name. The source YAML is used only for
/// the profile hash; raw profile text is not embedded in the report.
#[must_use]
pub fn explain_profile(
    profile_name: impl Into<String>,
    profile_yaml: &str,
    profile: &Profile,
    lint_report: &ProfileLintReport,
) -> ProfileExplainReport {
    let required_fields: Vec<ProfileExplainRequiredField> = profile
        .constraints
        .iter()
        .filter(|constraint| constraint.required)
        .map(|constraint| ProfileExplainRequiredField {
            path: constraint.path.clone(),
            conditional: constraint.when.is_some(),
        })
        .collect();

    let table_code_counts: HashMap<&str, usize> = profile
        .hl7_tables
        .iter()
        .map(|table| (table.id.as_str(), table.codes.len()))
        .collect();

    let datatype_rules = profile
        .datatypes
        .iter()
        .map(|datatype| ProfileExplainDatatypeRule {
            path: datatype.path.clone(),
            datatype: datatype.r#type.clone(),
            kind: "simple".to_string(),
            pattern: None,
            min_length: None,
            max_length: None,
            format: None,
            checksum: None,
        })
        .chain(
            profile
                .advanced_datatypes
                .iter()
                .map(|datatype| ProfileExplainDatatypeRule {
                    path: datatype.path.clone(),
                    datatype: datatype.r#type.clone(),
                    kind: "advanced".to_string(),
                    pattern: datatype.pattern.clone(),
                    min_length: datatype.min_length,
                    max_length: datatype.max_length,
                    format: datatype.format.clone(),
                    checksum: datatype.checksum.clone(),
                }),
        )
        .collect();

    ProfileExplainReport {
        profile: profile_name.into(),
        profile_sha256: compute_profile_sha256(profile_yaml),
        message_structure: profile.message_structure.clone(),
        version: profile.version.clone(),
        message_type: profile.message_type.clone(),
        parent: profile.parent.clone(),
        summary: ProfileExplainSummary {
            segment_count: profile.segments.len(),
            required_field_count: required_fields.len(),
            field_constraint_count: profile.constraints.len(),
            length_rule_count: profile.lengths.len(),
            datatype_rule_count: profile.datatypes.len(),
            advanced_datatype_rule_count: profile.advanced_datatypes.len(),
            value_set_count: profile.valuesets.len(),
            cross_field_rule_count: profile.cross_field_rules.len(),
            temporal_rule_count: profile.temporal_rules.len(),
            contextual_rule_count: profile.contextual_rules.len(),
            custom_rule_count: profile.custom_rules.len(),
            hl7_table_count: profile.hl7_tables.len(),
        },
        segments: profile
            .segments
            .iter()
            .map(|segment| ProfileExplainSegment {
                id: segment.id.clone(),
            })
            .collect(),
        required_fields,
        field_constraints: profile
            .constraints
            .iter()
            .map(|constraint| {
                let (component_min, component_max) = constraint
                    .components
                    .as_ref()
                    .map(|components| (components.min, components.max))
                    .unwrap_or((None, None));
                let allowed_values = constraint.r#in.clone().unwrap_or_default();
                ProfileExplainConstraint {
                    path: constraint.path.clone(),
                    required: constraint.required,
                    conditional: constraint.when.is_some(),
                    component_min,
                    component_max,
                    allowed_value_count: allowed_values.len(),
                    allowed_values,
                    pattern: constraint.pattern.clone(),
                }
            })
            .collect(),
        length_rules: profile
            .lengths
            .iter()
            .map(|length| ProfileExplainLengthRule {
                path: length.path.clone(),
                max: length.max,
                policy: length.policy.clone(),
            })
            .collect(),
        datatype_rules,
        value_sets: profile
            .valuesets
            .iter()
            .map(|valueset| {
                let table_code_count = table_code_counts
                    .get(valueset.name.as_str())
                    .copied()
                    .unwrap_or(0);
                let source = if !valueset.codes.is_empty() {
                    "inline"
                } else if table_code_count > 0 {
                    "hl7_table"
                } else {
                    "empty"
                };
                ProfileExplainValueSet {
                    name: valueset.name.clone(),
                    path: valueset.path.clone(),
                    source: source.to_string(),
                    inline_code_count: valueset.codes.len(),
                    table_code_count,
                }
            })
            .collect(),
        rules: ProfileExplainRules {
            cross_field: profile
                .cross_field_rules
                .iter()
                .map(|rule| ProfileExplainRule {
                    id: rule.id.clone(),
                    description: rule.description.clone(),
                })
                .collect(),
            temporal: profile
                .temporal_rules
                .iter()
                .map(|rule| ProfileExplainRule {
                    id: rule.id.clone(),
                    description: rule.description.clone(),
                })
                .collect(),
            contextual: profile
                .contextual_rules
                .iter()
                .map(|rule| ProfileExplainRule {
                    id: rule.id.clone(),
                    description: rule.description.clone(),
                })
                .collect(),
            custom: profile
                .custom_rules
                .iter()
                .map(|rule| ProfileExplainRule {
                    id: rule.id.clone(),
                    description: rule.description.clone(),
                })
                .collect(),
        },
        hl7_tables: profile
            .hl7_tables
            .iter()
            .map(|table| ProfileExplainTable {
                id: table.id.clone(),
                name: table.name.clone(),
                version: table.version.clone(),
                code_count: table.codes.len(),
            })
            .collect(),
        table_precedence: profile.table_precedence.clone(),
        expression_guardrails: ProfileExplainExpressionGuardrails {
            max_depth: profile.expression_guardrails.max_depth,
            max_length: profile.expression_guardrails.max_length,
            allow_custom_scripts: profile.expression_guardrails.allow_custom_scripts,
        },
        lint: ProfileExplainLintSummary {
            valid: lint_report.valid,
            error_count: lint_report.error_count,
            warning_count: lint_report.warning_count,
            issue_count: lint_report.issue_count,
            ignored_or_unsupported: lint_report
                .issues
                .iter()
                .filter(|issue| profile_lint_issue_is_ignored_or_unsupported(issue))
                .cloned()
                .collect(),
        },
    }
}

fn profile_lint_issue_is_ignored_or_unsupported(issue: &ProfileLintIssue) -> bool {
    issue.code.starts_with("unknown_")
        || issue.code.contains("unsupported")
        || issue.message.contains("ignored")
}

fn compute_profile_sha256(value: &str) -> String {
    let mut hasher = Sha256::new();
    hasher.update(value.as_bytes());
    format!("{:x}", hasher.finalize())
}

fn lint_unknown_profile_keys(root: &serde_yaml::Value, issues: &mut Vec<ProfileLintIssue>) {
    let Some(mapping) = root.as_mapping() else {
        return;
    };

    let known_keys = [
        "message_structure",
        "version",
        "message_type",
        "parent",
        "description",
        "segments",
        "constraints",
        "lengths",
        "valuesets",
        "datatypes",
        "advanced_datatypes",
        "cross_field_rules",
        "temporal_rules",
        "contextual_rules",
        "custom_rules",
        "hl7_tables",
        "table_precedence",
        "expression_guardrails",
    ];

    for key in mapping.keys().filter_map(serde_yaml::Value::as_str) {
        if !known_keys.contains(&key) {
            issues.push(ProfileLintIssue::warning(
                "unknown_top_level_key",
                Some(key.to_string()),
                format!("top-level key '{key}' is ignored by the profile loader"),
            ));
        }
    }
}

fn lint_profile(profile: &Profile, issues: &mut Vec<ProfileLintIssue>) {
    lint_profile_identity(profile, issues);
    lint_segments(profile, issues);
    lint_constraints(profile, issues);
    lint_lengths(profile, issues);
    lint_value_sets(profile, issues);
    lint_datatypes(profile, issues);
    lint_rules(profile, issues);
    lint_tables(profile, issues);
    lint_custom_rules(profile, issues);
}

fn lint_profile_identity(profile: &Profile, issues: &mut Vec<ProfileLintIssue>) {
    if profile.message_structure.trim().is_empty() {
        issues.push(ProfileLintIssue::error(
            "empty_message_structure",
            Some("message_structure".to_string()),
            "message_structure must not be empty".to_string(),
        ));
    }

    if profile.version.trim().is_empty() {
        issues.push(ProfileLintIssue::error(
            "empty_version",
            Some("version".to_string()),
            "version must not be empty".to_string(),
        ));
    }
}

fn lint_segments(profile: &Profile, issues: &mut Vec<ProfileLintIssue>) {
    let mut seen = HashSet::new();
    for (index, segment) in profile.segments.iter().enumerate() {
        let path = format!("segments[{index}].id");
        if segment.id.trim().is_empty() {
            issues.push(ProfileLintIssue::error(
                "empty_segment_id",
                Some(path),
                "segment id must not be empty".to_string(),
            ));
        } else if !seen.insert(segment.id.as_str()) {
            issues.push(ProfileLintIssue::warning(
                "duplicate_segment_id",
                Some(path),
                format!("segment '{}' is listed more than once", segment.id),
            ));
        }
    }
}

fn lint_constraints(profile: &Profile, issues: &mut Vec<ProfileLintIssue>) {
    for (index, constraint) in profile.constraints.iter().enumerate() {
        lint_hl7_path(
            &constraint.path,
            format!("constraints[{index}].path"),
            issues,
        );

        if let Some(components) = &constraint.components
            && let (Some(min), Some(max)) = (components.min, components.max)
            && min > max
        {
            issues.push(ProfileLintIssue::error(
                "component_min_exceeds_max",
                Some(format!("constraints[{index}].components")),
                format!("component minimum {min} exceeds maximum {max}"),
            ));
        }

        if let Some(pattern) = &constraint.pattern {
            lint_regex(
                pattern,
                format!("constraints[{index}].pattern"),
                "invalid_constraint_pattern",
                issues,
            );
        }

        if let Some(condition) = &constraint.when {
            lint_condition(condition, format!("constraints[{index}].when"), issues);
        }
    }
}

fn lint_condition(condition: &Condition, base_path: String, issues: &mut Vec<ProfileLintIssue>) {
    if let Some(eq_conditions) = &condition.eq {
        if eq_conditions.len() != 2 {
            issues.push(ProfileLintIssue::error(
                "invalid_condition_eq",
                Some(format!("{base_path}.eq")),
                "condition eq must contain exactly [field_path, expected_value]".to_string(),
            ));
        } else if let Some(field_path) = eq_conditions.first() {
            lint_hl7_path(field_path, format!("{base_path}.eq[0]"), issues);
        }
    }

    if let Some(nested_conditions) = &condition.any {
        for (index, nested) in nested_conditions.iter().enumerate() {
            lint_condition(nested, format!("{base_path}.any[{index}]"), issues);
        }
    }
}

fn lint_lengths(profile: &Profile, issues: &mut Vec<ProfileLintIssue>) {
    for (index, length) in profile.lengths.iter().enumerate() {
        lint_hl7_path(&length.path, format!("lengths[{index}].path"), issues);

        if let Some(policy) = &length.policy
            && policy != "no-truncate"
            && policy != "may-truncate"
        {
            issues.push(ProfileLintIssue::warning(
                "unknown_length_policy",
                Some(format!("lengths[{index}].policy")),
                format!("length policy '{policy}' is not recognized"),
            ));
        }
    }
}

fn lint_value_sets(profile: &Profile, issues: &mut Vec<ProfileLintIssue>) {
    let table_ids: HashSet<&str> = profile
        .hl7_tables
        .iter()
        .map(|table| table.id.as_str())
        .collect();
    let mut names = HashSet::new();

    for (index, valueset) in profile.valuesets.iter().enumerate() {
        lint_hl7_path(&valueset.path, format!("valuesets[{index}].path"), issues);

        if valueset.name.trim().is_empty() {
            issues.push(ProfileLintIssue::error(
                "empty_valueset_name",
                Some(format!("valuesets[{index}].name")),
                "value set name must not be empty".to_string(),
            ));
        } else if !names.insert(valueset.name.as_str()) {
            issues.push(ProfileLintIssue::warning(
                "duplicate_valueset_name",
                Some(format!("valuesets[{index}].name")),
                format!("value set '{}' is defined more than once", valueset.name),
            ));
        }

        if valueset.codes.is_empty() && !table_ids.contains(valueset.name.as_str()) {
            issues.push(ProfileLintIssue::warning(
                "empty_valueset_without_table",
                Some(format!("valuesets[{index}]")),
                format!(
                    "value set '{}' has no inline codes and does not reference an hl7_tables id",
                    valueset.name
                ),
            ));
        }
    }
}

fn lint_datatypes(profile: &Profile, issues: &mut Vec<ProfileLintIssue>) {
    for (index, datatype) in profile.datatypes.iter().enumerate() {
        lint_hl7_path(&datatype.path, format!("datatypes[{index}].path"), issues);
        if datatype.r#type.trim().is_empty() {
            issues.push(ProfileLintIssue::error(
                "empty_datatype",
                Some(format!("datatypes[{index}].type")),
                "datatype must not be empty".to_string(),
            ));
        }
    }

    for (index, datatype) in profile.advanced_datatypes.iter().enumerate() {
        lint_hl7_path(
            &datatype.path,
            format!("advanced_datatypes[{index}].path"),
            issues,
        );

        if datatype.r#type.trim().is_empty() {
            issues.push(ProfileLintIssue::error(
                "empty_advanced_datatype",
                Some(format!("advanced_datatypes[{index}].type")),
                "advanced datatype must not be empty".to_string(),
            ));
        }

        if let (Some(min), Some(max)) = (datatype.min_length, datatype.max_length)
            && min > max
        {
            issues.push(ProfileLintIssue::error(
                "datatype_min_length_exceeds_max",
                Some(format!("advanced_datatypes[{index}]")),
                format!("minimum length {min} exceeds maximum length {max}"),
            ));
        }

        if let Some(pattern) = &datatype.pattern {
            lint_regex(
                pattern,
                format!("advanced_datatypes[{index}].pattern"),
                "invalid_datatype_pattern",
                issues,
            );
        }

        if let Some(checksum) = &datatype.checksum
            && checksum != "luhn"
            && checksum != "mod10"
        {
            issues.push(ProfileLintIssue::warning(
                "unknown_checksum_algorithm",
                Some(format!("advanced_datatypes[{index}].checksum")),
                format!("checksum algorithm '{checksum}' is ignored by validation"),
            ));
        }
    }
}

fn lint_rules(profile: &Profile, issues: &mut Vec<ProfileLintIssue>) {
    let valueset_names: HashSet<&str> = profile
        .valuesets
        .iter()
        .map(|valueset| valueset.name.as_str())
        .collect();

    lint_cross_field_rules(profile, &valueset_names, issues);
    lint_temporal_rules(profile, issues);
    lint_contextual_rules(profile, &valueset_names, issues);
}

fn lint_cross_field_rules(
    profile: &Profile,
    valueset_names: &HashSet<&str>,
    issues: &mut Vec<ProfileLintIssue>,
) {
    let mut ids = HashSet::new();

    for (index, rule) in profile.cross_field_rules.iter().enumerate() {
        let base_path = format!("cross_field_rules[{index}]");
        lint_rule_id(rule.id.as_str(), &mut ids, &base_path, issues);

        if rule.validation_mode != "conditional" && rule.validation_mode != "assert" {
            issues.push(ProfileLintIssue::error(
                "unknown_cross_field_validation_mode",
                Some(format!("{base_path}.validation_mode")),
                format!(
                    "cross-field validation mode '{}' is not supported",
                    rule.validation_mode
                ),
            ));
        }

        for (condition_index, condition) in rule.conditions.iter().enumerate() {
            lint_rule_condition(
                condition,
                format!("{base_path}.conditions[{condition_index}]"),
                issues,
            );
        }

        for (action_index, action) in rule.actions.iter().enumerate() {
            lint_rule_action(
                action,
                format!("{base_path}.actions[{action_index}]"),
                valueset_names,
                issues,
            );
        }
    }
}

fn lint_temporal_rules(profile: &Profile, issues: &mut Vec<ProfileLintIssue>) {
    let mut ids = HashSet::new();

    for (index, rule) in profile.temporal_rules.iter().enumerate() {
        let base_path = format!("temporal_rules[{index}]");
        lint_rule_id(rule.id.as_str(), &mut ids, &base_path, issues);
        lint_hl7_path(&rule.before, format!("{base_path}.before"), issues);
        lint_hl7_path(&rule.after, format!("{base_path}.after"), issues);
    }
}

fn lint_contextual_rules(
    profile: &Profile,
    valueset_names: &HashSet<&str>,
    issues: &mut Vec<ProfileLintIssue>,
) {
    let mut ids = HashSet::new();

    for (index, rule) in profile.contextual_rules.iter().enumerate() {
        let base_path = format!("contextual_rules[{index}]");
        lint_rule_id(rule.id.as_str(), &mut ids, &base_path, issues);
        lint_hl7_path(
            &rule.context_field,
            format!("{base_path}.context_field"),
            issues,
        );
        lint_hl7_path(
            &rule.target_field,
            format!("{base_path}.target_field"),
            issues,
        );

        match rule.validation_type.as_str() {
            "require" | "prohibit" | "validate_datatype" | "validate_valueset" => {}
            validation_type => issues.push(ProfileLintIssue::error(
                "unknown_contextual_validation_type",
                Some(format!("{base_path}.validation_type")),
                format!("contextual validation type '{validation_type}' is not supported"),
            )),
        }

        if rule.validation_type == "validate_datatype" && !rule.parameters.contains_key("datatype")
        {
            issues.push(ProfileLintIssue::error(
                "missing_contextual_datatype_parameter",
                Some(format!("{base_path}.parameters.datatype")),
                "validate_datatype requires a datatype parameter".to_string(),
            ));
        }

        if rule.validation_type == "validate_valueset" {
            match rule.parameters.get("valueset") {
                Some(valueset) if valueset_names.contains(valueset.as_str()) => {}
                Some(valueset) => issues.push(ProfileLintIssue::error(
                    "unknown_contextual_valueset",
                    Some(format!("{base_path}.parameters.valueset")),
                    format!("contextual rule references undefined value set '{valueset}'"),
                )),
                None => issues.push(ProfileLintIssue::error(
                    "missing_contextual_valueset_parameter",
                    Some(format!("{base_path}.parameters.valueset")),
                    "validate_valueset requires a valueset parameter".to_string(),
                )),
            }
        }
    }
}

fn lint_rule_id(
    id: &str,
    seen: &mut HashSet<String>,
    base_path: &str,
    issues: &mut Vec<ProfileLintIssue>,
) {
    if id.trim().is_empty() {
        issues.push(ProfileLintIssue::error(
            "empty_rule_id",
            Some(format!("{base_path}.id")),
            "rule id must not be empty".to_string(),
        ));
    } else if !seen.insert(id.to_string()) {
        issues.push(ProfileLintIssue::warning(
            "duplicate_rule_id",
            Some(format!("{base_path}.id")),
            format!("rule id '{id}' is defined more than once in this rule family"),
        ));
    }
}

fn lint_rule_condition(
    condition: &RuleCondition,
    base_path: String,
    issues: &mut Vec<ProfileLintIssue>,
) {
    lint_hl7_path(&condition.field, format!("{base_path}.field"), issues);

    match condition.operator.as_str() {
        "eq" | "ne" | "contains" | "in" | "exists" | "not_exists" | "is_date" | "before"
        | "within_range" => {}
        "matches_regex" => match &condition.value {
            Some(pattern) => lint_regex(
                pattern,
                format!("{base_path}.value"),
                "invalid_rule_condition_regex",
                issues,
            ),
            None => issues.push(ProfileLintIssue::error(
                "missing_rule_condition_regex",
                Some(format!("{base_path}.value")),
                "matches_regex requires a regex pattern in value".to_string(),
            )),
        },
        operator => issues.push(ProfileLintIssue::error(
            "unknown_rule_condition_operator",
            Some(format!("{base_path}.operator")),
            format!("rule condition operator '{operator}' is not supported"),
        )),
    }

    if condition.operator == "within_range" && condition.values.as_ref().map_or(0, Vec::len) != 2 {
        issues.push(ProfileLintIssue::error(
            "invalid_within_range_values",
            Some(format!("{base_path}.values")),
            "within_range requires exactly two values".to_string(),
        ));
    }
}

fn lint_rule_action(
    action: &RuleAction,
    base_path: String,
    valueset_names: &HashSet<&str>,
    issues: &mut Vec<ProfileLintIssue>,
) {
    lint_hl7_path(&action.field, format!("{base_path}.field"), issues);

    match action.action.as_str() {
        "require" | "prohibit" | "validate" => {}
        action_type => issues.push(ProfileLintIssue::error(
            "unknown_rule_action",
            Some(format!("{base_path}.action")),
            format!("rule action '{action_type}' is not supported"),
        )),
    }

    if let Some(valueset) = &action.valueset
        && !valueset_names.contains(valueset.as_str())
    {
        issues.push(ProfileLintIssue::error(
            "unknown_action_valueset",
            Some(format!("{base_path}.valueset")),
            format!("rule action references undefined value set '{valueset}'"),
        ));
    }
}

fn lint_tables(profile: &Profile, issues: &mut Vec<ProfileLintIssue>) {
    let mut ids = HashSet::new();
    let mut table_by_id: HashMap<&str, usize> = HashMap::new();

    for (index, table) in profile.hl7_tables.iter().enumerate() {
        if table.id.trim().is_empty() {
            issues.push(ProfileLintIssue::error(
                "empty_table_id",
                Some(format!("hl7_tables[{index}].id")),
                "HL7 table id must not be empty".to_string(),
            ));
        } else {
            table_by_id.insert(table.id.as_str(), index);
            if !ids.insert(table.id.as_str()) {
                issues.push(ProfileLintIssue::warning(
                    "duplicate_table_id",
                    Some(format!("hl7_tables[{index}].id")),
                    format!("HL7 table '{}' is defined more than once", table.id),
                ));
            }
        }

        if table.name.trim().is_empty() {
            issues.push(ProfileLintIssue::warning(
                "empty_table_name",
                Some(format!("hl7_tables[{index}].name")),
                format!("HL7 table '{}' has an empty name", table.id),
            ));
        }

        if table.version.trim().is_empty() {
            issues.push(ProfileLintIssue::warning(
                "empty_table_version",
                Some(format!("hl7_tables[{index}].version")),
                format!("HL7 table '{}' has an empty version", table.id),
            ));
        }
    }

    for (index, table_id) in profile.table_precedence.iter().enumerate() {
        if !table_by_id.contains_key(table_id.as_str()) {
            issues.push(ProfileLintIssue::error(
                "unknown_table_precedence_entry",
                Some(format!("table_precedence[{index}]")),
                format!("table precedence references undefined HL7 table '{table_id}'"),
            ));
        }
    }
}

fn lint_custom_rules(profile: &Profile, issues: &mut Vec<ProfileLintIssue>) {
    let mut ids = HashSet::new();

    for (index, rule) in profile.custom_rules.iter().enumerate() {
        let base_path = format!("custom_rules[{index}]");
        lint_rule_id(rule.id.as_str(), &mut ids, &base_path, issues);

        if rule.script.trim().is_empty() {
            issues.push(ProfileLintIssue::error(
                "empty_custom_rule_script",
                Some(format!("{base_path}.script")),
                format!("custom rule '{}' has an empty script", rule.id),
            ));
        }
    }

    if !profile.custom_rules.is_empty() && !profile.expression_guardrails.allow_custom_scripts {
        issues.push(ProfileLintIssue::warning(
            "custom_rules_without_script_guardrail",
            Some("expression_guardrails.allow_custom_scripts".to_string()),
            "custom_rules are present but expression_guardrails.allow_custom_scripts is false"
                .to_string(),
        ));
    }
}

fn lint_hl7_path(path: &str, location: String, issues: &mut Vec<ProfileLintIssue>) {
    if let Err(err) = crate::query::path::parse_path(path) {
        issues.push(ProfileLintIssue::error(
            "invalid_hl7_path",
            Some(location),
            format!("'{path}' is not a valid HL7 field path: {err}"),
        ));
    }
}

fn lint_regex(pattern: &str, location: String, code: &str, issues: &mut Vec<ProfileLintIssue>) {
    if let Err(err) = Regex::new(pattern) {
        issues.push(ProfileLintIssue::error(
            code,
            Some(location),
            format!("regex '{pattern}' failed to compile: {err}"),
        ));
    }
}

/// Load profile from YAML
pub fn load_profile(yaml: &str) -> Result<Profile, ProfileLoadError> {
    serde_yaml::from_str(yaml).map_err(ProfileLoadError::from)
}

/// Load profile from YAML with specific error types.
///
/// This is the preferred function for loading profiles as it provides
/// detailed error information specific to profile loading issues.
///
/// # Arguments
///
/// * `yaml` - The YAML string containing the profile definition
///
/// # Returns
///
/// The parsed Profile, or a ProfileLoadError if parsing fails
///
/// # Example
///
/// ```ignore
/// use hl7v2::conformance::profile::{load_profile_checked, ProfileLoadError};
///
/// let yaml = r#"
/// message_structure: ADT_A01
/// version: "2.5.1"
/// segments:
///   - id: MSH
/// "#;
///
/// let profile = load_profile_checked(yaml)?;
/// assert_eq!(profile.message_structure, "ADT_A01");
/// ```
pub fn load_profile_checked(yaml: &str) -> Result<Profile, ProfileLoadError> {
    serde_yaml::from_str(yaml).map_err(ProfileLoadError::from)
}

/// Load profile from a file path with specific error types.
///
/// # Arguments
///
/// * `path` - The path to the YAML file containing the profile definition
///
/// # Returns
///
/// The parsed Profile, or a ProfileLoadError if loading or parsing fails
///
/// # Example
///
/// ```ignore
/// use hl7v2::conformance::profile::load_profile_from_file;
///
/// let profile = load_profile_from_file("profiles/adt_a01.yaml")?;
/// ```
pub async fn load_profile_from_file(path: &str) -> Result<Profile, ProfileLoadError> {
    let content = tokio::fs::read_to_string(path).await?;
    load_profile_checked(&content)
}

/// Load profile with inheritance resolution
///
/// This function loads a profile and recursively resolves any parent profiles,
/// merging their constraints and rules into a single profile.
///
/// # Arguments
///
/// * `yaml` - The YAML string for the profile
/// * `profile_loader` - A function that can load a parent profile by name
///
/// # Returns
///
/// A fully resolved profile with all inherited constraints merged
pub fn load_profile_with_inheritance<F>(
    yaml: &str,
    profile_loader: F,
) -> Result<Profile, ProfileLoadError>
where
    F: Fn(&str) -> Result<Profile, ProfileLoadError>,
{
    let profile = load_profile_checked(yaml)?;

    // If there's a parent, recursively load and merge it
    if let Some(parent_name) = &profile.parent {
        let parent_profile = load_profile_with_inheritance_recursive(parent_name, &profile_loader)?;
        return Ok(merge_profiles(parent_profile, profile));
    }

    Ok(profile)
}

/// Recursively load parent profiles
fn load_profile_with_inheritance_recursive<F>(
    parent_name: &str,
    profile_loader: &F,
) -> Result<Profile, ProfileLoadError>
where
    F: Fn(&str) -> Result<Profile, ProfileLoadError>,
{
    let parent_profile = profile_loader(parent_name)?;

    // If the parent also has a parent, recursively load and merge it
    if let Some(grandparent_name) = &parent_profile.parent {
        let grandparent_profile =
            load_profile_with_inheritance_recursive(grandparent_name, profile_loader)?;
        return Ok(merge_profiles(grandparent_profile, parent_profile));
    }

    Ok(parent_profile)
}

/// Merge two profiles, with the child profile taking precedence
fn merge_profiles(parent: Profile, child: Profile) -> Profile {
    Profile {
        message_structure: child.message_structure,
        version: child.version,
        message_type: child.message_type.or(parent.message_type),
        parent: child.parent, // Keep child's parent reference
        segments: merge_segment_specs(parent.segments, child.segments),
        constraints: merge_constraints(parent.constraints, child.constraints),
        lengths: merge_length_constraints(parent.lengths, child.lengths),
        valuesets: merge_valuesets(parent.valuesets, child.valuesets),
        datatypes: merge_datatype_constraints(parent.datatypes, child.datatypes),
        advanced_datatypes: merge_advanced_datatype_constraints(
            parent.advanced_datatypes,
            child.advanced_datatypes,
        ),
        cross_field_rules: merge_cross_field_rules(
            parent.cross_field_rules,
            child.cross_field_rules,
        ),
        temporal_rules: merge_temporal_rules(parent.temporal_rules, child.temporal_rules),
        contextual_rules: merge_contextual_rules(parent.contextual_rules, child.contextual_rules),
        custom_rules: merge_custom_rules(parent.custom_rules, child.custom_rules),
        hl7_tables: merge_hl7_tables(parent.hl7_tables, child.hl7_tables),
        table_precedence: if child.table_precedence.is_empty() {
            parent.table_precedence
        } else {
            child.table_precedence
        },
        expression_guardrails: if child.expression_guardrails == ExpressionGuardrails::default() {
            parent.expression_guardrails
        } else {
            child.expression_guardrails
        },
    }
}

/// Merge segment specifications, removing duplicates by ID
fn merge_segment_specs(parent: Vec<SegmentSpec>, child: Vec<SegmentSpec>) -> Vec<SegmentSpec> {
    let mut result: Vec<SegmentSpec> = parent;

    // Add child segments that don't already exist in parent
    for child_segment in child {
        if !result.iter().any(|s| s.id == child_segment.id) {
            result.push(child_segment);
        }
    }

    result
}

/// Merge constraints, with child constraints overriding parent constraints on same path
fn merge_constraints(parent: Vec<Constraint>, child: Vec<Constraint>) -> Vec<Constraint> {
    let mut result: Vec<Constraint> = parent;

    // Add child constraints, replacing any with the same path
    for child_constraint in child {
        if let Some(pos) = result.iter().position(|c| c.path == child_constraint.path) {
            result[pos] = child_constraint;
        } else {
            result.push(child_constraint);
        }
    }

    result
}

/// Merge length constraints, with child constraints overriding parent constraints on same path
fn merge_length_constraints(
    parent: Vec<LengthConstraint>,
    child: Vec<LengthConstraint>,
) -> Vec<LengthConstraint> {
    let mut result: Vec<LengthConstraint> = parent;

    // Add child constraints, replacing any with the same path
    for child_constraint in child {
        if let Some(pos) = result.iter().position(|c| c.path == child_constraint.path) {
            result[pos] = child_constraint;
        } else {
            result.push(child_constraint);
        }
    }

    result
}

/// Merge value sets, with child value sets overriding parent value sets on same path
fn merge_valuesets(parent: Vec<ValueSet>, child: Vec<ValueSet>) -> Vec<ValueSet> {
    let mut result: Vec<ValueSet> = parent;

    // Add child value sets, replacing any with the same path
    for child_valueset in child {
        if let Some(pos) = result.iter().position(|v| v.path == child_valueset.path) {
            result[pos] = child_valueset;
        } else {
            result.push(child_valueset);
        }
    }

    result
}

/// Merge data type constraints, with child constraints overriding parent constraints on same path
fn merge_datatype_constraints(
    parent: Vec<DataTypeConstraint>,
    child: Vec<DataTypeConstraint>,
) -> Vec<DataTypeConstraint> {
    let mut result: Vec<DataTypeConstraint> = parent;

    // Add child constraints, replacing any with the same path
    for child_constraint in child {
        if let Some(pos) = result.iter().position(|d| d.path == child_constraint.path) {
            result[pos] = child_constraint;
        } else {
            result.push(child_constraint);
        }
    }

    result
}

/// Merge advanced data type constraints, with child constraints overriding parent constraints on same path
fn merge_advanced_datatype_constraints(
    parent: Vec<AdvancedDataTypeConstraint>,
    child: Vec<AdvancedDataTypeConstraint>,
) -> Vec<AdvancedDataTypeConstraint> {
    let mut result: Vec<AdvancedDataTypeConstraint> = parent;

    // Add child constraints, replacing any with the same path
    for child_constraint in child {
        if let Some(pos) = result.iter().position(|d| d.path == child_constraint.path) {
            result[pos] = child_constraint;
        } else {
            result.push(child_constraint);
        }
    }

    result
}

/// Merge cross-field rules, with child rules overriding parent rules with same ID
fn merge_cross_field_rules(
    parent: Vec<CrossFieldRule>,
    child: Vec<CrossFieldRule>,
) -> Vec<CrossFieldRule> {
    let mut result: Vec<CrossFieldRule> = parent;

    // Add child rules, replacing any with the same ID
    for child_rule in child {
        if let Some(pos) = result.iter().position(|r| r.id == child_rule.id) {
            result[pos] = child_rule;
        } else {
            result.push(child_rule);
        }
    }

    result
}

/// Merge temporal rules, with child rules overriding parent rules with same ID
fn merge_temporal_rules(parent: Vec<TemporalRule>, child: Vec<TemporalRule>) -> Vec<TemporalRule> {
    let mut result: Vec<TemporalRule> = parent;

    // Add child rules, replacing any with the same ID
    for child_rule in child {
        if let Some(pos) = result.iter().position(|r| r.id == child_rule.id) {
            result[pos] = child_rule;
        } else {
            result.push(child_rule);
        }
    }

    result
}

/// Merge contextual rules, with child rules overriding parent rules with same ID
fn merge_contextual_rules(
    parent: Vec<ContextualRule>,
    child: Vec<ContextualRule>,
) -> Vec<ContextualRule> {
    let mut result: Vec<ContextualRule> = parent;

    // Add child rules, replacing any with the same ID
    for child_rule in child {
        if let Some(pos) = result.iter().position(|r| r.id == child_rule.id) {
            result[pos] = child_rule;
        } else {
            result.push(child_rule);
        }
    }

    result
}

/// Merge custom rules, with child rules overriding parent rules with same ID
fn merge_custom_rules(parent: Vec<CustomRule>, child: Vec<CustomRule>) -> Vec<CustomRule> {
    let mut result: Vec<CustomRule> = parent;

    // Add child rules, replacing any with the same ID
    for child_rule in child {
        if let Some(pos) = result.iter().position(|r| r.id == child_rule.id) {
            result[pos] = child_rule;
        } else {
            result.push(child_rule);
        }
    }

    result
}

/// Merge HL7 tables, with child tables overriding parent tables with same ID
fn merge_hl7_tables(parent: Vec<HL7Table>, child: Vec<HL7Table>) -> Vec<HL7Table> {
    let mut result: Vec<HL7Table> = parent;

    // Add child tables, replacing any with the same ID
    for child_table in child {
        if let Some(pos) = result.iter().position(|t| t.id == child_table.id) {
            result[pos] = child_table;
        } else {
            result.push(child_table);
        }
    }

    result
}

/// Validate message against profile
pub fn validate(msg: &Message, profile: &Profile) -> Vec<Issue> {
    let mut issues = Vec::new();

    // Validate constraints (including conditional ones)
    for constraint in &profile.constraints {
        if should_validate_constraint(msg, constraint) {
            if constraint.required {
                if let Some(path) = &constraint.path.strip_prefix("MSH.") {
                    // Special handling for MSH segment
                    validate_msh_field_required(msg, path, &mut issues);
                } else {
                    validate_field_required(msg, &constraint.path, &mut issues);
                }
            }

            // Validate 'in' constraints against value sets
            if let Some(allowed_values) = &constraint.r#in {
                validate_field_in_constraint(msg, &constraint.path, allowed_values, &mut issues);
            }
        }
    }

    // Validate value sets
    for valueset in &profile.valuesets {
        validate_value_set(msg, valueset, &mut issues);
    }

    // Validate data types
    for datatype in &profile.datatypes {
        validate_data_type_constraint(msg, datatype, &mut issues);
    }

    // Validate advanced data types
    for datatype in &profile.advanced_datatypes {
        validate_advanced_data_type(msg, datatype, &mut issues);
    }

    // Validate length constraints
    for length in &profile.lengths {
        validate_length_constraint(msg, length, &mut issues);
    }

    // Validate HL7 tables (with precedence support if configured)
    if !profile.hl7_tables.is_empty() || !profile.valuesets.is_empty() {
        validate_hl7_tables_with_precedence(msg, profile, &mut issues);
    }

    // Validate cross-field rules
    for rule in &profile.cross_field_rules {
        validate_cross_field_rule(msg, rule, profile, &mut issues);
    }

    // Validate temporal rules
    for rule in &profile.temporal_rules {
        validate_temporal_rule(msg, rule, &mut issues);
    }

    // Validate contextual rules
    for rule in &profile.contextual_rules {
        validate_contextual_rule(msg, rule, profile, &mut issues);
    }

    // Validate custom rules
    for rule in &profile.custom_rules {
        validate_custom_rule(msg, rule, &mut issues);
    }

    issues
}

/// Validate that a required field is present
fn validate_field_required(msg: &Message, path: &str, issues: &mut Vec<Issue>) {
    // Use the query module to retrieve the value.
    if let Some(value) = crate::query::get(msg, path) {
        // If we get a value, check if it's empty
        if value.is_empty() {
            issues.push(Issue::error(
                "MISSING_REQUIRED_FIELD",
                Some(path.to_string()),
                format!("Required field {} is missing", path),
            ));
        }
    } else {
        // If we get None, the field is truly missing
        issues.push(Issue::error(
            "MISSING_REQUIRED_FIELD",
            Some(path.to_string()),
            format!("Required field {} is missing", path),
        ));
    }
}

/// Determine if a constraint should be validated based on its conditions
fn should_validate_constraint(msg: &Message, constraint: &Constraint) -> bool {
    // If there's no condition, always validate
    let condition = match &constraint.when {
        Some(cond) => cond,
        None => return true,
    };

    // Check if any condition is met
    check_condition(msg, condition)
}

/// Check if a condition is met
fn check_condition(msg: &Message, condition: &Condition) -> bool {
    // Check equality conditions
    if let Some(eq_conditions) = &condition.eq {
        if eq_conditions.len() == 2 {
            let field_path = &eq_conditions[0];
            let expected_value = &eq_conditions[1];

            if let Some(actual_value) = crate::query::get(msg, field_path) {
                return actual_value == expected_value;
            }
            return false;
        }
    }

    // Check any conditions (OR logic)
    if let Some(any_conditions) = &condition.any {
        for cond in any_conditions {
            if check_condition(msg, cond) {
                return true;
            }
        }
        return false;
    }

    // If no conditions match, don't validate
    false
}

/// Validate that a required MSH field is present
fn validate_msh_field_required(msg: &Message, path: &str, issues: &mut Vec<Issue>) {
    let full_path = format!("MSH.{}", path);
    // Use the query module to retrieve the value.
    if crate::query::get(msg, &full_path).is_none() {
        issues.push(Issue::error(
            "MISSING_REQUIRED_FIELD",
            Some(full_path),
            format!("Required MSH field {} is missing", path),
        ));
    }
}

/// Validate that a field value is in the allowed values
fn validate_field_in_constraint(
    msg: &Message,
    path: &str,
    allowed_values: &[String],
    issues: &mut Vec<Issue>,
) {
    if let Some(value) = crate::query::get(msg, path) {
        if !allowed_values.contains(&value.to_string()) {
            issues.push(Issue::error(
                "VALUE_NOT_IN_CONSTRAINT",
                Some(path.to_string()),
                format!(
                    "Value '{}' for {} is not in allowed constraint values: {:?}",
                    value, path, allowed_values
                ),
            ));
        }
    }
}

/// Validate that a field value is in the allowed value set
fn validate_value_set(msg: &Message, valueset: &ValueSet, issues: &mut Vec<Issue>) {
    // If codes is empty, this valueset references an HL7 table
    // Validation will happen in validate_hl7_tables_with_precedence instead
    if valueset.codes.is_empty() {
        return;
    }

    if let Some(value) = crate::query::get(msg, &valueset.path) {
        if !valueset.codes.contains(&value.to_string()) {
            issues.push(Issue::error(
                "VALUE_NOT_IN_SET",
                Some(valueset.path.clone()),
                format!(
                    "Value '{}' for {} is not in allowed set: {:?}",
                    value, valueset.path, valueset.codes
                ),
            ));
        }
    }
    // Note: We don't report an error if the field is missing but has a value set constraint
    // That would be handled by a separate presence constraint if needed
}

/// Validate that a field value matches the expected data type
fn validate_data_type_constraint(
    msg: &Message,
    datatype: &DataTypeConstraint,
    issues: &mut Vec<Issue>,
) {
    if let Some(value) = crate::query::get(msg, &datatype.path) {
        if !validate_data_type(value, &datatype.r#type) {
            issues.push(Issue::error(
                "INVALID_DATA_TYPE",
                Some(datatype.path.clone()),
                format!(
                    "Value '{}' for {} does not match expected data type {}",
                    value, datatype.path, datatype.r#type
                ),
            ));
        }
    }
    // Note: We don't report an error if the field is missing but has a data type constraint
    // That would be handled by a separate presence constraint if needed
}

/// Validate that a field value matches the expected advanced data type
fn validate_advanced_data_type(
    msg: &Message,
    datatype: &AdvancedDataTypeConstraint,
    issues: &mut Vec<Issue>,
) {
    if let Some(value) = crate::query::get(msg, &datatype.path) {
        // First check basic data type
        if !validate_data_type(value, &datatype.r#type) {
            issues.push(Issue::error(
                "INVALID_DATA_TYPE",
                Some(datatype.path.clone()),
                format!(
                    "Value '{}' for {} does not match expected data type {}",
                    value, datatype.path, datatype.r#type
                ),
            ));
            return;
        }

        // Check length constraints
        if let Some(min_length) = datatype.min_length {
            if value.len() < min_length {
                issues.push(Issue::error(
                    "VALUE_TOO_SHORT",
                    Some(datatype.path.clone()),
                    format!(
                        "Value '{}' for {} is shorter than minimum length of {} characters",
                        value, datatype.path, min_length
                    ),
                ));
            }
        }

        if let Some(max_length) = datatype.max_length {
            if value.len() > max_length {
                issues.push(Issue::error(
                    "VALUE_TOO_LONG",
                    Some(datatype.path.clone()),
                    format!(
                        "Value '{}' for {} exceeds maximum length of {} characters",
                        value, datatype.path, max_length
                    ),
                ));
            }
        }

        // Check regex pattern if specified
        if let Some(pattern) = &datatype.pattern {
            if let Ok(regex) = Regex::new(pattern) {
                if !regex.is_match(value) {
                    issues.push(Issue::error(
                        "PATTERN_MISMATCH",
                        Some(datatype.path.clone()),
                        format!(
                            "Value '{}' for {} does not match required pattern '{}'",
                            value, datatype.path, pattern
                        ),
                    ));
                }
            }
        }

        // Check format if specified
        if let Some(format) = &datatype.format {
            if !matches_format(value, format, &datatype.r#type) {
                issues.push(Issue::error(
                    "FORMAT_MISMATCH",
                    Some(datatype.path.clone()),
                    format!(
                        "Value '{}' for {} does not match required format '{}'",
                        value, datatype.path, format
                    ),
                ));
            }
        }

        // Check checksum if specified
        if let Some(checksum) = &datatype.checksum {
            if !validate_checksum(value, checksum) {
                issues.push(Issue::error(
                    "CHECKSUM_MISMATCH",
                    Some(datatype.path.clone()),
                    format!("Checksum validation failed for {}", datatype.path),
                ));
            }
        }
    }
}

/// Validate HL7 tables with precedence support
fn validate_hl7_tables_with_precedence(msg: &Message, profile: &Profile, issues: &mut Vec<Issue>) {
    // Create a mapping of value set names to HL7 tables
    let mut table_map: std::collections::HashMap<&str, &HL7Table> =
        std::collections::HashMap::new();
    for table in &profile.hl7_tables {
        table_map.insert(&table.id, table);
    }

    // Validate value sets with table precedence
    for valueset in &profile.valuesets {
        if let Some(table_id) = table_map.get(valueset.name.as_str()) {
            if let Some(value) = crate::query::get(msg, &valueset.path) {
                // Only validate if the field is not empty
                if !value.is_empty() {
                    // Check if the value exists in the table
                    let is_valid = table_id.codes.iter().any(|entry| {
                        entry.value == value
                            && (entry.status.is_empty()
                                || entry.status == "A"
                                || entry.status == "active")
                    });

                    if !is_valid {
                        issues.push(Issue::error(
                            "VALUE_NOT_IN_HL7_TABLE",
                            Some(valueset.path.clone()),
                            format!(
                                "Value '{}' for {} is not in HL7 table {} ({})",
                                value, valueset.path, table_id.id, table_id.name
                            ),
                        ));
                    }
                }
            }
        }
    }
}

/// Validate that a field value does not exceed the maximum length
fn validate_length_constraint(msg: &Message, length: &LengthConstraint, issues: &mut Vec<Issue>) {
    if let Some(value) = crate::query::get(msg, &length.path) {
        if let Some(max_length) = length.max {
            if value.len() > max_length {
                issues.push(Issue::error(
                    "VALUE_TOO_LONG",
                    Some(length.path.clone()),
                    format!(
                        "Value '{}' for {} exceeds maximum length of {} characters",
                        value, length.path, max_length
                    ),
                ));
            }
        }
    }
    // Note: We don't report an error if the field is missing but has a length constraint
    // That would be handled by a separate presence constraint if needed
}

/// Validate that a field value is in the allowed HL7 table
#[expect(
    dead_code,
    reason = "Legacy table validator is retained for compatibility while the profile implementation is collapsed."
)]
fn validate_hl7_table(msg: &Message, table: &HL7Table, profile: &Profile, issues: &mut Vec<Issue>) {
    // This function is kept for backward compatibility but the new
    // validate_hl7_tables_with_precedence function should be used instead
    // when table precedence is important

    // Check value sets that reference this table by name
    for valueset in &profile.valuesets {
        if valueset.name == table.id {
            if let Some(value) = crate::query::get(msg, &valueset.path) {
                // Only validate if the field is not empty
                if !value.is_empty() {
                    // Check if the value exists in the table
                    let is_valid = table.codes.iter().any(|entry| {
                        entry.value == value
                            && (entry.status.is_empty()
                                || entry.status == "A"
                                || entry.status == "active")
                    });

                    if !is_valid {
                        issues.push(Issue::error(
                            "VALUE_NOT_IN_HL7_TABLE",
                            Some(valueset.path.clone()),
                            format!(
                                "Value '{}' for {} is not in HL7 table {} ({})",
                                value, valueset.path, table.id, table.name
                            ),
                        ));
                    }
                }
            }
        }
    }
}

/// Validate temporal rule (date/time relationships)
fn validate_temporal_rule(msg: &Message, rule: &TemporalRule, issues: &mut Vec<Issue>) {
    if let (Some(before_value), Some(after_value)) = (
        crate::query::get(msg, &rule.before),
        crate::query::get(msg, &rule.after),
    ) {
        // Parse the date/time values
        if let (Some(before_time), Some(after_time)) =
            (parse_datetime(before_value), parse_datetime(after_value))
        {
            // Check if before_time should be before after_time
            let is_valid = if rule.allow_equal {
                before_time <= after_time
            } else {
                before_time < after_time
            };

            if !is_valid {
                issues.push(Issue::error(
                    "TEMPORAL_RULE_VIOLATION",
                    Some(rule.before.clone()),
                    format!(
                        "Value '{}' for {} should be before {} for {}",
                        before_value, rule.before, after_value, rule.after
                    ),
                ));
            }
        } else {
            // Handle the case where the date/time parsing fails
            issues.push(Issue::error(
                "INVALID_DATETIME",
                Some(rule.before.clone()),
                format!(
                    "Invalid date/time value for {} or {}",
                    rule.before, rule.after
                ),
            ));
        }
    }
}

/// Validate custom rule
fn validate_custom_rule(msg: &Message, rule: &CustomRule, issues: &mut Vec<Issue>) {
    // Parse and evaluate the custom rule script
    if let Err(_e) = evaluate_custom_rule_script(msg, rule, issues) {
        // If parsing fails, fall back to the simple pattern matching
        evaluate_custom_rule_simple(msg, rule, issues);
    }
}

/// Evaluate custom rule script with proper expression parsing
fn evaluate_custom_rule_script(
    msg: &Message,
    rule: &CustomRule,
    issues: &mut Vec<Issue>,
) -> Result<(), ()> {
    // This is a simplified expression parser for custom rules
    // In a production implementation, this would be a full expression parser

    // Handle field access patterns like "field(PATH)"
    let script = &rule.script;

    // Pattern: "field(PATH).length() > N"
    if script.contains(".length() > ") {
        let re = Regex::new(r"field\(([^)]+)\)\.length\(\)\s*>\s*(\d+)").map_err(|_| ())?;
        if let Some(captures) = re.captures(script) {
            let path = &captures[1];
            let required_length: usize = captures[2].parse().map_err(|_| ())?;

            if let Some(value) = crate::query::get(msg, path) {
                if value.len() <= required_length {
                    issues.push(Issue::error(
                        "CUSTOM_RULE_VIOLATION",
                        Some(path.to_string()),
                        if rule.description.is_empty() {
                            format!(
                                "Field {} length {} is not greater than {}",
                                path,
                                value.len(),
                                required_length
                            )
                        } else {
                            rule.description.clone()
                        },
                    ));
                }
            }
            return Ok(());
        }
    }

    // Pattern: "field(PATH) in ['A', 'B', 'C']"
    if script.contains(" in [") {
        let re = Regex::new(r"field\(([^)]+)\)\s+in\s+\[([^\]]+)\]").map_err(|_| ())?;
        if let Some(captures) = re.captures(script) {
            let path = &captures[1];
            let values_str = &captures[2];

            if let Some(value) = crate::query::get(msg, path) {
                // Parse the allowed values
                let allowed_values: Vec<&str> = values_str
                    .split(',')
                    .map(str::trim)
                    .map(|s| s.trim_matches('\''))
                    .collect();

                if !allowed_values.contains(&value) {
                    issues.push(Issue::error(
                        "CUSTOM_RULE_VIOLATION",
                        Some(path.to_string()),
                        if rule.description.is_empty() {
                            format!(
                                "Field {} value '{}' is not in allowed set {:?}",
                                path, value, allowed_values
                            )
                        } else {
                            rule.description.clone()
                        },
                    ));
                }
            }
            return Ok(());
        }
    }

    // Pattern: "field(PATH).matches_regex('PATTERN')"
    if script.contains(".matches_regex(") {
        let re = Regex::new(r"field\(([^)]+)\)\.matches_regex\('([^']+)'\)").map_err(|_| ())?;
        if let Some(captures) = re.captures(script) {
            let path = &captures[1];
            let pattern = &captures[2];

            if let Some(value) = crate::query::get(msg, path) {
                let regex = Regex::new(pattern).map_err(|_| ())?;
                if !regex.is_match(value) {
                    issues.push(Issue::error(
                        "CUSTOM_RULE_VIOLATION",
                        Some(path.to_string()),
                        if rule.description.is_empty() {
                            format!(
                                "Field {} value '{}' does not match pattern '{}'",
                                path, value, pattern
                            )
                        } else {
                            rule.description.clone()
                        },
                    ));
                }
            }
            return Ok(());
        }
    }

    // Pattern: "field(PATH).starts_with('PREFIX')"
    if script.contains(".starts_with(") {
        let re = Regex::new(r"field\(([^)]+)\)\.starts_with\('([^']+)'\)").map_err(|_| ())?;
        if let Some(captures) = re.captures(script) {
            let path = &captures[1];
            let prefix = &captures[2];

            if let Some(value) = crate::query::get(msg, path) {
                if !value.starts_with(prefix) {
                    issues.push(Issue::error(
                        "CUSTOM_RULE_VIOLATION",
                        Some(path.to_string()),
                        if rule.description.is_empty() {
                            format!(
                                "Field {} value '{}' does not start with '{}'",
                                path, value, prefix
                            )
                        } else {
                            rule.description.clone()
                        },
                    ));
                }
            }
            return Ok(());
        }
    }

    // Pattern: "field(PATH).ends_with('SUFFIX')"
    if script.contains(".ends_with(") {
        let re = Regex::new(r"field\(([^)]+)\)\.ends_with\('([^']+)'\)").map_err(|_| ())?;
        if let Some(captures) = re.captures(script) {
            let path = &captures[1];
            let suffix = &captures[2];

            if let Some(value) = crate::query::get(msg, path) {
                if !value.ends_with(suffix) {
                    issues.push(Issue::error(
                        "CUSTOM_RULE_VIOLATION",
                        Some(path.to_string()),
                        if rule.description.is_empty() {
                            format!(
                                "Field {} value '{}' does not end with '{}'",
                                path, value, suffix
                            )
                        } else {
                            rule.description.clone()
                        },
                    ));
                }
            }
            return Ok(());
        }
    }

    // Pattern: "field(PATH).is_numeric()"
    if script.contains(".is_numeric()") {
        let re = Regex::new(r"field\(([^)]+)\)\.is_numeric\(\)").map_err(|_| ())?;
        if let Some(captures) = re.captures(script) {
            let path = &captures[1];

            if let Some(value) = crate::query::get(msg, path) {
                if !value.chars().all(|c| c.is_ascii_digit()) {
                    issues.push(Issue::error(
                        "CUSTOM_RULE_VIOLATION",
                        Some(path.to_string()),
                        if rule.description.is_empty() {
                            format!("Field {} value '{}' is not numeric", path, value)
                        } else {
                            rule.description.clone()
                        },
                    ));
                }
            }
            return Ok(());
        }
    }

    // Pattern: "field(PATH1) == field(PATH2)"
    if script.contains(" == field(") {
        let re = Regex::new(r"field\(([^)]+)\)\s*==\s*field\(([^)]+)\)").map_err(|_| ())?;
        if let Some(captures) = re.captures(script) {
            let path1 = &captures[1];
            let path2 = &captures[2];

            if let (Some(value1), Some(value2)) =
                (crate::query::get(msg, path1), crate::query::get(msg, path2))
            {
                if value1 != value2 {
                    issues.push(Issue::error(
                        "CUSTOM_RULE_VIOLATION",
                        Some(path1.to_string()),
                        if rule.description.is_empty() {
                            format!(
                                "Field {} value '{}' does not equal field {} value '{}'",
                                path1, value1, path2, value2
                            )
                        } else {
                            rule.description.clone()
                        },
                    ));
                }
            }
            return Ok(());
        }
    }

    // Pattern: "field(PATH).is_phone_number()"
    if script.contains(".is_phone_number()") {
        let re = Regex::new(r"field\(([^)]+)\)\.is_phone_number\(\)").map_err(|_| ())?;
        if let Some(captures) = re.captures(script) {
            let path = &captures[1];

            if let Some(value) = crate::query::get(msg, path) {
                if !is_phone_number(value) {
                    issues.push(Issue::error(
                        "CUSTOM_RULE_VIOLATION",
                        Some(path.to_string()),
                        if rule.description.is_empty() {
                            format!(
                                "Field {} value '{}' is not a valid phone number",
                                path, value
                            )
                        } else {
                            rule.description.clone()
                        },
                    ));
                }
            }
            return Ok(());
        }
    }

    // Pattern: "field(PATH).is_email()"
    if script.contains(".is_email()") {
        let re = Regex::new(r"field\(([^)]+)\)\.is_email\(\)").map_err(|_| ())?;
        if let Some(captures) = re.captures(script) {
            let path = &captures[1];

            if let Some(value) = crate::query::get(msg, path) {
                if !is_email(value) {
                    issues.push(Issue::error(
                        "CUSTOM_RULE_VIOLATION",
                        Some(path.to_string()),
                        if rule.description.is_empty() {
                            format!(
                                "Field {} value '{}' is not a valid email address",
                                path, value
                            )
                        } else {
                            rule.description.clone()
                        },
                    ));
                }
            }
            return Ok(());
        }
    }

    // Pattern: "field(PATH).is_ssn()"
    if script.contains(".is_ssn()") {
        let re = Regex::new(r"field\(([^)]+)\)\.is_ssn\(\)").map_err(|_| ())?;
        if let Some(captures) = re.captures(script) {
            let path = &captures[1];

            if let Some(value) = crate::query::get(msg, path) {
                if !is_ssn(value) {
                    issues.push(Issue::error(
                        "CUSTOM_RULE_VIOLATION",
                        Some(path.to_string()),
                        if rule.description.is_empty() {
                            format!("Field {} value '{}' is not a valid SSN", path, value)
                        } else {
                            rule.description.clone()
                        },
                    ));
                }
            }
            return Ok(());
        }
    }

    // Pattern: "field(PATH).is_valid_birth_date()"
    if script.contains(".is_valid_birth_date()") {
        let re = Regex::new(r"field\(([^)]+)\)\.is_valid_birth_date\(\)").map_err(|_| ())?;
        if let Some(captures) = re.captures(script) {
            let path = &captures[1];

            if let Some(value) = crate::query::get(msg, path) {
                if !is_valid_birth_date(value) {
                    issues.push(Issue::error(
                        "CUSTOM_RULE_VIOLATION",
                        Some(path.to_string()),
                        if rule.description.is_empty() {
                            format!("Field {} value '{}' is not a valid birth date", path, value)
                        } else {
                            rule.description.clone()
                        },
                    ));
                }
            }
            return Ok(());
        }
    }

    // Pattern: "is_valid_age_range(field(PATH1), field(PATH2))"
    if script.contains("is_valid_age_range(") {
        let re = Regex::new(r"is_valid_age_range\(field\(([^)]+)\),\s*field\(([^)]+)\)\)")
            .map_err(|_| ())?;
        if let Some(captures) = re.captures(script) {
            let path1 = &captures[1];
            let path2 = &captures[2];

            if let (Some(value1), Some(value2)) =
                (crate::query::get(msg, path1), crate::query::get(msg, path2))
            {
                if !is_valid_age_range(value1, value2) {
                    issues.push(Issue::error(
                        "CUSTOM_RULE_VIOLATION",
                        Some(path1.to_string()),
                        if rule.description.is_empty() {
                            format!("Age range between {} and {} is not valid", path1, path2)
                        } else {
                            rule.description.clone()
                        },
                    ));
                }
            }
            return Ok(());
        }
    }

    // Pattern: "field(PATH) between VALUE1 and VALUE2"
    if script.contains(" between ") && script.contains(" and ") {
        let re = Regex::new(r"field\(([^)]+)\)\s+between\s+([^\s]+)\s+and\s+([^\s]+)")
            .map_err(|_| ())?;
        if let Some(captures) = re.captures(script) {
            let path = &captures[1];
            let min_val = &captures[2];
            let max_val = &captures[3];

            if let Some(value) = crate::query::get(msg, path) {
                if !is_within_range(value, min_val, max_val) {
                    issues.push(Issue::error(
                        "CUSTOM_RULE_VIOLATION",
                        Some(path.to_string()),
                        if rule.description.is_empty() {
                            format!(
                                "Field {} value '{}' is not between {} and {}",
                                path, value, min_val, max_val
                            )
                        } else {
                            rule.description.clone()
                        },
                    ));
                }
            }
            return Ok(());
        }
    }

    // If we get here, we didn't match any known patterns
    Err(())
}

/// Simple pattern matching fallback for custom rules (original implementation)
fn evaluate_custom_rule_simple(msg: &Message, rule: &CustomRule, issues: &mut Vec<Issue>) {
    // For now, we'll implement a simple expression-based custom rule system
    // The script field can contain simple expressions like:
    // "field(PID.5.1).length() > 5"
    // "field(PID.8) in ['M', 'F']"
    // "field(PID.7).matches_regex('^[0-9]{8}$')"

    // This is a simplified implementation - a full implementation would require
    // a proper expression parser and evaluator

    // For demonstration purposes, let's implement a few basic patterns
    if rule.script.starts_with("field(") && rule.script.contains(").length() > ") {
        // Pattern: "field(PATH).length() > N"
        if let Some(path_end) = rule.script.find(").length() > ") {
            let path = &rule.script[6..path_end];
            if let Some(value) = crate::query::get(msg, path) {
                let length_str = &rule.script[path_end + 13..];
                if let Ok(required_length) = length_str.parse::<usize>() {
                    if value.len() <= required_length {
                        issues.push(Issue::error(
                            "CUSTOM_RULE_VIOLATION",
                            Some(path.to_string()),
                            if rule.description.is_empty() {
                                format!(
                                    "Field {} length {} is not greater than {}",
                                    path,
                                    value.len(),
                                    required_length
                                )
                            } else {
                                rule.description.clone()
                            },
                        ));
                    }
                }
            }
        }
    } else if rule.script.starts_with("field(") && rule.script.contains(") in [") {
        // Pattern: "field(PATH) in ['A', 'B', 'C']"
        if let Some(path_end) = rule.script.find(") in [") {
            let path = &rule.script[6..path_end];
            if let Some(value) = crate::query::get(msg, path) {
                // Extract the allowed values
                let values_part = &rule.script[path_end + 7..];
                if let Some(values_str) = values_part.strip_suffix("]") {
                    // Split by comma and remove quotes
                    let allowed_values: Vec<&str> = values_str
                        .split(',')
                        .map(str::trim)
                        .map(|s| s.trim_matches('\''))
                        .collect();

                    if !allowed_values.contains(&value) {
                        issues.push(Issue::error(
                            "CUSTOM_RULE_VIOLATION",
                            Some(path.to_string()),
                            if rule.description.is_empty() {
                                format!(
                                    "Field {} value '{}' is not in allowed set {:?}",
                                    path, value, allowed_values
                                )
                            } else {
                                rule.description.clone()
                            },
                        ));
                    }
                }
            }
        }
    } else if rule.script.starts_with("field(") && rule.script.contains(").matches_regex(") {
        // Pattern: "field(PATH).matches_regex('PATTERN')"
        if let Some(path_end) = rule.script.find(").matches_regex(") {
            let path = &rule.script[6..path_end];
            if let Some(value) = crate::query::get(msg, path) {
                // Extract the regex pattern
                let pattern_part = &rule.script[path_end + 15..];
                if pattern_part.starts_with('\'') && pattern_part.ends_with("')") {
                    let pattern = &pattern_part[1..pattern_part.len() - 2];
                    // Simple regex matching (in a real implementation, we would use regex crate)
                    if !value.contains(pattern) && pattern != ".*" {
                        // This is a very simplified check - just for demonstration
                        issues.push(Issue::error(
                            "CUSTOM_RULE_VIOLATION",
                            Some(path.to_string()),
                            if rule.description.is_empty() {
                                format!(
                                    "Field {} value '{}' does not match pattern '{}'",
                                    path, value, pattern
                                )
                            } else {
                                rule.description.clone()
                            },
                        ));
                    }
                }
            }
        }
    }
    // Additional custom rule patterns can be added here
}

/// Validate cross-field rule
fn validate_cross_field_rule(
    msg: &Message,
    rule: &CrossFieldRule,
    profile: &Profile,
    issues: &mut Vec<Issue>,
) {
    // Check if all conditions are met
    let conditions_met = rule
        .conditions
        .iter()
        .all(|condition| check_rule_condition(msg, condition));

    match rule.validation_mode.as_str() {
        "assert" => {
            // Assert mode: conditions must be true, fail if they're not
            if !conditions_met {
                issues.push(Issue::error(
                    "CROSS_FIELD_ASSERTION_FAILED",
                    None,
                    format!(
                        "Cross-field assertion failed: {} ({})",
                        rule.description, rule.id
                    ),
                ));
            }
            // If conditions are true, validation passes (no error)
        }
        _ => {
            // Conditional mode (default): if conditions are met, execute actions
            if conditions_met {
                for action in &rule.actions {
                    execute_rule_action(msg, action, rule, profile, issues);
                }
            }
        }
    }
}

/// Execute a rule action
fn execute_rule_action(
    msg: &Message,
    action: &RuleAction,
    rule: &CrossFieldRule,
    profile: &Profile,
    issues: &mut Vec<Issue>,
) {
    match action.action.as_str() {
        "require" => {
            // Check if the required field exists and is not empty
            if let Some(value) = crate::query::get(msg, &action.field) {
                if value.is_empty() {
                    issues.push(Issue::error(
                        "CROSS_FIELD_VALIDATION_ERROR",
                        Some(action.field.clone()),
                        action.message.clone().unwrap_or_else(|| {
                            format!(
                                "Field {} is required by cross-field rule {}",
                                action.field, rule.id
                            )
                        }),
                    ));
                }
            } else {
                issues.push(Issue::error(
                    "CROSS_FIELD_VALIDATION_ERROR",
                    Some(action.field.clone()),
                    action.message.clone().unwrap_or_else(|| {
                        format!(
                            "Field {} is required by cross-field rule {}",
                            action.field, rule.id
                        )
                    }),
                ));
            }
        }
        "prohibit" => {
            // Check if the prohibited field exists and is not empty
            if let Some(value) = crate::query::get(msg, &action.field) {
                if !value.is_empty() {
                    issues.push(Issue::error(
                        "CROSS_FIELD_VALIDATION_ERROR",
                        Some(action.field.clone()),
                        action.message.clone().unwrap_or_else(|| {
                            format!(
                                "Field {} is prohibited by cross-field rule {}",
                                action.field, rule.id
                            )
                        }),
                    ));
                }
            }
            // If the field doesn't exist at all, that's fine (it's not present)
        }
        "validate" => {
            // Apply additional validation based on action parameters
            if let Some(value) = crate::query::get(msg, &action.field) {
                // Only validate if the field is not empty
                if !value.is_empty() {
                    // Validate data type if specified
                    if let Some(datatype) = &action.datatype {
                        if !validate_data_type(value, datatype) {
                            issues.push(Issue::error(
                                "CROSS_FIELD_VALIDATION_ERROR",
                                Some(action.field.clone()),
                                action.message.clone().unwrap_or_else(||
                                    format!("Field {} does not match data type {} required by cross-field rule {}",
                                           action.field, datatype, rule.id)),
                            ));
                        }
                    }

                    // Validate against value set if specified
                    if let Some(valueset_name) = &action.valueset {
                        // Find the value set in the profile
                        if let Some(valueset) = find_valueset_by_name(profile, valueset_name) {
                            if !valueset.codes.contains(&value.to_string()) {
                                issues.push(Issue::error(
                                    "CROSS_FIELD_VALIDATION_ERROR",
                                    Some(action.field.clone()),
                                    action.message.clone().unwrap_or_else(||
                                        format!("Value '{}' for {} is not in value set {} required by cross-field rule {}",
                                               value, action.field, valueset_name, rule.id)),
                                ));
                            }
                        }
                    }
                }
            }
        }
        _ => {
            // Unknown action, ignore
        }
    }
}

/// Validate contextual rule
fn validate_contextual_rule(
    msg: &Message,
    rule: &ContextualRule,
    profile: &Profile,
    issues: &mut Vec<Issue>,
) {
    // Check if the context field has the expected value
    if let Some(context_value) = crate::query::get(msg, &rule.context_field) {
        if context_value == rule.context_value {
            // Apply the validation based on validation_type
            match rule.validation_type.as_str() {
                "require" => {
                    // Check if the target field exists and is not empty
                    if let Some(value) = crate::query::get(msg, &rule.target_field) {
                        if value.is_empty() {
                            issues.push(Issue::error(
                                "CONTEXTUAL_VALIDATION_ERROR",
                                Some(rule.target_field.clone()),
                                if rule.description.is_empty() {
                                    format!(
                                        "Field {} is required when {} equals {}",
                                        rule.target_field, rule.context_field, rule.context_value
                                    )
                                } else {
                                    rule.description.clone()
                                },
                            ));
                        }
                    } else {
                        issues.push(Issue::error(
                            "CONTEXTUAL_VALIDATION_ERROR",
                            Some(rule.target_field.clone()),
                            if rule.description.is_empty() {
                                format!(
                                    "Field {} is required when {} equals {}",
                                    rule.target_field, rule.context_field, rule.context_value
                                )
                            } else {
                                rule.description.clone()
                            },
                        ));
                    }
                }
                "prohibit" => {
                    // Check if the target field exists and is not empty
                    if let Some(value) = crate::query::get(msg, &rule.target_field) {
                        if !value.is_empty() {
                            issues.push(Issue::error(
                                "CONTEXTUAL_VALIDATION_ERROR",
                                Some(rule.target_field.clone()),
                                if rule.description.is_empty() {
                                    format!(
                                        "Field {} is prohibited when {} equals {}",
                                        rule.target_field, rule.context_field, rule.context_value
                                    )
                                } else {
                                    rule.description.clone()
                                },
                            ));
                        }
                    }
                    // If the field doesn't exist at all, that's fine (it's not present)
                }
                "validate_datatype" => {
                    // Validate target field against specified data type
                    if let Some(datatype) = rule.parameters.get("datatype") {
                        if let Some(value) = crate::query::get(msg, &rule.target_field) {
                            if !validate_data_type(value, datatype) {
                                issues.push(Issue::error(
                                    "CONTEXTUAL_VALIDATION_ERROR",
                                    Some(rule.target_field.clone()),
                                    if rule.description.is_empty() {
                                        format!("Field {} does not match data type {} required when {} equals {}", 
                                               rule.target_field, datatype, rule.context_field, rule.context_value)
                                    } else {
                                        rule.description.clone()
                                    },
                                ));
                            }
                        }
                    }
                }
                "validate_valueset" => {
                    // Validate target field against specified value set
                    if let Some(valueset_name) = rule.parameters.get("valueset") {
                        if let Some(value) = crate::query::get(msg, &rule.target_field) {
                            // Find the value set in the profile
                            if let Some(valueset) = find_valueset_by_name(profile, valueset_name) {
                                if !valueset.codes.contains(&value.to_string()) {
                                    issues.push(Issue::error(
                                        "CONTEXTUAL_VALIDATION_ERROR",
                                        Some(rule.target_field.clone()),
                                        if rule.description.is_empty() {
                                            format!("Value '{}' for {} is not in value set {} required when {} equals {}", 
                                                   value, rule.target_field, valueset_name, rule.context_field, rule.context_value)
                                        } else {
                                            rule.description.clone()
                                        },
                                    ));
                                }
                            }
                        }
                    }
                }
                _ => {
                    // Unknown validation type, ignore
                }
            }
        }
    }
}

/// Find a value set by name within a profile
fn find_valueset_by_name<'a>(profile: &'a Profile, name: &str) -> Option<&'a ValueSet> {
    profile
        .valuesets
        .iter()
        .find(|valueset| valueset.name == name)
}

/// Profile loader module with remote loading and caching support
pub mod loader;

/// Persistent profile cache with PostgreSQL backend and two-tier caching
#[cfg(feature = "persistent-cache")]
pub mod persistent_cache;

#[cfg(test)]
mod tests;