helios-fhirpath 0.2.0

This is an implementation of HL7's FHIRPath Specification.
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
//! # FHIR Resource Type Handling
//!
//! Provides utilities for working with FHIR resource types in FHIRPath evaluation.

use crate::evaluator::EvaluationContext;
use crate::fhir_type_hierarchy::{capitalize_first_letter, is_fhir_primitive_type};
use crate::parser::TypeSpecifier;
use helios_fhir::{FhirComplexTypeProvider, FhirResourceTypeProvider, FhirVersion};
use helios_fhirpath_support::{EvaluationError, EvaluationResult};

/// Handles type operations for FHIR resources, supporting is/as operators.
/// This module provides enhanced support for handling FHIR resource types
/// in FHIRPath expressions, allowing for proper type checking and filtering
/// based on resource types.
///
/// Checks if a type name is a resource type for the given FHIR version
///
/// # Arguments
///
/// * `type_name` - The type name to check (e.g., "Patient", "Observation")
/// * `fhir_version` - The FHIR version to check against
///
/// # Returns
///
/// * `true` if the type is a resource type in the given FHIR version, `false` otherwise
pub fn is_resource_type_for_version(type_name: &str, fhir_version: &FhirVersion) -> bool {
    match fhir_version {
        #[cfg(feature = "R4")]
        FhirVersion::R4 => helios_fhir::r4::Resource::is_resource_type(type_name),
        #[cfg(feature = "R4B")]
        FhirVersion::R4B => helios_fhir::r4b::Resource::is_resource_type(type_name),
        #[cfg(feature = "R5")]
        FhirVersion::R5 => helios_fhir::r5::Resource::is_resource_type(type_name),
        #[cfg(feature = "R6")]
        FhirVersion::R6 => helios_fhir::r6::Resource::is_resource_type(type_name),
        #[allow(unreachable_patterns)]
        _ => false, // For versions not enabled by feature flags
    }
}

/// Checks if a type name is a complex type for the given FHIR version
///
/// # Arguments
///
/// * `type_name` - The type name to check (e.g., "Quantity", "HumanName")
/// * `fhir_version` - The FHIR version to check against
///
/// # Returns
///
/// * `true` if the type is a complex type in the given FHIR version, `false` otherwise
pub fn is_complex_type_for_version(type_name: &str, fhir_version: &FhirVersion) -> bool {
    match fhir_version {
        #[cfg(feature = "R4")]
        FhirVersion::R4 => helios_fhir::r4::ComplexTypes::is_complex_type(type_name),
        #[cfg(feature = "R4B")]
        FhirVersion::R4B => helios_fhir::r4b::ComplexTypes::is_complex_type(type_name),
        #[cfg(feature = "R5")]
        FhirVersion::R5 => helios_fhir::r5::ComplexTypes::is_complex_type(type_name),
        #[cfg(feature = "R6")]
        FhirVersion::R6 => helios_fhir::r6::ComplexTypes::is_complex_type(type_name),
        #[allow(unreachable_patterns)]
        _ => false, // For versions not enabled by feature flags
    }
}

/// Determines if a value is of a specified FHIR or System type (context-aware version)
///
/// # Arguments
///
/// * `value` - The value to check
/// * `type_spec` - The type specifier to check against
/// * `context` - The evaluation context containing FHIR version information
///
/// # Returns
///
/// * `true` if the value is of the specified type, `false` otherwise
pub fn is_of_type_with_context(
    value: &EvaluationResult,
    type_spec: &TypeSpecifier,
    context: &EvaluationContext,
) -> Result<bool, EvaluationError> {
    let (target_namespace, target_type) =
        extract_namespace_and_type_with_context(type_spec, context)?;
    match value {
        EvaluationResult::Boolean(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Boolean for boolean values
                check_type_match(
                    &Some("System".to_string()),
                    "Boolean",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Integer(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Integer for integer values
                check_type_match(
                    &Some("System".to_string()),
                    "Integer",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Decimal(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Decimal for decimal values
                check_type_match(
                    &Some("System".to_string()),
                    "Decimal",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::String(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.String for string values
                check_type_match(
                    &Some("System".to_string()),
                    "String",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Date(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Date for date values
                check_type_match(
                    &Some("System".to_string()),
                    "Date",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::DateTime(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.DateTime for datetime values
                check_type_match(
                    &Some("System".to_string()),
                    "DateTime",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Time(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Time for time values
                check_type_match(
                    &Some("System".to_string()),
                    "Time",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Quantity(_, _, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Quantity for quantity values
                check_type_match(
                    &Some("System".to_string()),
                    "Quantity",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Object { map, type_info, .. } => {
            // First check if there's type_info available
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else if let Some(resource_type_value) = map.get("resourceType") {
                // For FHIR resources, check the resourceType property
                if let EvaluationResult::String(resource_type, _, _) = resource_type_value {
                    // Check if the resource type matches the target type
                    check_type_match(
                        &Some("FHIR".to_string()),
                        resource_type,
                        &target_namespace,
                        &target_type,
                    )
                } else {
                    Ok(false)
                }
            } else {
                // Default to System.Object for object values
                check_type_match(
                    &Some("System".to_string()),
                    "Object",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Collection { type_info, .. } => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Collection for collection values
                check_type_match(
                    &Some("System".to_string()),
                    "Collection",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Empty => {
            // Empty values don't match any specific type
            Ok(false)
        }
        #[cfg(not(any(feature = "R4", feature = "R4B")))]
        EvaluationResult::Integer64(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Integer64 for integer64 values
                check_type_match(
                    &Some("System".to_string()),
                    "Integer64",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        #[cfg(any(feature = "R4", feature = "R4B"))]
        EvaluationResult::Integer64(_, _, _) => {
            // In R4 and R4B, Integer64 should be treated as Integer
            check_type_match(
                &Some("System".to_string()),
                "Integer",
                &target_namespace,
                &target_type,
            )
        }
    }
}

/// Determines if a value is of a specified FHIR or System type with cross-namespace matching (for ofType operations)
///
/// # Arguments
///
/// * `value` - The value to check
/// * `type_spec` - The type specifier to check against
///
/// # Returns
///
/// * `true` if the value is of the specified type, `false` otherwise
#[allow(dead_code)]
pub fn is_of_type_for_of_type(
    value: &EvaluationResult,
    type_spec: &TypeSpecifier,
) -> Result<bool, EvaluationError> {
    let (target_namespace, target_type) = extract_namespace_and_type_without_context(type_spec)?;

    match value {
        EvaluationResult::Boolean(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match_with_cross_namespace(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                    true,
                )
            } else {
                // Default to System.Boolean for boolean values
                check_type_match_with_cross_namespace(
                    &Some("System".to_string()),
                    "Boolean",
                    &target_namespace,
                    &target_type,
                    true,
                )
            }
        }
        EvaluationResult::Integer(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match_with_cross_namespace(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                    true,
                )
            } else {
                // Default to System.Integer for integer values
                check_type_match_with_cross_namespace(
                    &Some("System".to_string()),
                    "Integer",
                    &target_namespace,
                    &target_type,
                    true,
                )
            }
        }
        EvaluationResult::Decimal(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match_with_cross_namespace(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                    true,
                )
            } else {
                // Default to System.Decimal for decimal values
                check_type_match_with_cross_namespace(
                    &Some("System".to_string()),
                    "Decimal",
                    &target_namespace,
                    &target_type,
                    true,
                )
            }
        }
        EvaluationResult::String(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match_with_cross_namespace(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                    true,
                )
            } else {
                // Default to System.String for string values
                check_type_match_with_cross_namespace(
                    &Some("System".to_string()),
                    "String",
                    &target_namespace,
                    &target_type,
                    true,
                )
            }
        }
        EvaluationResult::Date(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match_with_cross_namespace(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                    true,
                )
            } else {
                // Default to System.Date for date values
                check_type_match_with_cross_namespace(
                    &Some("System".to_string()),
                    "Date",
                    &target_namespace,
                    &target_type,
                    true,
                )
            }
        }
        EvaluationResult::DateTime(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match_with_cross_namespace(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                    true,
                )
            } else {
                // Default to System.DateTime for datetime values
                check_type_match_with_cross_namespace(
                    &Some("System".to_string()),
                    "DateTime",
                    &target_namespace,
                    &target_type,
                    true,
                )
            }
        }
        EvaluationResult::Time(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match_with_cross_namespace(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                    true,
                )
            } else {
                // Default to System.Time for time values
                check_type_match_with_cross_namespace(
                    &Some("System".to_string()),
                    "Time",
                    &target_namespace,
                    &target_type,
                    true,
                )
            }
        }
        EvaluationResult::Quantity(_, _, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match_with_cross_namespace(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                    true,
                )
            } else {
                // Default to System.Quantity for quantity values
                check_type_match_with_cross_namespace(
                    &Some("System".to_string()),
                    "Quantity",
                    &target_namespace,
                    &target_type,
                    true,
                )
            }
        }
        EvaluationResult::Collection { .. } => {
            // Collections are not simple types and don't match single type checks
            Ok(false)
        }
        EvaluationResult::Empty => {
            // Empty values don't match any specific type
            Ok(false)
        }
        #[cfg(not(any(feature = "R4", feature = "R4B")))]
        EvaluationResult::Integer64(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match_with_cross_namespace(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                    true,
                )
            } else {
                // Default to System.Integer64 for integer64 values
                check_type_match_with_cross_namespace(
                    &Some("System".to_string()),
                    "Integer64",
                    &target_namespace,
                    &target_type,
                    true,
                )
            }
        }
        #[cfg(any(feature = "R4", feature = "R4B"))]
        EvaluationResult::Integer64(_, _, _) => {
            // In R4 and R4B, Integer64 should be treated as Integer
            check_type_match_with_cross_namespace(
                &Some("System".to_string()),
                "Integer",
                &target_namespace,
                &target_type,
                true,
            )
        }
        EvaluationResult::Object { map, type_info, .. } => {
            // First check if there's type_info available
            if let Some(type_info) = type_info {
                check_type_match_with_cross_namespace(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                    true,
                )
            } else if let Some(resource_type_value) = map.get("resourceType") {
                // For FHIR resources, check the resourceType property
                if let EvaluationResult::String(resource_type, _, _) = resource_type_value {
                    // Check if the resource type matches the target type
                    check_type_match_with_cross_namespace(
                        &Some("FHIR".to_string()),
                        resource_type,
                        &target_namespace,
                        &target_type,
                        true,
                    )
                } else {
                    Ok(false)
                }
            } else {
                // For non-FHIR objects, we can't determine the type
                Ok(false)
            }
        }
    }
}

/// Determines if a value is of a specified FHIR or System type (legacy version without context)
///
/// # Arguments
///
/// * `value` - The value to check
/// * `type_spec` - The type specifier to check against
///
/// # Returns
///
/// * `true` if the value is of the specified type, `false` otherwise
#[allow(dead_code)]
pub fn is_of_type(
    value: &EvaluationResult,
    type_spec: &TypeSpecifier,
) -> Result<bool, EvaluationError> {
    let (target_namespace, target_type) = extract_namespace_and_type_without_context(type_spec)?;

    match value {
        EvaluationResult::Boolean(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Boolean for boolean values
                check_type_match(
                    &Some("System".to_string()),
                    "Boolean",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Integer(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Integer for integer values
                check_type_match(
                    &Some("System".to_string()),
                    "Integer",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Decimal(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Decimal for decimal values
                check_type_match(
                    &Some("System".to_string()),
                    "Decimal",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::String(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.String for string values
                check_type_match(
                    &Some("System".to_string()),
                    "String",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Date(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Date for date values
                check_type_match(
                    &Some("System".to_string()),
                    "Date",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::DateTime(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.DateTime for datetime values
                check_type_match(
                    &Some("System".to_string()),
                    "DateTime",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Time(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Time for time values
                check_type_match(
                    &Some("System".to_string()),
                    "Time",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Quantity(_, _, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Quantity for quantity values
                check_type_match(
                    &Some("System".to_string()),
                    "Quantity",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        EvaluationResult::Collection { .. } => {
            // Collections are not simple types and don't match single type checks
            Ok(false)
        }
        EvaluationResult::Empty => {
            // Empty values don't match any specific type
            Ok(false)
        }
        #[cfg(not(any(feature = "R4", feature = "R4B")))]
        EvaluationResult::Integer64(_, type_info, _) => {
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else {
                // Default to System.Integer64 for integer64 values
                check_type_match(
                    &Some("System".to_string()),
                    "Integer64",
                    &target_namespace,
                    &target_type,
                )
            }
        }
        #[cfg(any(feature = "R4", feature = "R4B"))]
        EvaluationResult::Integer64(_, _, _) => {
            // In R4 and R4B, Integer64 should be treated as Integer
            check_type_match(
                &Some("System".to_string()),
                "Integer",
                &target_namespace,
                &target_type,
            )
        }
        EvaluationResult::Object { map, type_info, .. } => {
            // First check if there's type_info available
            if let Some(type_info) = type_info {
                check_type_match(
                    &Some(type_info.namespace.clone()),
                    &type_info.name,
                    &target_namespace,
                    &target_type,
                )
            } else if let Some(resource_type_value) = map.get("resourceType") {
                // For FHIR resources, check the resourceType property
                if let EvaluationResult::String(resource_type, _, _) = resource_type_value {
                    // Check if the resource type matches the target type
                    check_type_match(
                        &Some("FHIR".to_string()),
                        resource_type,
                        &target_namespace,
                        &target_type,
                    )
                } else {
                    Ok(false)
                }
            } else {
                // For non-FHIR objects, we can't determine the type
                Ok(false)
            }
        }
    }
}

/// Helper function to check if two types match, considering namespace and case-insensitive comparison
fn check_type_match(
    value_namespace: &Option<String>,
    value_type: &str,
    target_namespace: &Option<String>,
    target_type: &str,
) -> Result<bool, EvaluationError> {
    // Special handling for FHIR types in is() operations
    // When target is FHIR.string, FHIR string subtypes should match
    if let (Some(value_ns), Some(target_ns)) = (value_namespace, target_namespace) {
        if value_ns.eq_ignore_ascii_case("FHIR") && target_ns.eq_ignore_ascii_case("FHIR") {
            // Use generated type hierarchy to check if value_type is a subtype of target_type
            #[cfg(feature = "R4")]
            if helios_fhir::r4::type_hierarchy::is_subtype_of(value_type, target_type) {
                return Ok(true);
            }
            #[cfg(feature = "R4B")]
            if helios_fhir::r4b::type_hierarchy::is_subtype_of(value_type, target_type) {
                return Ok(true);
            }
            #[cfg(feature = "R5")]
            if helios_fhir::r5::type_hierarchy::is_subtype_of(value_type, target_type) {
                return Ok(true);
            }
            #[cfg(feature = "R6")]
            if helios_fhir::r6::type_hierarchy::is_subtype_of(value_type, target_type) {
                return Ok(true);
            }
        }
    }

    // Special handling for FHIR primitive types matching unqualified System types in is() operations
    if target_namespace.is_none() {
        if let Some(ns) = value_namespace {
            if ns.eq_ignore_ascii_case("FHIR") {
                // Use generated type hierarchy for FHIR subtypes
                #[cfg(feature = "R4")]
                if helios_fhir::r4::type_hierarchy::is_subtype_of(value_type, target_type) {
                    if target_type.eq_ignore_ascii_case("string") {
                        eprintln!("Matched FHIR string subtype: {} -> string", value_type);
                    }
                    return Ok(true);
                }
                #[cfg(feature = "R4B")]
                if helios_fhir::r4b::type_hierarchy::is_subtype_of(value_type, target_type) {
                    if target_type.eq_ignore_ascii_case("string") {
                        eprintln!("Matched FHIR string subtype: {} -> string", value_type);
                    }
                    return Ok(true);
                }
                #[cfg(feature = "R5")]
                if helios_fhir::r5::type_hierarchy::is_subtype_of(value_type, target_type) {
                    if target_type.eq_ignore_ascii_case("string") {
                        eprintln!("Matched FHIR string subtype: {} -> string", value_type);
                    }
                    return Ok(true);
                }
                #[cfg(feature = "R6")]
                if helios_fhir::r6::type_hierarchy::is_subtype_of(value_type, target_type) {
                    if target_type.eq_ignore_ascii_case("string") {
                        eprintln!("Matched FHIR string subtype: {} -> string", value_type);
                    }
                    return Ok(true);
                }

                // Other FHIR primitive types should match their unqualified equivalents
                let direct_matches = [
                    ("boolean", "boolean"),
                    ("decimal", "decimal"),
                    ("date", "date"),
                    ("datetime", "datetime"),
                    ("time", "time"),
                    ("instant", "datetime"), // instant is a special datetime
                ];

                for (fhir_type, system_type) in &direct_matches {
                    if value_type.eq_ignore_ascii_case(fhir_type)
                        && target_type.eq_ignore_ascii_case(system_type)
                    {
                        return Ok(true);
                    }
                }
            }
        }
    }

    // For Quantity types and their subtypes, we need to allow cross-namespace matching
    // because FHIR.Age should match System.Quantity
    let allow_cross_namespace = if target_type.eq_ignore_ascii_case("quantity") {
        #[cfg(feature = "R4")]
        if helios_fhir::r4::type_hierarchy::is_subtype_of(value_type, "Quantity") {
            return check_type_match_with_cross_namespace(
                value_namespace,
                value_type,
                target_namespace,
                target_type,
                true,
            );
        }
        #[cfg(feature = "R4B")]
        if helios_fhir::r4b::type_hierarchy::is_subtype_of(value_type, "Quantity") {
            return check_type_match_with_cross_namespace(
                value_namespace,
                value_type,
                target_namespace,
                target_type,
                true,
            );
        }
        #[cfg(feature = "R5")]
        if helios_fhir::r5::type_hierarchy::is_subtype_of(value_type, "Quantity") {
            return check_type_match_with_cross_namespace(
                value_namespace,
                value_type,
                target_namespace,
                target_type,
                true,
            );
        }
        #[cfg(feature = "R6")]
        if helios_fhir::r6::type_hierarchy::is_subtype_of(value_type, "Quantity") {
            return check_type_match_with_cross_namespace(
                value_namespace,
                value_type,
                target_namespace,
                target_type,
                true,
            );
        }
        false
    } else {
        false
    };

    check_type_match_with_cross_namespace(
        value_namespace,
        value_type,
        target_namespace,
        target_type,
        allow_cross_namespace,
    )
}

/// Helper function to check if two types match with configurable cross-namespace matching
fn check_type_match_with_cross_namespace(
    value_namespace: &Option<String>,
    value_type: &str,
    target_namespace: &Option<String>,
    target_type: &str,
    allow_cross_namespace: bool,
) -> Result<bool, EvaluationError> {
    // Case-insensitive type name comparison
    let type_matches = value_type.eq_ignore_ascii_case(target_type);

    // Check FHIR type hierarchy using generated hierarchy
    let type_hierarchy_matches = if allow_cross_namespace
        || (value_namespace.as_deref() == target_namespace.as_deref()
            && value_namespace.as_deref() == Some("FHIR"))
    {
        #[cfg(feature = "R4")]
        if helios_fhir::r4::type_hierarchy::is_subtype_of(value_type, target_type) {
            return Ok(true);
        }
        #[cfg(feature = "R4B")]
        if helios_fhir::r4b::type_hierarchy::is_subtype_of(value_type, target_type) {
            return Ok(true);
        }
        #[cfg(feature = "R5")]
        if helios_fhir::r5::type_hierarchy::is_subtype_of(value_type, target_type) {
            return Ok(true);
        }
        #[cfg(feature = "R6")]
        if helios_fhir::r6::type_hierarchy::is_subtype_of(value_type, target_type) {
            return Ok(true);
        }
        false
    } else {
        false
    };

    let type_or_hierarchy_matches = type_matches || type_hierarchy_matches;

    // If no target namespace is specified, match any namespace
    if target_namespace.is_none() {
        return Ok(type_or_hierarchy_matches);
    }

    // Special case: FHIR complex types should match their System equivalents
    // For example, FHIR.Quantity should match System.Quantity
    if type_or_hierarchy_matches {
        match (value_namespace, target_namespace) {
            (Some(value_ns), Some(target_ns)) => {
                let namespace_matches = value_ns.eq_ignore_ascii_case(target_ns);

                // Allow FHIR/System cross-matching for specific types:
                // 1. Complex types like Quantity, Date, DateTime, Time (always allowed)
                // 2. Primitive types like boolean, string, integer, decimal (only for ofType operations when allow_cross_namespace is true)
                // 3. Resource types (checked dynamically)
                // Check if it's a complex type or a Quantity subtype
                let value_type_lower = value_type.to_lowercase();
                let is_complex_type = matches!(
                    value_type_lower.as_str(),
                    "quantity" | "date" | "datetime" | "time"
                );

                // Also check if it's a Quantity subtype (Age, Distance, Duration, Count)
                let is_quantity_subtype = matches!(
                    value_type_lower.as_str(),
                    "age" | "distance" | "duration" | "count"
                ) && target_type.eq_ignore_ascii_case("quantity");

                // Only allow cross-namespace matching for primitive types when explicitly enabled (for ofType operations)
                // FHIR.boolean should match the type specifier "boolean" only in ofType, not in is operations
                let is_primitive_type = allow_cross_namespace
                    && matches!(
                        value_type.to_lowercase().as_str(),
                        "boolean"
                            | "string"
                            | "integer"
                            | "decimal"
                            | "date"
                            | "datetime"
                            | "time"
                            | "instant"
                            | "id"
                            | "oid"
                            | "url"
                            | "uuid"
                            | "uri"
                            | "canonical"
                            | "code"
                            | "markdown"
                            | "base64binary"
                            | "positiveint"
                            | "unsignedint"
                    );

                let is_cross_matchable_type =
                    is_complex_type || is_primitive_type || is_quantity_subtype;

                let cross_namespace_match = is_cross_matchable_type
                    && ((value_ns.eq_ignore_ascii_case("FHIR")
                        && target_ns.eq_ignore_ascii_case("System"))
                        || (value_ns.eq_ignore_ascii_case("System")
                            && target_ns.eq_ignore_ascii_case("FHIR")));

                Ok(namespace_matches || cross_namespace_match)
            }
            (None, Some(_)) => {
                // Value has no namespace but target does - no match
                Ok(false)
            }
            _ => Ok(type_matches), // This case is already handled above
        }
    } else {
        Ok(false)
    }
}

/// Extract namespace and type name from a TypeSpecifier with context-aware resource checking
/// Handles qualified names like "System.Boolean" or "FHIR.Patient"
/// including backtick-quoted variants
pub fn extract_namespace_and_type_with_context(
    type_spec: &TypeSpecifier,
    context: &EvaluationContext,
) -> Result<(Option<String>, String), EvaluationError> {
    match type_spec {
        // Handle explicitly qualified types like FHIR.Patient in the AST
        // The parser should have already cleaned up backticks in both parts
        TypeSpecifier::QualifiedIdentifier(ns, Some(name)) => {
            // Clean the namespace and name
            let clean_name = clean_identifier(name);
            let clean_ns = clean_identifier(ns);

            // Special handling for multi-part namespaces (e.g. System.Collections.List)
            if clean_ns.contains('.') {
                // For our current qualified type checks, we only need the main namespace
                // (System, FHIR, etc.) and don't need to further split multi-part namespaces
                let primary_ns = clean_ns.split('.').next().unwrap_or(&clean_ns).to_string();

                // For now, we'll treat complex namespaces as just their first part
                // This simplifies handling System.Collections.List.Item vs System.Boolean
                return Ok((Some(primary_ns), clean_name));
            }

            // Normalize namespace casing for standard namespaces
            let normalized_ns = match clean_ns.to_lowercase().as_str() {
                "system" => "System".to_string(),
                "fhir" => "FHIR".to_string(),
                _ => clean_ns,
            };

            Ok((Some(normalized_ns), clean_name))
        }

        // Handle plain identifiers - these might be:
        // 1. Simple types like "Boolean"
        // 2. Already-qualified types like "System.Boolean" that need parsing
        TypeSpecifier::QualifiedIdentifier(name, _) => {
            // Clean the identifier
            let clean_name = clean_identifier(name);

            // Check if this is a dot-separated qualified name like "System.Boolean"
            if clean_name.contains('.') {
                let parts: Vec<&str> = clean_name.split('.').collect();

                if parts.len() >= 2 {
                    // Get namespace (first part) and type name (last part)
                    // For multi-part qualifiers like System.Collections.List,
                    // we'll consider only the first part as the primary namespace
                    let raw_namespace = parts[0].to_string();
                    let type_name = parts[parts.len() - 1].to_string();

                    // Normalize namespace casing for standard namespaces
                    let normalized_ns = match raw_namespace.to_lowercase().as_str() {
                        "system" => "System".to_string(),
                        "fhir" => "FHIR".to_string(),
                        _ => raw_namespace,
                    };

                    // Return namespace and clean type name
                    return Ok((Some(normalized_ns), clean_identifier(&type_name)));
                }
            }

            // Improved detection of type names with context-aware resource checking

            // First check for System types (with capitalized first letter)
            let first_char = clean_name.chars().next().unwrap_or('_');
            let is_likely_system_type = first_char.is_uppercase();

            // Known System primitive types
            let system_primitives = [
                "Boolean", "String", "Integer", "Decimal", "Date", "DateTime", "Time", "Quantity",
            ];

            // Known FHIR primitive types (lowercase)
            let fhir_primitives = [
                "boolean",
                "string",
                "integer",
                "decimal",
                "date",
                "dateTime",
                "time",
                "code",
                "id",
                "uri",
                "url",
                "canonical",
                "markdown",
                "base64Binary",
                "instant",
                "positiveInt",
                "unsignedInt",
                "uuid",
            ];

            // Check type based on capitalization to determine intended namespace
            if is_likely_system_type {
                // Capitalized names likely intended for System namespace
                if system_primitives
                    .iter()
                    .any(|&t| t.eq_ignore_ascii_case(&clean_name))
                {
                    return Ok((Some("System".to_string()), clean_name.clone()));
                }
            } else {
                // Lowercase names likely intended for FHIR namespace
                if fhir_primitives
                    .iter()
                    .any(|&t| t.eq_ignore_ascii_case(&clean_name))
                {
                    return Ok((Some("FHIR".to_string()), clean_name.to_lowercase()));
                }
            }

            // Fallback: check if it matches any primitive type regardless of case preference
            if system_primitives
                .iter()
                .any(|&t| t.eq_ignore_ascii_case(&clean_name))
            {
                // When using "is(Boolean)" or "is(Integer)", normalize to System.X
                let normalized_type = if is_likely_system_type {
                    // Keep original capitalization for System types
                    clean_name.clone()
                } else {
                    // Capitalize first letter for System types
                    capitalize_first_letter(&clean_name)
                };

                Ok((Some("System".to_string()), normalized_type))
            } else if fhir_primitives
                .iter()
                .any(|&t| t.eq_ignore_ascii_case(&clean_name))
            {
                // FHIR primitive types are conventionally lowercase
                let normalized_type = if is_likely_system_type {
                    // If capitalized, it might be a System type
                    clean_name.clone()
                } else {
                    // Otherwise keep lowercase for FHIR primitive
                    clean_name.to_lowercase()
                };

                Ok((Some("FHIR".to_string()), normalized_type))
            }
            // Use context-aware resource checking
            else if is_resource_type_for_version(&clean_name, &context.fhir_version) {
                // Resource types default to FHIR namespace
                Ok((
                    Some("FHIR".to_string()),
                    capitalize_first_letter(&clean_name),
                ))
            }
            // Check for complex types
            else if is_complex_type_for_version(&clean_name, &context.fhir_version) {
                // Complex types default to FHIR namespace
                Ok((
                    Some("FHIR".to_string()),
                    capitalize_first_letter(&clean_name),
                ))
            }
            // For unknown types, validate them
            else if !is_valid_type_name(&clean_name, &context.fhir_version) {
                // Unknown type - this should throw an error
                Err(EvaluationError::InvalidTypeSpecifier(format!(
                    "The type '{}' is unknown",
                    clean_name
                )))
            } else if is_likely_system_type {
                // Capitalized types are likely System types
                Ok((Some("System".to_string()), clean_name))
            } else {
                // Lowercase types are likely FHIR types
                Ok((Some("FHIR".to_string()), clean_name))
            }
        }
    }
}

/// Validates if a type name is a known primitive type (without version context)
fn is_primitive_type(type_name: &str) -> bool {
    // Known System primitive types
    let system_primitives = [
        "Boolean", "String", "Integer", "Decimal", "Date", "DateTime", "Time", "Quantity",
        "boolean", "string", "integer", "decimal", "date", "datetime", "time", "quantity",
    ];

    // Check against System primitives
    if system_primitives
        .iter()
        .any(|&t| t.eq_ignore_ascii_case(type_name))
    {
        return true;
    }

    // Check against FHIR primitives using the existing function
    is_fhir_primitive_type(type_name)
}

/// Validates if a type name is valid in the FHIR/System type system
fn is_valid_type_name(type_name: &str, fhir_version: &FhirVersion) -> bool {
    // Check the common types first (primitives)
    if is_primitive_type(type_name) {
        return true;
    }

    // Check if it's a valid resource type
    if is_resource_type_for_version(type_name, fhir_version) {
        return true;
    }

    // Check if it's a valid complex type
    is_complex_type_for_version(type_name, fhir_version)
}

/// Checks if a given suffix is a valid FHIR type suffix for polymorphic fields
///
/// This function checks if a suffix (like "Quantity", "CodeableConcept", etc.) is a valid
/// FHIR type that could be used as a suffix in polymorphic fields. It leverages the existing
/// type checking infrastructure rather than hard-coding type names.
///
/// # Arguments
///
/// * `suffix` - The type suffix to check (e.g., "Quantity", "CodeableConcept")
/// * `fhir_version` - The FHIR version to check against
///
/// # Returns
///
/// * `true` if the suffix is a valid FHIR type that could be used in polymorphic fields
pub fn is_valid_fhir_type_suffix(suffix: &str, fhir_version: &FhirVersion) -> bool {
    // First check if it's a primitive type (these can be suffixes)
    if is_fhir_primitive_type(suffix) {
        return true;
    }

    // Check if it's a complex type (these are commonly used as suffixes)
    if is_complex_type_for_version(suffix, fhir_version) {
        return true;
    }

    // Special case: SimpleQuantity is not a separate type but a profiled Quantity
    // It's commonly used as a suffix in polymorphic fields (e.g., doseSimpleQuantity)
    if suffix.eq_ignore_ascii_case("SimpleQuantity") {
        return true;
    }

    false
}

/// Extract namespace and type name from a TypeSpecifier (version without context)
/// Handles qualified names like "System.Boolean" or "FHIR.Patient"
/// including backtick-quoted variants
/// Note: This version cannot validate resource/complex types without FHIR version context
#[allow(dead_code)]
pub fn extract_namespace_and_type_without_context(
    type_spec: &TypeSpecifier,
) -> Result<(Option<String>, String), EvaluationError> {
    match type_spec {
        // Handle explicitly qualified types like FHIR.Patient in the AST
        // The parser should have already cleaned up backticks in both parts
        TypeSpecifier::QualifiedIdentifier(ns, Some(name)) => {
            // Clean the namespace and name
            let clean_name = clean_identifier(name);
            let clean_ns = clean_identifier(ns);

            // Special handling for multi-part namespaces (e.g. System.Collections.List)
            if clean_ns.contains('.') {
                // For our current qualified type checks, we only need the main namespace
                // (System, FHIR, etc.) and don't need to further split multi-part namespaces
                let primary_ns = clean_ns.split('.').next().unwrap_or(&clean_ns).to_string();

                // For now, we'll treat complex namespaces as just their first part
                // This simplifies handling System.Collections.List.Item vs System.Boolean
                return Ok((Some(primary_ns), clean_name));
            }

            // Normalize namespace casing for standard namespaces
            let normalized_ns = match clean_ns.to_lowercase().as_str() {
                "system" => "System".to_string(),
                "fhir" => "FHIR".to_string(),
                _ => clean_ns,
            };

            Ok((Some(normalized_ns), clean_name))
        }

        // Handle plain identifiers - these might be:
        // 1. Simple types like "Boolean"
        // 2. Already-qualified types like "System.Boolean" that need parsing
        TypeSpecifier::QualifiedIdentifier(name, _) => {
            // Clean the identifier
            let clean_name = clean_identifier(name);

            // Check if this is a dot-separated qualified name like "System.Boolean"
            if clean_name.contains('.') {
                let parts: Vec<&str> = clean_name.split('.').collect();

                if parts.len() >= 2 {
                    // Get namespace (first part) and type name (last part)
                    // For multi-part qualifiers like System.Collections.List,
                    // we'll consider only the first part as the primary namespace
                    let raw_namespace = parts[0].to_string();
                    let type_name = parts[parts.len() - 1].to_string();

                    // Normalize namespace casing for standard namespaces
                    let normalized_ns = match raw_namespace.to_lowercase().as_str() {
                        "system" => "System".to_string(),
                        "fhir" => "FHIR".to_string(),
                        _ => raw_namespace,
                    };

                    // Return namespace and clean type name
                    return Ok((Some(normalized_ns), clean_identifier(&type_name)));
                }
            }

            // Improved detection of type names with more accurate namespace detection

            // First check for System types (with capitalized first letter)
            let first_char = clean_name.chars().next().unwrap_or('_');
            let is_likely_system_type = first_char.is_uppercase();

            // Known System primitive types
            let system_primitives = [
                "Boolean", "String", "Integer", "Decimal", "Date", "DateTime", "Time", "Quantity",
            ];

            // Known FHIR primitive types (lowercase)
            let fhir_primitives = [
                "boolean",
                "string",
                "integer",
                "decimal",
                "date",
                "dateTime",
                "time",
                "code",
                "id",
                "uri",
                "url",
                "canonical",
                "markdown",
                "base64Binary",
                "instant",
                "positiveInt",
                "unsignedInt",
                "uuid",
            ];

            // Note: Without context, we cannot check against version-specific resource/complex types
            // This legacy function relies on primitive type checking and basic heuristics

            // Check if the clean_name is a known System primitive type
            if system_primitives
                .iter()
                .any(|&t| t.eq_ignore_ascii_case(&clean_name))
            {
                // When using "is(Boolean)" or "is(Integer)", normalize to System.X
                let normalized_type = if is_likely_system_type {
                    // Keep original capitalization for System types
                    clean_name.clone()
                } else {
                    // Capitalize first letter for System types
                    capitalize_first_letter(&clean_name)
                };

                Ok((Some("System".to_string()), normalized_type))
            }
            // Check if the clean_name is a known FHIR primitive type
            else if fhir_primitives
                .iter()
                .any(|&t| t.eq_ignore_ascii_case(&clean_name))
            {
                // FHIR primitive types are conventionally lowercase
                let normalized_type = if is_likely_system_type {
                    // If capitalized, it might be a System type
                    clean_name.clone()
                } else {
                    // Otherwise keep lowercase for FHIR primitive
                    clean_name.to_lowercase()
                };

                Ok((Some("FHIR".to_string()), normalized_type))
            }
            // For non-primitive types, make an educated guess
            // But reject obviously invalid types (lowercase non-primitives that look like typos)
            else if !is_likely_system_type && clean_name.chars().any(|c| c.is_ascii_digit()) {
                // Types with digits that aren't primitives are likely invalid (e.g., "string1")
                Err(EvaluationError::InvalidTypeSpecifier(format!(
                    "The type '{}' is unknown",
                    clean_name
                )))
            } else if is_likely_system_type {
                // Capitalized types are likely System types
                Ok((Some("System".to_string()), clean_name))
            } else {
                // Lowercase types are likely FHIR types
                Ok((Some("FHIR".to_string()), clean_name))
            }
        }
    }
}

// Using capitalize_first_letter from fhir_type_hierarchy instead

/// Helper function to clean up backtick-quoted identifiers
fn clean_identifier(ident: &str) -> String {
    if ident.starts_with('`') && ident.ends_with('`') && ident.len() > 2 {
        ident[1..ident.len() - 1].to_string()
    } else {
        ident.to_string()
    }
}

/// Determines if a FHIR resource type is a DomainResource for the given FHIR version
///
/// This delegates to the macro-generated `type_hierarchy` module emitted into each
/// version's model file, which records every type's `baseDefinition` parent. A type
/// is a `DomainResource` if walking its parent chain reaches `DomainResource`
/// (true for almost all resources; `Binary`, `Bundle`, and `Parameters` derive
/// directly from `Resource` and are therefore not DomainResources).
pub fn is_fhir_domain_resource_for_version(
    resource_type: &str,
    fhir_version: &FhirVersion,
) -> bool {
    match fhir_version {
        #[cfg(feature = "R4")]
        FhirVersion::R4 => {
            helios_fhir::r4::type_hierarchy::is_subtype_of(resource_type, "DomainResource")
        }
        #[cfg(feature = "R4B")]
        FhirVersion::R4B => {
            helios_fhir::r4b::type_hierarchy::is_subtype_of(resource_type, "DomainResource")
        }
        #[cfg(feature = "R5")]
        FhirVersion::R5 => {
            helios_fhir::r5::type_hierarchy::is_subtype_of(resource_type, "DomainResource")
        }
        #[cfg(feature = "R6")]
        FhirVersion::R6 => {
            helios_fhir::r6::type_hierarchy::is_subtype_of(resource_type, "DomainResource")
        }
        #[allow(unreachable_patterns)]
        _ => false, // For versions not enabled by feature flags
    }
}

/// Determines if a FHIR resource type is a DomainResource.
///
/// Version-agnostic convenience wrapper around [`is_fhir_domain_resource_for_version`].
/// Returns `true` if the type is a DomainResource in any enabled FHIR version.
/// DomainResource membership is consistent across versions, so checking the enabled
/// versions in turn is sufficient and avoids requiring callers to thread a version
/// through type-checking code paths that don't have one.
pub fn is_fhir_domain_resource(resource_type: &str) -> bool {
    FhirVersion::enabled_versions()
        .iter()
        .any(|version| is_fhir_domain_resource_for_version(resource_type, version))
}

// is_fhir_type and is_system_type were removed as they were never used and
// their functionality has been incorporated into is_of_type and other functions

/// Attempts to cast a value to a specific type
///
/// # Arguments
///
/// * `value` - The value to cast
/// * `type_spec` - The type to cast to
///
/// # Returns
///
/// * The value as the specified type if possible, or Empty if not
#[allow(dead_code)]
pub fn as_type(
    value: &EvaluationResult,
    type_spec: &TypeSpecifier,
) -> Result<EvaluationResult, EvaluationError> {
    // Check if the value is of the specified type
    if is_of_type(value, type_spec)? {
        // If it matches, return the value as-is
        Ok(value.clone())
    } else {
        // If it doesn't match, return Empty
        Ok(EvaluationResult::Empty)
    }
}

/// Casts a value to a specified type if it matches (context-aware version)
///
/// # Arguments
///
/// * `value` - The value to cast
/// * `type_spec` - The type specifier to cast to
/// * `context` - The evaluation context containing FHIR version information
///
/// # Returns
///
/// * The original value if it matches the type, Empty otherwise
pub fn as_type_with_context(
    value: &EvaluationResult,
    type_spec: &TypeSpecifier,
    context: &EvaluationContext,
) -> Result<EvaluationResult, EvaluationError> {
    // Check if the value is of the specified type using context-aware version
    if is_of_type_with_context(value, type_spec, context)? {
        // If it matches, return the value as-is
        Ok(value.clone())
    } else {
        // If it doesn't match, return Empty
        Ok(EvaluationResult::Empty)
    }
}

/// Helper function to try converting a value to a target type for ofType operations
#[allow(dead_code)]
fn try_convert_for_of_type(
    value: &EvaluationResult,
    type_spec: &TypeSpecifier,
) -> Result<Option<EvaluationResult>, EvaluationError> {
    let (_target_namespace, target_type) = extract_namespace_and_type_without_context(type_spec)?;

    match value {
        EvaluationResult::String(s, type_info, _) => {
            // Check if this is a FHIR string that might represent a different type
            if let Some(type_info) = type_info {
                if type_info.namespace == "FHIR" && type_info.name == "string" {
                    // Try to convert FHIR strings to target types
                    match target_type.to_lowercase().as_str() {
                        "datetime" => {
                            // Only convert to datetime if it looks like a date or datetime, not a time
                            if s.len() == 10
                                && s.chars().nth(4) == Some('-')
                                && s.chars().nth(7) == Some('-')
                            {
                                // This is a date string like "2010-10-10", convert to DateTime
                                Ok(Some(EvaluationResult::datetime(s.clone())))
                            } else if s.contains('T') || s.len() > 10 {
                                // This looks like a full datetime string
                                Ok(Some(EvaluationResult::datetime(s.clone())))
                            } else {
                                // Don't convert time-only strings to datetime
                                Ok(None)
                            }
                        }
                        "time" => {
                            // Try to parse as time
                            if s.contains(':') {
                                Ok(Some(EvaluationResult::time(s.clone())))
                            } else {
                                Ok(None)
                            }
                        }
                        "date" => {
                            // Try to parse as date
                            if s.len() >= 7 && s.chars().nth(4) == Some('-') {
                                Ok(Some(EvaluationResult::date(s.clone())))
                            } else {
                                Ok(None)
                            }
                        }
                        "instant" => {
                            // Try to parse as instant (must have timezone)
                            if s.contains('T')
                                && (s.contains('+') || s.contains('-') || s.ends_with('Z'))
                            {
                                Ok(Some(EvaluationResult::fhir_string(s.clone(), "instant")))
                            } else {
                                Ok(None)
                            }
                        }
                        "id" => {
                            // Only convert simple strings to ID, not URLs or other special formats
                            if s.starts_with("http://")
                                || s.starts_with("https://")
                                || s.starts_with("urn:")
                            {
                                // These look like URLs, URIs, OIDs, UUIDs - not simple IDs
                                Ok(None)
                            } else {
                                // Simple string values can be IDs
                                Ok(Some(EvaluationResult::fhir_string(s.clone(), "id")))
                            }
                        }
                        "oid" => {
                            // OID strings start with "urn:oid:"
                            if s.starts_with("urn:oid:") {
                                Ok(Some(EvaluationResult::fhir_string(s.clone(), "oid")))
                            } else {
                                Ok(None)
                            }
                        }
                        "url" => {
                            // URL strings typically start with "http://" or "https://"
                            if s.starts_with("http://") || s.starts_with("https://") {
                                Ok(Some(EvaluationResult::fhir_string(s.clone(), "url")))
                            } else {
                                Ok(None)
                            }
                        }
                        "uuid" => {
                            // UUID strings start with "urn:uuid:"
                            if s.starts_with("urn:uuid:") {
                                Ok(Some(EvaluationResult::fhir_string(s.clone(), "uuid")))
                            } else {
                                Ok(None)
                            }
                        }
                        "uri" => {
                            // URI strings can be various formats
                            if s.starts_with("urn:")
                                || s.starts_with("http://")
                                || s.starts_with("https://")
                            {
                                Ok(Some(EvaluationResult::fhir_string(s.clone(), "uri")))
                            } else {
                                Ok(None)
                            }
                        }
                        "canonical" => {
                            // Canonical URIs are similar to URIs
                            if s.starts_with("http://") || s.starts_with("https://") {
                                Ok(Some(EvaluationResult::fhir_string(s.clone(), "canonical")))
                            } else {
                                Ok(None)
                            }
                        }
                        "code" => {
                            // Simple string values can be codes
                            Ok(Some(EvaluationResult::fhir_string(s.clone(), "code")))
                        }
                        "markdown" => {
                            // Any string can be markdown
                            Ok(Some(EvaluationResult::fhir_string(s.clone(), "markdown")))
                        }
                        "base64binary" => {
                            // Base64 encoded strings
                            Ok(Some(EvaluationResult::fhir_string(
                                s.clone(),
                                "base64Binary",
                            )))
                        }
                        _ => Ok(None),
                    }
                } else {
                    Ok(None)
                }
            } else {
                Ok(None)
            }
        }
        _ => Ok(None),
    }
}

/// Filters a collection based on a type specifier (context-aware version)
///
/// # Arguments
///
/// * `collection` - The collection to filter
/// * `type_spec` - The type to filter by
/// * `context` - The evaluation context containing FHIR version information
///
/// # Returns
///
/// * A new collection containing only items of the specified type
/// * If there's only one item in the collection, returns that item directly (unwrapped)
/// * If the collection is empty, returns Empty
pub fn of_type_with_context(
    collection: &EvaluationResult,
    type_spec: &TypeSpecifier,
    context: &EvaluationContext,
) -> Result<EvaluationResult, EvaluationError> {
    // Use a consistent helper function for applying the type filter
    let apply_type_filter =
        |items: &[EvaluationResult]| -> Result<EvaluationResult, EvaluationError> {
            let mut result = Vec::new();

            for item in items {
                // Use context-aware type checking
                if is_of_type_with_context(item, type_spec, context)? {
                    result.push(item.clone());
                }
                // Note: try_convert_for_of_type uses the without-context version
                // which can't validate complex types, so we skip it for now
            }

            if result.is_empty() {
                Ok(EvaluationResult::Empty)
            } else if result.len() == 1 {
                Ok(result[0].clone())
            } else {
                // ofType preserves the order of the input collection
                let input_was_unordered = matches!(
                    collection,
                    EvaluationResult::Collection {
                        has_undefined_order: true,
                        ..
                    }
                );
                Ok(EvaluationResult::Collection {
                    items: result,
                    has_undefined_order: input_was_unordered,
                    type_info: None,
                })
            }
        };

    match collection {
        EvaluationResult::Collection { items, .. } => apply_type_filter(items), // Destructure
        EvaluationResult::Empty => Ok(EvaluationResult::Empty),

        // For a singleton value, treat it like a collection of one
        _ => {
            if is_of_type_with_context(collection, type_spec, context)? {
                // Return the value directly for a singleton that matches
                Ok(collection.clone())
            } else {
                Ok(EvaluationResult::Empty)
            }
        }
    }
}

/// Filters a collection based on a type specifier (version without context)
/// This version is deprecated - use of_type_with_context instead
#[allow(dead_code)]
pub fn of_type(
    collection: &EvaluationResult,
    type_spec: &TypeSpecifier,
) -> Result<EvaluationResult, EvaluationError> {
    // Use a consistent helper function for applying the type filter
    let apply_type_filter =
        |items: &[EvaluationResult]| -> Result<EvaluationResult, EvaluationError> {
            let mut result = Vec::new();

            for item in items {
                if is_of_type_for_of_type(item, type_spec)? {
                    result.push(item.clone());
                } else if let Some(converted) = try_convert_for_of_type(item, type_spec)? {
                    result.push(converted);
                }
            }

            if result.is_empty() {
                Ok(EvaluationResult::Empty)
            } else if result.len() == 1 {
                Ok(result[0].clone())
            } else {
                // ofType preserves the order of the input collection
                let input_was_unordered = matches!(
                    collection,
                    EvaluationResult::Collection {
                        has_undefined_order: true,
                        ..
                    }
                );
                Ok(EvaluationResult::Collection {
                    items: result,
                    has_undefined_order: input_was_unordered,
                    type_info: None,
                })
            }
        };

    match collection {
        EvaluationResult::Collection { items, .. } => apply_type_filter(items), // Destructure
        EvaluationResult::Empty => Ok(EvaluationResult::Empty),

        // For a singleton value, treat it like a collection of one
        _ => {
            if is_of_type_for_of_type(collection, type_spec)? {
                // Return the value directly for a singleton that matches
                Ok(collection.clone())
            } else if let Some(converted) = try_convert_for_of_type(collection, type_spec)? {
                Ok(converted)
            } else {
                Ok(EvaluationResult::Empty)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::HashMap;
    use std::str::FromStr;

    // Helper function to create a FHIR Patient resource
    fn create_patient() -> EvaluationResult {
        let mut patient = HashMap::new();
        patient.insert(
            "resourceType".to_string(),
            EvaluationResult::string("Patient".to_string()),
        );
        patient.insert(
            "id".to_string(),
            EvaluationResult::string("123".to_string()),
        );
        patient.insert("active".to_string(), EvaluationResult::boolean(true));

        // Add a name
        let mut name = HashMap::new();
        name.insert(
            "use".to_string(),
            EvaluationResult::string("official".to_string()),
        );
        name.insert(
            "family".to_string(),
            EvaluationResult::string("Smith".to_string()),
        );

        let given = vec![
            EvaluationResult::string("John".to_string()),
            EvaluationResult::string("Q".to_string()),
        ];
        name.insert(
            "given".to_string(),
            EvaluationResult::Collection {
                items: given,
                has_undefined_order: false,
                type_info: None,
            },
        );

        let names = vec![EvaluationResult::Object {
            map: name,
            type_info: None,
        }];
        patient.insert(
            "name".to_string(),
            EvaluationResult::Collection {
                items: names,
                has_undefined_order: false,
                type_info: None,
            },
        );

        // Add birthDate
        patient.insert(
            "birthDate".to_string(),
            EvaluationResult::string("1974-12-25".to_string()),
        );

        EvaluationResult::Object {
            map: patient,
            type_info: None,
        }
    }

    // Helper function to create a FHIR Observation resource with a valueQuantity
    fn create_observation() -> EvaluationResult {
        let mut obs = HashMap::new();
        obs.insert(
            "resourceType".to_string(),
            EvaluationResult::string("Observation".to_string()),
        );
        obs.insert(
            "id".to_string(),
            EvaluationResult::string("456".to_string()),
        );
        obs.insert(
            "status".to_string(),
            EvaluationResult::string("final".to_string()),
        );

        // Add valueQuantity
        let mut quantity = HashMap::new();
        quantity.insert(
            "value".to_string(),
            EvaluationResult::decimal(rust_decimal::Decimal::from(185)),
        );
        quantity.insert(
            "unit".to_string(),
            EvaluationResult::string("lbs".to_string()),
        );
        quantity.insert(
            "system".to_string(),
            EvaluationResult::string("http://unitsofmeasure.org".to_string()),
        );
        quantity.insert(
            "code".to_string(),
            EvaluationResult::string("lb_av".to_string()),
        );

        obs.insert(
            "valueQuantity".to_string(),
            EvaluationResult::Object {
                map: quantity,
                type_info: None,
            },
        );

        EvaluationResult::Object {
            map: obs,
            type_info: None,
        }
    }

    #[test]
    fn test_is_of_type_system_types() {
        // Test System types
        let bool_val = EvaluationResult::boolean(true);
        let int_val = EvaluationResult::integer(42);
        let dec_val = EvaluationResult::decimal(rust_decimal::Decimal::from_str("3.14").unwrap());
        let str_val = EvaluationResult::string("test".to_string());

        // Create type specifiers
        let bool_type = TypeSpecifier::QualifiedIdentifier("Boolean".to_string(), None);
        let int_type = TypeSpecifier::QualifiedIdentifier("Integer".to_string(), None);
        let dec_type = TypeSpecifier::QualifiedIdentifier("Decimal".to_string(), None);
        let str_type = TypeSpecifier::QualifiedIdentifier("String".to_string(), None);

        // Test correct matches
        assert!(is_of_type(&bool_val, &bool_type).unwrap());
        assert!(is_of_type(&int_val, &int_type).unwrap());
        assert!(is_of_type(&dec_val, &dec_type).unwrap());
        assert!(is_of_type(&str_val, &str_type).unwrap());

        // Test incorrect matches
        assert!(!is_of_type(&bool_val, &int_type).unwrap());
        assert!(!is_of_type(&int_val, &str_type).unwrap());
        assert!(!is_of_type(&dec_val, &bool_type).unwrap());
        assert!(!is_of_type(&str_val, &dec_type).unwrap());
    }

    #[test]
    fn test_is_of_type_fhir_resources() {
        // Create FHIR resources
        let patient = create_patient();
        let observation = create_observation();

        // Print the patient object for debugging
        if let EvaluationResult::Object {
            map: obj,
            type_info: None,
        } = &patient
        {
            eprintln!("Patient object:");
            for (key, value) in obj {
                eprintln!("  {}: {:?}", key, value);
            }
        }

        // Create type specifiers with exact case matching the resourceType property
        // Since Patient is a FHIR resource, we need to specify the FHIR namespace
        let patient_type =
            TypeSpecifier::QualifiedIdentifier("FHIR".to_string(), Some("Patient".to_string()));

        // Print the type specifier for debugging
        eprintln!("Patient type: {:?}", patient_type);

        let is_result = is_of_type(&patient, &patient_type);
        eprintln!("is_of_type result: {:?}", is_result);

        // Test correct matches
        assert!(is_result.unwrap());

        // Create the rest of the type specifiers
        let obs_type =
            TypeSpecifier::QualifiedIdentifier("FHIR".to_string(), Some("Observation".to_string()));
        let fhir_patient_type =
            TypeSpecifier::QualifiedIdentifier("FHIR".to_string(), Some("Patient".to_string()));

        assert!(is_of_type(&observation, &obs_type).unwrap());
        assert!(is_of_type(&patient, &fhir_patient_type).unwrap());

        // Test with different casing (should still work with case-insensitive comparison)
        let patient_type_lowercase =
            TypeSpecifier::QualifiedIdentifier("fhir".to_string(), Some("patient".to_string()));
        assert!(is_of_type(&patient, &patient_type_lowercase).unwrap());

        // Test incorrect matches
        assert!(!is_of_type(&patient, &obs_type).unwrap());
        assert!(!is_of_type(&observation, &patient_type).unwrap());
    }

    #[test]
    fn test_as_type() {
        // Create test values
        let bool_val = EvaluationResult::boolean(true);
        let patient = create_patient();
        let observation = create_observation();

        // Create type specifiers with exact case matching the resourceType property
        let bool_type = TypeSpecifier::QualifiedIdentifier("Boolean".to_string(), None);
        let patient_type =
            TypeSpecifier::QualifiedIdentifier("FHIR".to_string(), Some("Patient".to_string()));
        let obs_type =
            TypeSpecifier::QualifiedIdentifier("FHIR".to_string(), Some("Observation".to_string()));

        // Test correct casts
        assert_eq!(as_type(&bool_val, &bool_type).unwrap(), bool_val);
        assert_eq!(as_type(&patient, &patient_type).unwrap(), patient);
        assert_eq!(as_type(&observation, &obs_type).unwrap(), observation);

        // Test with different casing (should still work)
        let patient_type_lowercase =
            TypeSpecifier::QualifiedIdentifier("fhir".to_string(), Some("patient".to_string()));
        assert_eq!(as_type(&patient, &patient_type_lowercase).unwrap(), patient);

        // Test incorrect casts
        assert_eq!(
            as_type(&bool_val, &patient_type).unwrap(),
            EvaluationResult::Empty
        );
        assert_eq!(
            as_type(&patient, &bool_type).unwrap(),
            EvaluationResult::Empty
        );
        assert_eq!(
            as_type(&observation, &patient_type).unwrap(),
            EvaluationResult::Empty
        );
    }

    #[test]
    fn test_of_type() {
        // Create a collection with mixed types
        let collection = EvaluationResult::Collection {
            items: vec![
                EvaluationResult::boolean(true),
                EvaluationResult::integer(42),
                EvaluationResult::boolean(false),
                EvaluationResult::string("test".to_string()),
            ],
            has_undefined_order: false,
            type_info: None,
        };

        // Create type specifiers
        let bool_type = TypeSpecifier::QualifiedIdentifier("Boolean".to_string(), None);
        let int_type = TypeSpecifier::QualifiedIdentifier("Integer".to_string(), None);
        let str_type = TypeSpecifier::QualifiedIdentifier("String".to_string(), None);

        // Test filtering with multiple matches - should return a collection
        let collection_with_only_booleans = EvaluationResult::Collection {
            items: vec![
                EvaluationResult::boolean(true),
                EvaluationResult::boolean(false),
            ],
            has_undefined_order: false,
            type_info: None,
        };
        let bool_result = of_type(&collection, &bool_type).unwrap();
        assert_eq!(bool_result, collection_with_only_booleans);

        // Test filtering with single match - should return the single item directly
        let int_result = of_type(&collection, &int_type).unwrap();
        assert_eq!(int_result, EvaluationResult::integer(42));

        // Test another single match
        let str_result = of_type(&collection, &str_type).unwrap();
        assert_eq!(str_result, EvaluationResult::string("test".to_string()));

        // Test with no matches
        let decimal_type = TypeSpecifier::QualifiedIdentifier("Decimal".to_string(), None);
        let decimal_result = of_type(&collection, &decimal_type).unwrap();
        assert_eq!(decimal_result, EvaluationResult::Empty);
    }
}