posthog-rs 0.6.0

The official Rust client for Posthog (https://posthog.com/).
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
use chrono::{DateTime, NaiveDate, Utc};
use regex::Regex;
use serde::{Deserialize, Serialize};
use sha1::{Digest, Sha1};
use std::collections::HashMap;
use std::fmt;
use std::sync::{Mutex, OnceLock};

/// Global cache for compiled regexes to avoid recompilation on every flag evaluation
static REGEX_CACHE: OnceLock<Mutex<HashMap<String, Option<Regex>>>> = OnceLock::new();

/// Salt used for rollout percentage hashing. Intentionally empty to match PostHog's
/// consistent hashing algorithm across all SDKs. This ensures the same user gets
/// the same rollout decision regardless of which SDK evaluates the flag.
const ROLLOUT_HASH_SALT: &str = "";

/// Salt used for multivariate variant selection. Uses "variant" to ensure consistent
/// variant assignment across all PostHog SDKs for the same user/flag combination.
const VARIANT_HASH_SALT: &str = "variant";

fn get_cached_regex(pattern: &str) -> Option<Regex> {
    let cache = REGEX_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
    let mut cache_guard = match cache.lock() {
        Ok(guard) => guard,
        Err(_) => {
            tracing::warn!(
                pattern,
                "Regex cache mutex poisoned, treating as cache miss"
            );
            return None;
        }
    };

    if let Some(cached) = cache_guard.get(pattern) {
        return cached.clone();
    }

    let compiled = Regex::new(pattern).ok();
    cache_guard.insert(pattern.to_string(), compiled.clone());
    compiled
}

/// The value of a feature flag evaluation.
///
/// Feature flags can return either a boolean (enabled/disabled) or a string
/// (for multivariate flags where users are assigned to different variants).
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum FlagValue {
    /// Flag is either enabled (true) or disabled (false)
    Boolean(bool),
    /// Flag returns a specific variant key (e.g., "control", "test", "variant-a")
    String(String),
}

/// Error returned when a feature flag cannot be evaluated locally.
///
/// This typically occurs when:
/// - Required person/group properties are missing
/// - A cohort referenced by the flag is not in the local cache
/// - A dependent flag is not available locally
/// - An unknown operator is encountered
#[derive(Debug)]
pub struct InconclusiveMatchError {
    /// Human-readable description of why evaluation was inconclusive
    pub message: String,
}

impl InconclusiveMatchError {
    pub fn new(message: &str) -> Self {
        Self {
            message: message.to_string(),
        }
    }
}

impl fmt::Display for InconclusiveMatchError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl std::error::Error for InconclusiveMatchError {}

impl Default for FlagValue {
    fn default() -> Self {
        FlagValue::Boolean(false)
    }
}

/// A feature flag definition from PostHog.
///
/// Contains all the information needed to evaluate whether a flag should be
/// enabled for a given user, including targeting rules and rollout percentages.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureFlag {
    /// Unique identifier for the flag (e.g., "new-checkout-flow")
    pub key: String,
    /// Whether the flag is currently active. Inactive flags always return false.
    pub active: bool,
    /// Targeting rules and rollout configuration
    #[serde(default)]
    pub filters: FeatureFlagFilters,
}

/// Targeting rules and configuration for a feature flag.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FeatureFlagFilters {
    /// List of condition groups (evaluated with OR logic between groups)
    #[serde(default)]
    pub groups: Vec<FeatureFlagCondition>,
    /// Multivariate configuration for A/B tests with multiple variants
    #[serde(default)]
    pub multivariate: Option<MultivariateFilter>,
    /// JSON payloads associated with flag variants
    #[serde(default)]
    pub payloads: HashMap<String, serde_json::Value>,
}

/// A single condition group within a feature flag's targeting rules.
///
/// All properties within a condition must match (AND logic), and the user
/// must fall within the rollout percentage to be included.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FeatureFlagCondition {
    /// Property filters that must all match (AND logic)
    #[serde(default)]
    pub properties: Vec<Property>,
    /// Percentage of matching users who should see this flag (0-100)
    pub rollout_percentage: Option<f64>,
    /// Specific variant to serve for this condition (for variant overrides)
    pub variant: Option<String>,
}

/// A property filter used in feature flag targeting.
///
/// Supports various operators for matching user properties against expected values.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Property {
    /// The property key to match (e.g., "email", "country", "$feature/other-flag")
    pub key: String,
    /// The value to compare against
    pub value: serde_json::Value,
    /// Comparison operator: "exact", "is_not", "icontains", "not_icontains",
    /// "regex", "not_regex", "gt", "gte", "lt", "lte", "is_set", "is_not_set",
    /// "is_date_before", "is_date_after"
    #[serde(default = "default_operator")]
    pub operator: String,
    /// Property type, e.g., "cohort" for cohort membership checks
    #[serde(rename = "type")]
    pub property_type: Option<String>,
}

fn default_operator() -> String {
    "exact".to_string()
}

/// Definition of a cohort for local evaluation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CohortDefinition {
    pub id: String,
    /// Properties can be either:
    /// - A JSON object with "type" and "values" for complex property groups
    /// - Or a direct Vec<Property> for simple cases
    #[serde(default)]
    pub properties: serde_json::Value,
}

impl CohortDefinition {
    /// Create a new cohort definition with simple property list
    pub fn new(id: String, properties: Vec<Property>) -> Self {
        Self {
            id,
            properties: serde_json::to_value(properties).unwrap_or_default(),
        }
    }

    /// Parse the properties from the JSON structure
    /// PostHog cohort properties come in format:
    /// {"type": "AND", "values": [{"type": "property", "key": "...", "value": "...", "operator": "..."}]}
    pub fn parse_properties(&self) -> Vec<Property> {
        // If it's an array, treat it as direct property list
        if let Some(arr) = self.properties.as_array() {
            return arr
                .iter()
                .filter_map(|v| serde_json::from_value::<Property>(v.clone()).ok())
                .collect();
        }

        // If it's an object with "values" key, extract properties from there
        if let Some(obj) = self.properties.as_object() {
            if let Some(values) = obj.get("values") {
                if let Some(values_arr) = values.as_array() {
                    return values_arr
                        .iter()
                        .filter_map(|v| {
                            // Handle both direct property objects and nested property groups
                            if v.get("type").and_then(|t| t.as_str()) == Some("property") {
                                serde_json::from_value::<Property>(v.clone()).ok()
                            } else if let Some(inner_values) = v.get("values") {
                                // Recursively handle nested groups
                                inner_values.as_array().and_then(|arr| {
                                    arr.iter()
                                        .filter_map(|inner| {
                                            serde_json::from_value::<Property>(inner.clone()).ok()
                                        })
                                        .next()
                                })
                            } else {
                                None
                            }
                        })
                        .collect();
                }
            }
        }

        Vec::new()
    }
}

/// Context for evaluating properties that may depend on cohorts or other flags
pub struct EvaluationContext<'a> {
    pub cohorts: &'a HashMap<String, CohortDefinition>,
    pub flags: &'a HashMap<String, FeatureFlag>,
    pub distinct_id: &'a str,
}

/// Configuration for multivariate (A/B/n) feature flags.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct MultivariateFilter {
    /// List of variants with their rollout percentages
    pub variants: Vec<MultivariateVariant>,
}

/// A single variant in a multivariate feature flag.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MultivariateVariant {
    /// Unique key for this variant (e.g., "control", "test", "variant-a")
    pub key: String,
    /// Percentage of users who should see this variant (0-100)
    pub rollout_percentage: f64,
}

/// Response from the PostHog feature flags API.
///
/// Supports both the v2 API format (with detailed flag information) and the
/// legacy format (simple flag values and payloads).
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum FeatureFlagsResponse {
    /// v2 API format from `/flags/?v=2` endpoint
    V2 {
        /// Map of flag keys to their detailed evaluation results
        flags: HashMap<String, FlagDetail>,
        /// Whether any errors occurred during flag computation
        #[serde(rename = "errorsWhileComputingFlags")]
        #[serde(default)]
        errors_while_computing_flags: bool,
        /// Whether the response was returned without evaluation because the
        /// project is over its feature-flag quota.
        #[serde(rename = "quotaLimited")]
        #[serde(default)]
        quota_limited: bool,
        /// Unique identifier for this evaluation request, propagated to
        /// `$feature_flag_called` events as `$feature_flag_request_id`
        /// for experiment exposure tracking.
        #[serde(rename = "requestId")]
        #[serde(default)]
        request_id: Option<String>,
    },
    /// Legacy format from older decide endpoint
    Legacy {
        /// Map of flag keys to their values
        #[serde(rename = "featureFlags")]
        feature_flags: HashMap<String, FlagValue>,
        /// Map of flag keys to their JSON payloads
        #[serde(rename = "featureFlagPayloads")]
        #[serde(default)]
        feature_flag_payloads: HashMap<String, serde_json::Value>,
        /// Any errors that occurred during evaluation
        #[serde(default)]
        errors: Option<Vec<String>>,
    },
}

impl FeatureFlagsResponse {
    /// Convert the response to a normalized format
    pub fn normalize(
        self,
    ) -> (
        HashMap<String, FlagValue>,
        HashMap<String, serde_json::Value>,
    ) {
        match self {
            FeatureFlagsResponse::V2 { flags, .. } => {
                let mut feature_flags = HashMap::new();
                let mut payloads = HashMap::new();

                for (key, detail) in flags {
                    if detail.enabled {
                        if let Some(variant) = detail.variant {
                            feature_flags.insert(key.clone(), FlagValue::String(variant));
                        } else {
                            feature_flags.insert(key.clone(), FlagValue::Boolean(true));
                        }
                    } else {
                        feature_flags.insert(key.clone(), FlagValue::Boolean(false));
                    }

                    if let Some(metadata) = detail.metadata {
                        if let Some(payload) = metadata.payload {
                            payloads.insert(key, payload);
                        }
                    }
                }

                (feature_flags, payloads)
            }
            FeatureFlagsResponse::Legacy {
                feature_flags,
                feature_flag_payloads,
                ..
            } => (feature_flags, feature_flag_payloads),
        }
    }
}

/// Detailed information about a feature flag evaluation result.
///
/// Returned by the `/decide` endpoint with extended information about
/// why a flag evaluated to a particular value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlagDetail {
    /// The feature flag key
    pub key: String,
    /// Whether the flag is enabled for this user
    pub enabled: bool,
    /// The variant key if this is a multivariate flag
    pub variant: Option<String>,
    /// Reason explaining why the flag evaluated to this value
    #[serde(default)]
    pub reason: Option<FlagReason>,
    /// Additional metadata about the flag
    #[serde(default)]
    pub metadata: Option<FlagMetadata>,
}

/// Explains why a feature flag evaluated to a particular value.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlagReason {
    /// Reason code (e.g., "condition_match", "out_of_rollout_bound")
    pub code: String,
    /// Index of the condition that matched (if applicable)
    #[serde(default)]
    pub condition_index: Option<usize>,
    /// Human-readable description of the reason
    #[serde(default)]
    pub description: Option<String>,
}

/// Metadata about a feature flag from the PostHog server.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FlagMetadata {
    /// Unique identifier for this flag
    pub id: u64,
    /// Version number of the flag definition
    pub version: u32,
    /// Optional description of what this flag controls
    pub description: Option<String>,
    /// Optional JSON payload associated with the flag
    pub payload: Option<serde_json::Value>,
}

const LONG_SCALE: f64 = 0xFFFFFFFFFFFFFFFu64 as f64; // Must be exactly 15 F's to match Python SDK

/// Compute a deterministic hash value for feature flag bucketing.
///
/// Uses SHA-1 to generate a consistent hash in the range [0, 1) for the given
/// key, distinct_id, and salt combination. This ensures users get consistent
/// flag values across requests.
pub fn hash_key(key: &str, distinct_id: &str, salt: &str) -> f64 {
    let hash_key = format!("{key}.{distinct_id}{salt}");
    let mut hasher = Sha1::new();
    hasher.update(hash_key.as_bytes());
    let result = hasher.finalize();
    let hex_str = format!("{result:x}");
    let hash_val = u64::from_str_radix(&hex_str[..15], 16).unwrap_or(0);
    hash_val as f64 / LONG_SCALE
}

/// Determine which variant a user should see for a multivariate flag.
///
/// Uses consistent hashing to assign users to variants based on their
/// rollout percentages. Returns `None` if the flag has no variants or
/// the user doesn't fall into any variant bucket.
pub fn get_matching_variant(flag: &FeatureFlag, distinct_id: &str) -> Option<String> {
    let hash_value = hash_key(&flag.key, distinct_id, VARIANT_HASH_SALT);
    let variants = flag.filters.multivariate.as_ref()?.variants.as_slice();

    let mut value_min = 0.0;
    for variant in variants {
        let value_max = value_min + variant.rollout_percentage / 100.0;
        if hash_value >= value_min && hash_value < value_max {
            return Some(variant.key.clone());
        }
        value_min = value_max;
    }
    None
}

#[must_use = "feature flag evaluation result should be used"]
pub fn match_feature_flag(
    flag: &FeatureFlag,
    distinct_id: &str,
    properties: &HashMap<String, serde_json::Value>,
) -> Result<FlagValue, InconclusiveMatchError> {
    if !flag.active {
        return Ok(FlagValue::Boolean(false));
    }

    let conditions = &flag.filters.groups;

    // Sort conditions to evaluate variant overrides first
    let mut sorted_conditions = conditions.clone();
    sorted_conditions.sort_by_key(|c| if c.variant.is_some() { 0 } else { 1 });

    let mut is_inconclusive = false;

    for condition in sorted_conditions {
        match is_condition_match(flag, distinct_id, &condition, properties) {
            Ok(true) => {
                if let Some(variant_override) = &condition.variant {
                    // Check if variant is valid
                    if let Some(ref multivariate) = flag.filters.multivariate {
                        let valid_variants: Vec<String> = multivariate
                            .variants
                            .iter()
                            .map(|v| v.key.clone())
                            .collect();

                        if valid_variants.contains(variant_override) {
                            return Ok(FlagValue::String(variant_override.clone()));
                        }
                    }
                }

                // Try to get matching variant or return true
                if let Some(variant) = get_matching_variant(flag, distinct_id) {
                    return Ok(FlagValue::String(variant));
                }
                return Ok(FlagValue::Boolean(true));
            }
            Ok(false) => continue,
            Err(_) => {
                is_inconclusive = true;
            }
        }
    }

    if is_inconclusive {
        return Err(InconclusiveMatchError::new(
            "Can't determine if feature flag is enabled or not with given properties",
        ));
    }

    Ok(FlagValue::Boolean(false))
}

fn is_condition_match(
    flag: &FeatureFlag,
    distinct_id: &str,
    condition: &FeatureFlagCondition,
    properties: &HashMap<String, serde_json::Value>,
) -> Result<bool, InconclusiveMatchError> {
    // Check properties first
    for prop in &condition.properties {
        if !match_property(prop, properties)? {
            return Ok(false);
        }
    }

    // If all properties match (or no properties), check rollout percentage
    if let Some(rollout_percentage) = condition.rollout_percentage {
        let hash_value = hash_key(&flag.key, distinct_id, ROLLOUT_HASH_SALT);
        if hash_value > (rollout_percentage / 100.0) {
            return Ok(false);
        }
    }

    Ok(true)
}

/// Match a feature flag with full context (cohorts, other flags)
/// This version supports cohort membership checks and flag dependency checks
#[must_use = "feature flag evaluation result should be used"]
pub fn match_feature_flag_with_context(
    flag: &FeatureFlag,
    distinct_id: &str,
    properties: &HashMap<String, serde_json::Value>,
    ctx: &EvaluationContext,
) -> Result<FlagValue, InconclusiveMatchError> {
    if !flag.active {
        return Ok(FlagValue::Boolean(false));
    }

    let conditions = &flag.filters.groups;

    // Sort conditions to evaluate variant overrides first
    let mut sorted_conditions = conditions.clone();
    sorted_conditions.sort_by_key(|c| if c.variant.is_some() { 0 } else { 1 });

    let mut is_inconclusive = false;

    for condition in sorted_conditions {
        match is_condition_match_with_context(flag, distinct_id, &condition, properties, ctx) {
            Ok(true) => {
                if let Some(variant_override) = &condition.variant {
                    // Check if variant is valid
                    if let Some(ref multivariate) = flag.filters.multivariate {
                        let valid_variants: Vec<String> = multivariate
                            .variants
                            .iter()
                            .map(|v| v.key.clone())
                            .collect();

                        if valid_variants.contains(variant_override) {
                            return Ok(FlagValue::String(variant_override.clone()));
                        }
                    }
                }

                // Try to get matching variant or return true
                if let Some(variant) = get_matching_variant(flag, distinct_id) {
                    return Ok(FlagValue::String(variant));
                }
                return Ok(FlagValue::Boolean(true));
            }
            Ok(false) => continue,
            Err(_) => {
                is_inconclusive = true;
            }
        }
    }

    if is_inconclusive {
        return Err(InconclusiveMatchError::new(
            "Can't determine if feature flag is enabled or not with given properties",
        ));
    }

    Ok(FlagValue::Boolean(false))
}

fn is_condition_match_with_context(
    flag: &FeatureFlag,
    distinct_id: &str,
    condition: &FeatureFlagCondition,
    properties: &HashMap<String, serde_json::Value>,
    ctx: &EvaluationContext,
) -> Result<bool, InconclusiveMatchError> {
    // Check properties first (using context-aware matching for cohorts/flag dependencies)
    for prop in &condition.properties {
        if !match_property_with_context(prop, properties, ctx)? {
            return Ok(false);
        }
    }

    // If all properties match (or no properties), check rollout percentage
    if let Some(rollout_percentage) = condition.rollout_percentage {
        let hash_value = hash_key(&flag.key, distinct_id, ROLLOUT_HASH_SALT);
        if hash_value > (rollout_percentage / 100.0) {
            return Ok(false);
        }
    }

    Ok(true)
}

/// Match a property with additional context for cohorts and flag dependencies
pub fn match_property_with_context(
    property: &Property,
    properties: &HashMap<String, serde_json::Value>,
    ctx: &EvaluationContext,
) -> Result<bool, InconclusiveMatchError> {
    // Check if this is a cohort membership check
    if property.property_type.as_deref() == Some("cohort") {
        return match_cohort_property(property, properties, ctx);
    }

    // Check if this is a flag dependency check
    if property.key.starts_with("$feature/") {
        return match_flag_dependency_property(property, ctx);
    }

    // Fall back to regular property matching
    match_property(property, properties)
}

/// Evaluate cohort membership
fn match_cohort_property(
    property: &Property,
    properties: &HashMap<String, serde_json::Value>,
    ctx: &EvaluationContext,
) -> Result<bool, InconclusiveMatchError> {
    let cohort_id = property
        .value
        .as_str()
        .ok_or_else(|| InconclusiveMatchError::new("Cohort ID must be a string"))?;

    let cohort = ctx.cohorts.get(cohort_id).ok_or_else(|| {
        InconclusiveMatchError::new(&format!("Cohort '{}' not found in local cache", cohort_id))
    })?;

    // Parse and evaluate all cohort properties against the user's properties
    let cohort_properties = cohort.parse_properties();
    let mut is_in_cohort = true;
    for cohort_prop in &cohort_properties {
        match match_property(cohort_prop, properties) {
            Ok(true) => continue,
            Ok(false) => {
                is_in_cohort = false;
                break;
            }
            Err(e) => {
                // If we can't evaluate a cohort property, the cohort membership is inconclusive
                return Err(InconclusiveMatchError::new(&format!(
                    "Cannot evaluate cohort '{}' property '{}': {}",
                    cohort_id, cohort_prop.key, e.message
                )));
            }
        }
    }

    // Handle "in" vs "not_in" operator
    Ok(match property.operator.as_str() {
        "in" => is_in_cohort,
        "not_in" => !is_in_cohort,
        op => {
            return Err(InconclusiveMatchError::new(&format!(
                "Unknown cohort operator: {}",
                op
            )));
        }
    })
}

/// Evaluate flag dependency
fn match_flag_dependency_property(
    property: &Property,
    ctx: &EvaluationContext,
) -> Result<bool, InconclusiveMatchError> {
    // Extract flag key from "$feature/flag-key"
    let flag_key = property
        .key
        .strip_prefix("$feature/")
        .ok_or_else(|| InconclusiveMatchError::new("Invalid flag dependency format"))?;

    let flag = ctx.flags.get(flag_key).ok_or_else(|| {
        InconclusiveMatchError::new(&format!("Flag '{}' not found in local cache", flag_key))
    })?;

    // Evaluate the dependent flag for this user (with empty properties to avoid recursion issues)
    let empty_props = HashMap::new();
    let flag_value = match_feature_flag(flag, ctx.distinct_id, &empty_props)?;

    // Compare the flag value with the expected value
    let expected = &property.value;

    let matches = match (&flag_value, expected) {
        (FlagValue::Boolean(b), serde_json::Value::Bool(expected_b)) => b == expected_b,
        (FlagValue::String(s), serde_json::Value::String(expected_s)) => {
            s.eq_ignore_ascii_case(expected_s)
        }
        (FlagValue::Boolean(true), serde_json::Value::String(s)) => {
            // Flag is enabled (boolean true) but we're checking for a specific variant
            // This should not match
            s.is_empty() || s == "true"
        }
        (FlagValue::Boolean(false), serde_json::Value::String(s)) => s.is_empty() || s == "false",
        (FlagValue::String(s), serde_json::Value::Bool(true)) => {
            // Flag returns a variant string, checking for "enabled" (any variant is enabled)
            !s.is_empty()
        }
        (FlagValue::String(_), serde_json::Value::Bool(false)) => false,
        _ => false,
    };

    // Handle different operators
    Ok(match property.operator.as_str() {
        "exact" => matches,
        "is_not" => !matches,
        op => {
            return Err(InconclusiveMatchError::new(&format!(
                "Unknown flag dependency operator: {}",
                op
            )));
        }
    })
}

/// Parse a relative date string like "-7d", "-24h", "-2w", "-3m", "-1y"
/// Returns the DateTime<Utc> that the relative date represents
fn parse_relative_date(value: &str) -> Option<DateTime<Utc>> {
    let value = value.trim();
    // Need at least 3 chars: "-", digit(s), and unit (e.g., "-7d")
    if value.len() < 3 || !value.starts_with('-') {
        return None;
    }

    let (num_str, unit) = value[1..].split_at(value.len() - 2);
    let num: i64 = num_str.parse().ok()?;

    let duration = match unit {
        "h" => chrono::Duration::hours(num),
        "d" => chrono::Duration::days(num),
        "w" => chrono::Duration::weeks(num),
        "m" => chrono::Duration::days(num * 30), // Approximate month as 30 days
        "y" => chrono::Duration::days(num * 365), // Approximate year as 365 days
        _ => return None,
    };

    Some(Utc::now() - duration)
}

/// Parse a date value from a string (ISO date, ISO datetime, or relative date)
fn parse_date_value(value: &serde_json::Value) -> Option<DateTime<Utc>> {
    let date_str = value.as_str()?;

    // Try relative date first (e.g., "-7d")
    if date_str.starts_with('-') && date_str.len() > 1 {
        if let Some(dt) = parse_relative_date(date_str) {
            return Some(dt);
        }
    }

    // Try ISO datetime with timezone (e.g., "2024-06-15T10:30:00Z")
    if let Ok(dt) = DateTime::parse_from_rfc3339(date_str) {
        return Some(dt.with_timezone(&Utc));
    }

    // Try ISO date only (e.g., "2024-06-15")
    if let Ok(date) = NaiveDate::parse_from_str(date_str, "%Y-%m-%d") {
        return Some(
            date.and_hms_opt(0, 0, 0)
                .expect("midnight is always valid")
                .and_utc(),
        );
    }

    None
}

/// A parsed semantic version as (major, minor, patch)
type SemverTuple = (u64, u64, u64);

/// Parse a semantic version string into a (major, minor, patch) tuple.
///
/// Rules:
/// 1. Strip leading/trailing whitespace
/// 2. Strip `v` or `V` prefix (e.g., "v1.2.3" → "1.2.3")
/// 3. Strip pre-release and build metadata suffixes (split on `-` or `+`, take first part)
/// 4. Split on `.` and parse first 3 components as integers
/// 5. Default missing components to 0 (e.g., "1.2" → (1, 2, 0), "1" → (1, 0, 0))
/// 6. Ignore extra components beyond the third (e.g., "1.2.3.4" → (1, 2, 3))
/// 7. Return None for invalid input (empty string, non-numeric parts, leading dot)
fn parse_semver(value: &str) -> Option<SemverTuple> {
    let value = value.trim();
    if value.is_empty() {
        return None;
    }

    // Strip v/V prefix
    let value = value
        .strip_prefix('v')
        .or_else(|| value.strip_prefix('V'))
        .unwrap_or(value);
    if value.is_empty() {
        return None;
    }

    // Strip pre-release/build metadata (everything after - or +)
    let value = value.split(['-', '+']).next().unwrap_or(value);
    if value.is_empty() {
        return None;
    }

    // Leading dot is invalid
    if value.starts_with('.') {
        return None;
    }

    // Split on dots and parse components
    let parts: Vec<&str> = value.split('.').collect();
    if parts.is_empty() {
        return None;
    }

    let major: u64 = parts.first().and_then(|s| s.parse().ok())?;
    let minor: u64 = parts.get(1).map(|s| s.parse().ok()).unwrap_or(Some(0))?;
    let patch: u64 = parts.get(2).map(|s| s.parse().ok()).unwrap_or(Some(0))?;

    Some((major, minor, patch))
}

/// Parse a wildcard pattern like "1.*" or "1.2.*" and return (lower_bound, upper_bound)
/// Returns None if the pattern is invalid
fn parse_semver_wildcard(pattern: &str) -> Option<(SemverTuple, SemverTuple)> {
    let pattern = pattern.trim();
    if pattern.is_empty() {
        return None;
    }

    // Strip v/V prefix
    let pattern = pattern
        .strip_prefix('v')
        .or_else(|| pattern.strip_prefix('V'))
        .unwrap_or(pattern);
    if pattern.is_empty() {
        return None;
    }

    let parts: Vec<&str> = pattern.split('.').collect();

    match parts.as_slice() {
        // "X.*" pattern
        [major_str, "*"] => {
            let major: u64 = major_str.parse().ok()?;
            Some(((major, 0, 0), (major + 1, 0, 0)))
        }
        // "X.Y.*" pattern
        [major_str, minor_str, "*"] => {
            let major: u64 = major_str.parse().ok()?;
            let minor: u64 = minor_str.parse().ok()?;
            Some(((major, minor, 0), (major, minor + 1, 0)))
        }
        _ => None,
    }
}

/// Compute bounds for tilde range: ~X.Y.Z means >=X.Y.Z and <X.(Y+1).0
fn compute_tilde_bounds(version: SemverTuple) -> (SemverTuple, SemverTuple) {
    let (major, minor, patch) = version;
    ((major, minor, patch), (major, minor + 1, 0))
}

/// Compute bounds for caret range per semver spec:
/// - ^X.Y.Z where X > 0: >=X.Y.Z <(X+1).0.0
/// - ^0.Y.Z where Y > 0: >=0.Y.Z <0.(Y+1).0
/// - ^0.0.Z: >=0.0.Z <0.0.(Z+1)
fn compute_caret_bounds(version: SemverTuple) -> (SemverTuple, SemverTuple) {
    let (major, minor, patch) = version;
    if major > 0 {
        ((major, minor, patch), (major + 1, 0, 0))
    } else if minor > 0 {
        ((0, minor, patch), (0, minor + 1, 0))
    } else {
        ((0, 0, patch), (0, 0, patch + 1))
    }
}

fn match_property(
    property: &Property,
    properties: &HashMap<String, serde_json::Value>,
) -> Result<bool, InconclusiveMatchError> {
    let value = match properties.get(&property.key) {
        Some(v) => v,
        None => {
            // Handle is_not_set operator
            if property.operator == "is_not_set" {
                return Ok(true);
            }
            // Handle is_set operator
            if property.operator == "is_set" {
                return Ok(false);
            }
            // For other operators, missing property is inconclusive
            return Err(InconclusiveMatchError::new(&format!(
                "Property '{}' not found in provided properties",
                property.key
            )));
        }
    };

    Ok(match property.operator.as_str() {
        "exact" => {
            if property.value.is_array() {
                if let Some(arr) = property.value.as_array() {
                    for val in arr {
                        if compare_values(val, value) {
                            return Ok(true);
                        }
                    }
                    return Ok(false);
                }
            }
            compare_values(&property.value, value)
        }
        "is_not" => {
            if property.value.is_array() {
                if let Some(arr) = property.value.as_array() {
                    for val in arr {
                        if compare_values(val, value) {
                            return Ok(false);
                        }
                    }
                    return Ok(true);
                }
            }
            !compare_values(&property.value, value)
        }
        "is_set" => true,      // We already know the property exists
        "is_not_set" => false, // We already know the property exists
        "icontains" => {
            let prop_str = value_to_string(value);
            let search_str = value_to_string(&property.value);
            prop_str.to_lowercase().contains(&search_str.to_lowercase())
        }
        "not_icontains" => {
            let prop_str = value_to_string(value);
            let search_str = value_to_string(&property.value);
            !prop_str.to_lowercase().contains(&search_str.to_lowercase())
        }
        "regex" => {
            let prop_str = value_to_string(value);
            let regex_str = value_to_string(&property.value);
            get_cached_regex(&regex_str)
                .map(|re| re.is_match(&prop_str))
                .unwrap_or(false)
        }
        "not_regex" => {
            let prop_str = value_to_string(value);
            let regex_str = value_to_string(&property.value);
            get_cached_regex(&regex_str)
                .map(|re| !re.is_match(&prop_str))
                .unwrap_or(true)
        }
        "gt" | "gte" | "lt" | "lte" => compare_numeric(&property.operator, &property.value, value),
        "is_date_before" | "is_date_after" => {
            let target_date = parse_date_value(&property.value).ok_or_else(|| {
                InconclusiveMatchError::new(&format!(
                    "Unable to parse target date value: {:?}",
                    property.value
                ))
            })?;

            let prop_date = parse_date_value(value).ok_or_else(|| {
                InconclusiveMatchError::new(&format!(
                    "Unable to parse property date value for '{}': {:?}",
                    property.key, value
                ))
            })?;

            if property.operator == "is_date_before" {
                prop_date < target_date
            } else {
                prop_date > target_date
            }
        }
        // Semver comparison operators
        "semver_eq" | "semver_neq" | "semver_gt" | "semver_gte" | "semver_lt" | "semver_lte" => {
            let prop_str = value_to_string(value);
            let target_str = value_to_string(&property.value);

            let prop_version = parse_semver(&prop_str).ok_or_else(|| {
                InconclusiveMatchError::new(&format!(
                    "Unable to parse property semver value for '{}': {:?}",
                    property.key, value
                ))
            })?;

            let target_version = parse_semver(&target_str).ok_or_else(|| {
                InconclusiveMatchError::new(&format!(
                    "Unable to parse target semver value: {:?}",
                    property.value
                ))
            })?;

            match property.operator.as_str() {
                "semver_eq" => prop_version == target_version,
                "semver_neq" => prop_version != target_version,
                "semver_gt" => prop_version > target_version,
                "semver_gte" => prop_version >= target_version,
                "semver_lt" => prop_version < target_version,
                "semver_lte" => prop_version <= target_version,
                _ => unreachable!(),
            }
        }
        "semver_tilde" => {
            let prop_str = value_to_string(value);
            let target_str = value_to_string(&property.value);

            let prop_version = parse_semver(&prop_str).ok_or_else(|| {
                InconclusiveMatchError::new(&format!(
                    "Unable to parse property semver value for '{}': {:?}",
                    property.key, value
                ))
            })?;

            let target_version = parse_semver(&target_str).ok_or_else(|| {
                InconclusiveMatchError::new(&format!(
                    "Unable to parse target semver value: {:?}",
                    property.value
                ))
            })?;

            let (lower, upper) = compute_tilde_bounds(target_version);
            prop_version >= lower && prop_version < upper
        }
        "semver_caret" => {
            let prop_str = value_to_string(value);
            let target_str = value_to_string(&property.value);

            let prop_version = parse_semver(&prop_str).ok_or_else(|| {
                InconclusiveMatchError::new(&format!(
                    "Unable to parse property semver value for '{}': {:?}",
                    property.key, value
                ))
            })?;

            let target_version = parse_semver(&target_str).ok_or_else(|| {
                InconclusiveMatchError::new(&format!(
                    "Unable to parse target semver value: {:?}",
                    property.value
                ))
            })?;

            let (lower, upper) = compute_caret_bounds(target_version);
            prop_version >= lower && prop_version < upper
        }
        "semver_wildcard" => {
            let prop_str = value_to_string(value);
            let target_str = value_to_string(&property.value);

            let prop_version = parse_semver(&prop_str).ok_or_else(|| {
                InconclusiveMatchError::new(&format!(
                    "Unable to parse property semver value for '{}': {:?}",
                    property.key, value
                ))
            })?;

            let (lower, upper) = parse_semver_wildcard(&target_str).ok_or_else(|| {
                InconclusiveMatchError::new(&format!(
                    "Unable to parse target semver wildcard pattern: {:?}",
                    property.value
                ))
            })?;

            prop_version >= lower && prop_version < upper
        }
        unknown => {
            return Err(InconclusiveMatchError::new(&format!(
                "Unknown operator: {}",
                unknown
            )));
        }
    })
}

fn compare_values(a: &serde_json::Value, b: &serde_json::Value) -> bool {
    // Case-insensitive string comparison
    if let (Some(a_str), Some(b_str)) = (a.as_str(), b.as_str()) {
        return a_str.eq_ignore_ascii_case(b_str);
    }

    // Direct comparison for other types
    a == b
}

fn value_to_string(value: &serde_json::Value) -> String {
    match value {
        serde_json::Value::String(s) => s.clone(),
        serde_json::Value::Number(n) => n.to_string(),
        serde_json::Value::Bool(b) => b.to_string(),
        _ => value.to_string(),
    }
}

fn compare_numeric(
    operator: &str,
    property_value: &serde_json::Value,
    value: &serde_json::Value,
) -> bool {
    let prop_num = match property_value {
        serde_json::Value::Number(n) => n.as_f64(),
        serde_json::Value::String(s) => s.parse::<f64>().ok(),
        _ => None,
    };

    let val_num = match value {
        serde_json::Value::Number(n) => n.as_f64(),
        serde_json::Value::String(s) => s.parse::<f64>().ok(),
        _ => None,
    };

    if let (Some(prop), Some(val)) = (prop_num, val_num) {
        match operator {
            "gt" => val > prop,
            "gte" => val >= prop,
            "lt" => val < prop,
            "lte" => val <= prop,
            _ => false,
        }
    } else {
        // Fall back to string comparison
        let prop_str = value_to_string(property_value);
        let val_str = value_to_string(value);
        match operator {
            "gt" => val_str > prop_str,
            "gte" => val_str >= prop_str,
            "lt" => val_str < prop_str,
            "lte" => val_str <= prop_str,
            _ => false,
        }
    }
}

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

    /// Test salt constant to avoid CodeQL warnings about empty cryptographic values
    const TEST_SALT: &str = "test-salt";

    #[test]
    fn test_hash_key() {
        let hash = hash_key("test-flag", "user-123", TEST_SALT);
        assert!((0.0..=1.0).contains(&hash));

        // Same inputs should produce same hash
        let hash2 = hash_key("test-flag", "user-123", TEST_SALT);
        assert_eq!(hash, hash2);

        // Different inputs should produce different hash
        let hash3 = hash_key("test-flag", "user-456", TEST_SALT);
        assert_ne!(hash, hash3);
    }

    #[test]
    fn test_simple_flag_match() {
        let flag = FeatureFlag {
            key: "test-flag".to_string(),
            active: true,
            filters: FeatureFlagFilters {
                groups: vec![FeatureFlagCondition {
                    properties: vec![],
                    rollout_percentage: Some(100.0),
                    variant: None,
                }],
                multivariate: None,
                payloads: HashMap::new(),
            },
        };

        let properties = HashMap::new();
        let result = match_feature_flag(&flag, "user-123", &properties).unwrap();
        assert_eq!(result, FlagValue::Boolean(true));
    }

    #[test]
    fn test_property_matching() {
        let prop = Property {
            key: "country".to_string(),
            value: json!("US"),
            operator: "exact".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("country".to_string(), json!("US"));

        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("country".to_string(), json!("UK"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_multivariate_variants() {
        let flag = FeatureFlag {
            key: "test-flag".to_string(),
            active: true,
            filters: FeatureFlagFilters {
                groups: vec![FeatureFlagCondition {
                    properties: vec![],
                    rollout_percentage: Some(100.0),
                    variant: None,
                }],
                multivariate: Some(MultivariateFilter {
                    variants: vec![
                        MultivariateVariant {
                            key: "control".to_string(),
                            rollout_percentage: 50.0,
                        },
                        MultivariateVariant {
                            key: "test".to_string(),
                            rollout_percentage: 50.0,
                        },
                    ],
                }),
                payloads: HashMap::new(),
            },
        };

        let properties = HashMap::new();
        let result = match_feature_flag(&flag, "user-123", &properties).unwrap();

        match result {
            FlagValue::String(variant) => {
                assert!(variant == "control" || variant == "test");
            }
            _ => panic!("Expected string variant"),
        }
    }

    #[test]
    fn test_inactive_flag() {
        let flag = FeatureFlag {
            key: "inactive-flag".to_string(),
            active: false,
            filters: FeatureFlagFilters {
                groups: vec![FeatureFlagCondition {
                    properties: vec![],
                    rollout_percentage: Some(100.0),
                    variant: None,
                }],
                multivariate: None,
                payloads: HashMap::new(),
            },
        };

        let properties = HashMap::new();
        let result = match_feature_flag(&flag, "user-123", &properties).unwrap();
        assert_eq!(result, FlagValue::Boolean(false));
    }

    #[test]
    fn test_rollout_percentage() {
        let flag = FeatureFlag {
            key: "rollout-flag".to_string(),
            active: true,
            filters: FeatureFlagFilters {
                groups: vec![FeatureFlagCondition {
                    properties: vec![],
                    rollout_percentage: Some(30.0), // 30% rollout
                    variant: None,
                }],
                multivariate: None,
                payloads: HashMap::new(),
            },
        };

        let properties = HashMap::new();

        // Test with multiple users to ensure distribution
        let mut enabled_count = 0;
        for i in 0..1000 {
            let result = match_feature_flag(&flag, &format!("user-{}", i), &properties).unwrap();
            if result == FlagValue::Boolean(true) {
                enabled_count += 1;
            }
        }

        // Should be roughly 30% enabled (allow for some variance)
        assert!(enabled_count > 250 && enabled_count < 350);
    }

    #[test]
    fn test_regex_operator() {
        let prop = Property {
            key: "email".to_string(),
            value: json!(".*@company\\.com$"),
            operator: "regex".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("email".to_string(), json!("user@company.com"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("email".to_string(), json!("user@example.com"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_icontains_operator() {
        let prop = Property {
            key: "name".to_string(),
            value: json!("ADMIN"),
            operator: "icontains".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("name".to_string(), json!("admin_user"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("name".to_string(), json!("regular_user"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_numeric_operators() {
        // Greater than
        let prop_gt = Property {
            key: "age".to_string(),
            value: json!(18),
            operator: "gt".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("age".to_string(), json!(25));
        assert!(match_property(&prop_gt, &properties).unwrap());

        properties.insert("age".to_string(), json!(15));
        assert!(!match_property(&prop_gt, &properties).unwrap());

        // Less than or equal
        let prop_lte = Property {
            key: "score".to_string(),
            value: json!(100),
            operator: "lte".to_string(),
            property_type: None,
        };

        properties.insert("score".to_string(), json!(100));
        assert!(match_property(&prop_lte, &properties).unwrap());

        properties.insert("score".to_string(), json!(101));
        assert!(!match_property(&prop_lte, &properties).unwrap());
    }

    #[test]
    fn test_is_set_operator() {
        let prop = Property {
            key: "email".to_string(),
            value: json!(true),
            operator: "is_set".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("email".to_string(), json!("test@example.com"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.remove("email");
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_is_not_set_operator() {
        let prop = Property {
            key: "phone".to_string(),
            value: json!(true),
            operator: "is_not_set".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("phone".to_string(), json!("+1234567890"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_empty_groups() {
        let flag = FeatureFlag {
            key: "empty-groups".to_string(),
            active: true,
            filters: FeatureFlagFilters {
                groups: vec![],
                multivariate: None,
                payloads: HashMap::new(),
            },
        };

        let properties = HashMap::new();
        let result = match_feature_flag(&flag, "user-123", &properties).unwrap();
        assert_eq!(result, FlagValue::Boolean(false));
    }

    #[test]
    fn test_hash_scale_constant() {
        // Verify the constant is exactly 15 F's (not 16)
        assert_eq!(LONG_SCALE, 0xFFFFFFFFFFFFFFFu64 as f64);
        assert_ne!(LONG_SCALE, 0xFFFFFFFFFFFFFFFFu64 as f64);
    }

    // ==================== Tests for missing operators ====================

    #[test]
    fn test_unknown_operator_returns_inconclusive_error() {
        let prop = Property {
            key: "status".to_string(),
            value: json!("active"),
            operator: "unknown_operator".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("status".to_string(), json!("active"));

        let result = match_property(&prop, &properties);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.message.contains("unknown_operator"));
    }

    #[test]
    fn test_is_date_before_with_relative_date() {
        let prop = Property {
            key: "signup_date".to_string(),
            value: json!("-7d"), // 7 days ago
            operator: "is_date_before".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        // Date 10 days ago should be before -7d
        let ten_days_ago = chrono::Utc::now() - chrono::Duration::days(10);
        properties.insert(
            "signup_date".to_string(),
            json!(ten_days_ago.format("%Y-%m-%d").to_string()),
        );
        assert!(match_property(&prop, &properties).unwrap());

        // Date 3 days ago should NOT be before -7d
        let three_days_ago = chrono::Utc::now() - chrono::Duration::days(3);
        properties.insert(
            "signup_date".to_string(),
            json!(three_days_ago.format("%Y-%m-%d").to_string()),
        );
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_is_date_after_with_relative_date() {
        let prop = Property {
            key: "last_seen".to_string(),
            value: json!("-30d"), // 30 days ago
            operator: "is_date_after".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        // Date 10 days ago should be after -30d
        let ten_days_ago = chrono::Utc::now() - chrono::Duration::days(10);
        properties.insert(
            "last_seen".to_string(),
            json!(ten_days_ago.format("%Y-%m-%d").to_string()),
        );
        assert!(match_property(&prop, &properties).unwrap());

        // Date 60 days ago should NOT be after -30d
        let sixty_days_ago = chrono::Utc::now() - chrono::Duration::days(60);
        properties.insert(
            "last_seen".to_string(),
            json!(sixty_days_ago.format("%Y-%m-%d").to_string()),
        );
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_is_date_before_with_iso_date() {
        let prop = Property {
            key: "expiry_date".to_string(),
            value: json!("2024-06-15"),
            operator: "is_date_before".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("expiry_date".to_string(), json!("2024-06-10"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("expiry_date".to_string(), json!("2024-06-20"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_is_date_after_with_iso_date() {
        let prop = Property {
            key: "start_date".to_string(),
            value: json!("2024-01-01"),
            operator: "is_date_after".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("start_date".to_string(), json!("2024-03-15"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("start_date".to_string(), json!("2023-12-01"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_is_date_with_relative_hours() {
        let prop = Property {
            key: "last_active".to_string(),
            value: json!("-24h"), // 24 hours ago
            operator: "is_date_after".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        // 12 hours ago should be after -24h
        let twelve_hours_ago = chrono::Utc::now() - chrono::Duration::hours(12);
        properties.insert(
            "last_active".to_string(),
            json!(twelve_hours_ago.to_rfc3339()),
        );
        assert!(match_property(&prop, &properties).unwrap());

        // 48 hours ago should NOT be after -24h
        let forty_eight_hours_ago = chrono::Utc::now() - chrono::Duration::hours(48);
        properties.insert(
            "last_active".to_string(),
            json!(forty_eight_hours_ago.to_rfc3339()),
        );
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_is_date_with_relative_weeks() {
        let prop = Property {
            key: "joined".to_string(),
            value: json!("-2w"), // 2 weeks ago
            operator: "is_date_before".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        // 3 weeks ago should be before -2w
        let three_weeks_ago = chrono::Utc::now() - chrono::Duration::weeks(3);
        properties.insert(
            "joined".to_string(),
            json!(three_weeks_ago.format("%Y-%m-%d").to_string()),
        );
        assert!(match_property(&prop, &properties).unwrap());

        // 1 week ago should NOT be before -2w
        let one_week_ago = chrono::Utc::now() - chrono::Duration::weeks(1);
        properties.insert(
            "joined".to_string(),
            json!(one_week_ago.format("%Y-%m-%d").to_string()),
        );
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_is_date_with_relative_months() {
        let prop = Property {
            key: "subscription_date".to_string(),
            value: json!("-3m"), // 3 months ago
            operator: "is_date_after".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        // 1 month ago should be after -3m
        let one_month_ago = chrono::Utc::now() - chrono::Duration::days(30);
        properties.insert(
            "subscription_date".to_string(),
            json!(one_month_ago.format("%Y-%m-%d").to_string()),
        );
        assert!(match_property(&prop, &properties).unwrap());

        // 6 months ago should NOT be after -3m
        let six_months_ago = chrono::Utc::now() - chrono::Duration::days(180);
        properties.insert(
            "subscription_date".to_string(),
            json!(six_months_ago.format("%Y-%m-%d").to_string()),
        );
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_is_date_with_relative_years() {
        let prop = Property {
            key: "created_at".to_string(),
            value: json!("-1y"), // 1 year ago
            operator: "is_date_before".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        // 2 years ago should be before -1y
        let two_years_ago = chrono::Utc::now() - chrono::Duration::days(730);
        properties.insert(
            "created_at".to_string(),
            json!(two_years_ago.format("%Y-%m-%d").to_string()),
        );
        assert!(match_property(&prop, &properties).unwrap());

        // 6 months ago should NOT be before -1y
        let six_months_ago = chrono::Utc::now() - chrono::Duration::days(180);
        properties.insert(
            "created_at".to_string(),
            json!(six_months_ago.format("%Y-%m-%d").to_string()),
        );
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_is_date_with_invalid_date_format() {
        let prop = Property {
            key: "date".to_string(),
            value: json!("-7d"),
            operator: "is_date_before".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("date".to_string(), json!("not-a-date"));

        // Invalid date formats should return inconclusive
        let result = match_property(&prop, &properties);
        assert!(result.is_err());
    }

    #[test]
    fn test_is_date_with_iso_datetime() {
        let prop = Property {
            key: "event_time".to_string(),
            value: json!("2024-06-15T10:30:00Z"),
            operator: "is_date_before".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("event_time".to_string(), json!("2024-06-15T08:00:00Z"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("event_time".to_string(), json!("2024-06-15T12:00:00Z"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    // ==================== Tests for cohort membership ====================

    #[test]
    fn test_cohort_membership_in() {
        // Create a cohort that matches users with country = US
        let mut cohorts = HashMap::new();
        cohorts.insert(
            "cohort_1".to_string(),
            CohortDefinition::new(
                "cohort_1".to_string(),
                vec![Property {
                    key: "country".to_string(),
                    value: json!("US"),
                    operator: "exact".to_string(),
                    property_type: None,
                }],
            ),
        );

        // Property filter checking cohort membership
        let prop = Property {
            key: "$cohort".to_string(),
            value: json!("cohort_1"),
            operator: "in".to_string(),
            property_type: Some("cohort".to_string()),
        };

        // User with country = US should be in the cohort
        let mut properties = HashMap::new();
        properties.insert("country".to_string(), json!("US"));

        let ctx = EvaluationContext {
            cohorts: &cohorts,
            flags: &HashMap::new(),
            distinct_id: "user-123",
        };
        assert!(match_property_with_context(&prop, &properties, &ctx).unwrap());

        // User with country = UK should NOT be in the cohort
        properties.insert("country".to_string(), json!("UK"));
        assert!(!match_property_with_context(&prop, &properties, &ctx).unwrap());
    }

    #[test]
    fn test_cohort_membership_not_in() {
        let mut cohorts = HashMap::new();
        cohorts.insert(
            "cohort_blocked".to_string(),
            CohortDefinition::new(
                "cohort_blocked".to_string(),
                vec![Property {
                    key: "status".to_string(),
                    value: json!("blocked"),
                    operator: "exact".to_string(),
                    property_type: None,
                }],
            ),
        );

        let prop = Property {
            key: "$cohort".to_string(),
            value: json!("cohort_blocked"),
            operator: "not_in".to_string(),
            property_type: Some("cohort".to_string()),
        };

        let mut properties = HashMap::new();
        properties.insert("status".to_string(), json!("active"));

        let ctx = EvaluationContext {
            cohorts: &cohorts,
            flags: &HashMap::new(),
            distinct_id: "user-123",
        };
        // User with status = active should NOT be in the blocked cohort (so not_in returns true)
        assert!(match_property_with_context(&prop, &properties, &ctx).unwrap());

        // User with status = blocked IS in the cohort (so not_in returns false)
        properties.insert("status".to_string(), json!("blocked"));
        assert!(!match_property_with_context(&prop, &properties, &ctx).unwrap());
    }

    #[test]
    fn test_cohort_not_found_returns_inconclusive() {
        let cohorts = HashMap::new(); // No cohorts defined

        let prop = Property {
            key: "$cohort".to_string(),
            value: json!("nonexistent_cohort"),
            operator: "in".to_string(),
            property_type: Some("cohort".to_string()),
        };

        let properties = HashMap::new();
        let ctx = EvaluationContext {
            cohorts: &cohorts,
            flags: &HashMap::new(),
            distinct_id: "user-123",
        };

        let result = match_property_with_context(&prop, &properties, &ctx);
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains("Cohort"));
    }

    // ==================== Tests for flag dependencies ====================

    #[test]
    fn test_flag_dependency_enabled() {
        let mut flags = HashMap::new();
        flags.insert(
            "prerequisite-flag".to_string(),
            FeatureFlag {
                key: "prerequisite-flag".to_string(),
                active: true,
                filters: FeatureFlagFilters {
                    groups: vec![FeatureFlagCondition {
                        properties: vec![],
                        rollout_percentage: Some(100.0),
                        variant: None,
                    }],
                    multivariate: None,
                    payloads: HashMap::new(),
                },
            },
        );

        // Property checking if prerequisite-flag is enabled
        let prop = Property {
            key: "$feature/prerequisite-flag".to_string(),
            value: json!(true),
            operator: "exact".to_string(),
            property_type: None,
        };

        let properties = HashMap::new();
        let ctx = EvaluationContext {
            cohorts: &HashMap::new(),
            flags: &flags,
            distinct_id: "user-123",
        };

        // The prerequisite flag is enabled for user-123, so this should match
        assert!(match_property_with_context(&prop, &properties, &ctx).unwrap());
    }

    #[test]
    fn test_flag_dependency_disabled() {
        let mut flags = HashMap::new();
        flags.insert(
            "disabled-flag".to_string(),
            FeatureFlag {
                key: "disabled-flag".to_string(),
                active: false, // Flag is inactive
                filters: FeatureFlagFilters {
                    groups: vec![],
                    multivariate: None,
                    payloads: HashMap::new(),
                },
            },
        );

        // Property checking if disabled-flag is enabled
        let prop = Property {
            key: "$feature/disabled-flag".to_string(),
            value: json!(true),
            operator: "exact".to_string(),
            property_type: None,
        };

        let properties = HashMap::new();
        let ctx = EvaluationContext {
            cohorts: &HashMap::new(),
            flags: &flags,
            distinct_id: "user-123",
        };

        // The flag is disabled, so checking for true should fail
        assert!(!match_property_with_context(&prop, &properties, &ctx).unwrap());
    }

    #[test]
    fn test_flag_dependency_variant_match() {
        let mut flags = HashMap::new();
        flags.insert(
            "ab-test-flag".to_string(),
            FeatureFlag {
                key: "ab-test-flag".to_string(),
                active: true,
                filters: FeatureFlagFilters {
                    groups: vec![FeatureFlagCondition {
                        properties: vec![],
                        rollout_percentage: Some(100.0),
                        variant: None,
                    }],
                    multivariate: Some(MultivariateFilter {
                        variants: vec![
                            MultivariateVariant {
                                key: "control".to_string(),
                                rollout_percentage: 50.0,
                            },
                            MultivariateVariant {
                                key: "test".to_string(),
                                rollout_percentage: 50.0,
                            },
                        ],
                    }),
                    payloads: HashMap::new(),
                },
            },
        );

        // Check if user is in "control" variant
        let prop = Property {
            key: "$feature/ab-test-flag".to_string(),
            value: json!("control"),
            operator: "exact".to_string(),
            property_type: None,
        };

        let properties = HashMap::new();
        let ctx = EvaluationContext {
            cohorts: &HashMap::new(),
            flags: &flags,
            distinct_id: "user-gets-control", // This distinct_id should deterministically get "control"
        };

        // The result depends on the hash - we just check it doesn't error
        let result = match_property_with_context(&prop, &properties, &ctx);
        assert!(result.is_ok());
    }

    #[test]
    fn test_flag_dependency_not_found_returns_inconclusive() {
        let flags = HashMap::new(); // No flags defined

        let prop = Property {
            key: "$feature/nonexistent-flag".to_string(),
            value: json!(true),
            operator: "exact".to_string(),
            property_type: None,
        };

        let properties = HashMap::new();
        let ctx = EvaluationContext {
            cohorts: &HashMap::new(),
            flags: &flags,
            distinct_id: "user-123",
        };

        let result = match_property_with_context(&prop, &properties, &ctx);
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains("Flag"));
    }

    // ==================== Date parsing edge case tests ====================

    #[test]
    fn test_parse_relative_date_edge_cases() {
        // These test the internal parse_relative_date function indirectly via match_property
        let prop = Property {
            key: "date".to_string(),
            value: json!("placeholder"),
            operator: "is_date_before".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("date".to_string(), json!("2024-01-01"));

        // Empty string as target date should fail
        let empty_prop = Property {
            value: json!(""),
            ..prop.clone()
        };
        assert!(match_property(&empty_prop, &properties).is_err());

        // Single dash should fail
        let dash_prop = Property {
            value: json!("-"),
            ..prop.clone()
        };
        assert!(match_property(&dash_prop, &properties).is_err());

        // Missing unit (just "-7") should fail
        let no_unit_prop = Property {
            value: json!("-7"),
            ..prop.clone()
        };
        assert!(match_property(&no_unit_prop, &properties).is_err());

        // Missing number (just "-d") should fail
        let no_number_prop = Property {
            value: json!("-d"),
            ..prop.clone()
        };
        assert!(match_property(&no_number_prop, &properties).is_err());

        // Invalid unit should fail
        let invalid_unit_prop = Property {
            value: json!("-7x"),
            ..prop.clone()
        };
        assert!(match_property(&invalid_unit_prop, &properties).is_err());
    }

    #[test]
    fn test_parse_relative_date_large_values() {
        // Very large relative dates should work
        let prop = Property {
            key: "created_at".to_string(),
            value: json!("-1000d"), // ~2.7 years ago
            operator: "is_date_before".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        // Date 5 years ago should be before -1000d
        let five_years_ago = chrono::Utc::now() - chrono::Duration::days(1825);
        properties.insert(
            "created_at".to_string(),
            json!(five_years_ago.format("%Y-%m-%d").to_string()),
        );
        assert!(match_property(&prop, &properties).unwrap());
    }

    // ==================== Tests for invalid regex patterns ====================

    #[test]
    fn test_regex_with_invalid_pattern_returns_false() {
        // Invalid regex pattern (unclosed group)
        let prop = Property {
            key: "email".to_string(),
            value: json!("(unclosed"),
            operator: "regex".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("email".to_string(), json!("test@example.com"));

        // Invalid regex should return false (not match)
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_not_regex_with_invalid_pattern_returns_true() {
        // Invalid regex pattern (unclosed group)
        let prop = Property {
            key: "email".to_string(),
            value: json!("(unclosed"),
            operator: "not_regex".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("email".to_string(), json!("test@example.com"));

        // Invalid regex with not_regex should return true (no match means "not matching")
        assert!(match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_regex_with_various_invalid_patterns() {
        let invalid_patterns = vec![
            "(unclosed", // Unclosed group
            "[unclosed", // Unclosed bracket
            "*invalid",  // Invalid quantifier at start
            "(?P<bad",   // Unclosed named group
            r"\",        // Trailing backslash
        ];

        for pattern in invalid_patterns {
            let prop = Property {
                key: "value".to_string(),
                value: json!(pattern),
                operator: "regex".to_string(),
                property_type: None,
            };

            let mut properties = HashMap::new();
            properties.insert("value".to_string(), json!("test"));

            // All invalid patterns should return false for regex
            assert!(
                !match_property(&prop, &properties).unwrap(),
                "Invalid pattern '{}' should return false for regex",
                pattern
            );

            // And true for not_regex
            let not_regex_prop = Property {
                operator: "not_regex".to_string(),
                ..prop
            };
            assert!(
                match_property(&not_regex_prop, &properties).unwrap(),
                "Invalid pattern '{}' should return true for not_regex",
                pattern
            );
        }
    }

    // ==================== Semver parsing tests ====================

    #[test]
    fn test_parse_semver_basic() {
        assert_eq!(parse_semver("1.2.3"), Some((1, 2, 3)));
        assert_eq!(parse_semver("0.0.0"), Some((0, 0, 0)));
        assert_eq!(parse_semver("10.20.30"), Some((10, 20, 30)));
    }

    #[test]
    fn test_parse_semver_v_prefix() {
        assert_eq!(parse_semver("v1.2.3"), Some((1, 2, 3)));
        assert_eq!(parse_semver("V1.2.3"), Some((1, 2, 3)));
    }

    #[test]
    fn test_parse_semver_whitespace() {
        assert_eq!(parse_semver("  1.2.3  "), Some((1, 2, 3)));
        assert_eq!(parse_semver(" v1.2.3 "), Some((1, 2, 3)));
    }

    #[test]
    fn test_parse_semver_prerelease_stripped() {
        assert_eq!(parse_semver("1.2.3-alpha"), Some((1, 2, 3)));
        assert_eq!(parse_semver("1.2.3-beta.1"), Some((1, 2, 3)));
        assert_eq!(parse_semver("1.2.3-rc.1+build.123"), Some((1, 2, 3)));
        assert_eq!(parse_semver("1.2.3+build.456"), Some((1, 2, 3)));
    }

    #[test]
    fn test_parse_semver_partial_versions() {
        assert_eq!(parse_semver("1.2"), Some((1, 2, 0)));
        assert_eq!(parse_semver("1"), Some((1, 0, 0)));
        assert_eq!(parse_semver("v1.2"), Some((1, 2, 0)));
    }

    #[test]
    fn test_parse_semver_extra_components_ignored() {
        assert_eq!(parse_semver("1.2.3.4"), Some((1, 2, 3)));
        assert_eq!(parse_semver("1.2.3.4.5.6"), Some((1, 2, 3)));
    }

    #[test]
    fn test_parse_semver_leading_zeros() {
        assert_eq!(parse_semver("01.02.03"), Some((1, 2, 3)));
        assert_eq!(parse_semver("001.002.003"), Some((1, 2, 3)));
    }

    #[test]
    fn test_parse_semver_invalid() {
        assert_eq!(parse_semver(""), None);
        assert_eq!(parse_semver("   "), None);
        assert_eq!(parse_semver("v"), None);
        assert_eq!(parse_semver(".1.2.3"), None);
        assert_eq!(parse_semver("abc"), None);
        assert_eq!(parse_semver("1.abc.3"), None);
        assert_eq!(parse_semver("1.2.abc"), None);
        assert_eq!(parse_semver("not-a-version"), None);
    }

    // ==================== Semver eq/neq tests ====================

    #[test]
    fn test_semver_eq_basic() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3"),
            operator: "semver_eq".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        properties.insert("version".to_string(), json!("1.2.3"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.2.4"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.3.3"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("2.2.3"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_semver_eq_with_v_prefix() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3"),
            operator: "semver_eq".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // v-prefix on property value
        properties.insert("version".to_string(), json!("v1.2.3"));
        assert!(match_property(&prop, &properties).unwrap());

        // v-prefix on target value
        let prop_with_v = Property {
            value: json!("v1.2.3"),
            ..prop.clone()
        };
        properties.insert("version".to_string(), json!("1.2.3"));
        assert!(match_property(&prop_with_v, &properties).unwrap());
    }

    #[test]
    fn test_semver_eq_prerelease_stripped() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3"),
            operator: "semver_eq".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        properties.insert("version".to_string(), json!("1.2.3-alpha"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.2.3-beta.1"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.2.3+build.456"));
        assert!(match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_semver_eq_partial_versions() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.0"),
            operator: "semver_eq".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // "1.2" should equal "1.2.0"
        properties.insert("version".to_string(), json!("1.2"));
        assert!(match_property(&prop, &properties).unwrap());

        // Target as partial version
        let partial_prop = Property {
            value: json!("1.2"),
            ..prop.clone()
        };
        properties.insert("version".to_string(), json!("1.2.0"));
        assert!(match_property(&partial_prop, &properties).unwrap());
    }

    #[test]
    fn test_semver_neq() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3"),
            operator: "semver_neq".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        properties.insert("version".to_string(), json!("1.2.3"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.2.4"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("2.0.0"));
        assert!(match_property(&prop, &properties).unwrap());
    }

    // ==================== Semver gt/gte/lt/lte tests ====================

    #[test]
    fn test_semver_gt() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3"),
            operator: "semver_gt".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // Greater versions
        properties.insert("version".to_string(), json!("1.2.4"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.3.0"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("2.0.0"));
        assert!(match_property(&prop, &properties).unwrap());

        // Equal version
        properties.insert("version".to_string(), json!("1.2.3"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Lesser versions
        properties.insert("version".to_string(), json!("1.2.2"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.1.9"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("0.9.9"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_semver_gte() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3"),
            operator: "semver_gte".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // Greater versions
        properties.insert("version".to_string(), json!("1.2.4"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("2.0.0"));
        assert!(match_property(&prop, &properties).unwrap());

        // Equal version
        properties.insert("version".to_string(), json!("1.2.3"));
        assert!(match_property(&prop, &properties).unwrap());

        // Lesser versions
        properties.insert("version".to_string(), json!("1.2.2"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("0.9.9"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_semver_lt() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3"),
            operator: "semver_lt".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // Lesser versions
        properties.insert("version".to_string(), json!("1.2.2"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.1.9"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("0.9.9"));
        assert!(match_property(&prop, &properties).unwrap());

        // Equal version
        properties.insert("version".to_string(), json!("1.2.3"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Greater versions
        properties.insert("version".to_string(), json!("1.2.4"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("2.0.0"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_semver_lte() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3"),
            operator: "semver_lte".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // Lesser versions
        properties.insert("version".to_string(), json!("1.2.2"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("0.9.9"));
        assert!(match_property(&prop, &properties).unwrap());

        // Equal version
        properties.insert("version".to_string(), json!("1.2.3"));
        assert!(match_property(&prop, &properties).unwrap());

        // Greater versions
        properties.insert("version".to_string(), json!("1.2.4"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("2.0.0"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    // ==================== Semver tilde tests ====================

    #[test]
    fn test_semver_tilde_basic() {
        // ~1.2.3 means >=1.2.3 <1.3.0
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3"),
            operator: "semver_tilde".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // Exact match
        properties.insert("version".to_string(), json!("1.2.3"));
        assert!(match_property(&prop, &properties).unwrap());

        // Within range
        properties.insert("version".to_string(), json!("1.2.4"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.2.99"));
        assert!(match_property(&prop, &properties).unwrap());

        // At upper bound (excluded)
        properties.insert("version".to_string(), json!("1.3.0"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Above upper bound
        properties.insert("version".to_string(), json!("1.3.1"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("2.0.0"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Below lower bound
        properties.insert("version".to_string(), json!("1.2.2"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.1.9"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_semver_tilde_zero_versions() {
        // ~0.2.3 means >=0.2.3 <0.3.0
        let prop = Property {
            key: "version".to_string(),
            value: json!("0.2.3"),
            operator: "semver_tilde".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        properties.insert("version".to_string(), json!("0.2.3"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("0.2.9"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("0.3.0"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("0.2.2"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    // ==================== Semver caret tests ====================

    #[test]
    fn test_semver_caret_major_nonzero() {
        // ^1.2.3 means >=1.2.3 <2.0.0
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3"),
            operator: "semver_caret".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // Exact match
        properties.insert("version".to_string(), json!("1.2.3"));
        assert!(match_property(&prop, &properties).unwrap());

        // Within range
        properties.insert("version".to_string(), json!("1.2.4"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.3.0"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.99.99"));
        assert!(match_property(&prop, &properties).unwrap());

        // At upper bound (excluded)
        properties.insert("version".to_string(), json!("2.0.0"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Above upper bound
        properties.insert("version".to_string(), json!("2.0.1"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Below lower bound
        properties.insert("version".to_string(), json!("1.2.2"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("0.9.9"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_semver_caret_major_zero_minor_nonzero() {
        // ^0.2.3 means >=0.2.3 <0.3.0
        let prop = Property {
            key: "version".to_string(),
            value: json!("0.2.3"),
            operator: "semver_caret".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // Exact match
        properties.insert("version".to_string(), json!("0.2.3"));
        assert!(match_property(&prop, &properties).unwrap());

        // Within range
        properties.insert("version".to_string(), json!("0.2.4"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("0.2.99"));
        assert!(match_property(&prop, &properties).unwrap());

        // At upper bound (excluded)
        properties.insert("version".to_string(), json!("0.3.0"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Above upper bound
        properties.insert("version".to_string(), json!("0.3.1"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.0.0"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Below lower bound
        properties.insert("version".to_string(), json!("0.2.2"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("0.1.9"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_semver_caret_major_zero_minor_zero() {
        // ^0.0.3 means >=0.0.3 <0.0.4
        let prop = Property {
            key: "version".to_string(),
            value: json!("0.0.3"),
            operator: "semver_caret".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // Exact match
        properties.insert("version".to_string(), json!("0.0.3"));
        assert!(match_property(&prop, &properties).unwrap());

        // At upper bound (excluded)
        properties.insert("version".to_string(), json!("0.0.4"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Above upper bound
        properties.insert("version".to_string(), json!("0.0.5"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("0.1.0"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Below lower bound
        properties.insert("version".to_string(), json!("0.0.2"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    // ==================== Semver wildcard tests ====================

    #[test]
    fn test_semver_wildcard_major() {
        // 1.* means >=1.0.0 <2.0.0
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.*"),
            operator: "semver_wildcard".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // At lower bound
        properties.insert("version".to_string(), json!("1.0.0"));
        assert!(match_property(&prop, &properties).unwrap());

        // Within range
        properties.insert("version".to_string(), json!("1.2.3"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.99.99"));
        assert!(match_property(&prop, &properties).unwrap());

        // At upper bound (excluded)
        properties.insert("version".to_string(), json!("2.0.0"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Above upper bound
        properties.insert("version".to_string(), json!("2.0.1"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Below lower bound
        properties.insert("version".to_string(), json!("0.9.9"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_semver_wildcard_minor() {
        // 1.2.* means >=1.2.0 <1.3.0
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.*"),
            operator: "semver_wildcard".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // At lower bound
        properties.insert("version".to_string(), json!("1.2.0"));
        assert!(match_property(&prop, &properties).unwrap());

        // Within range
        properties.insert("version".to_string(), json!("1.2.3"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.2.99"));
        assert!(match_property(&prop, &properties).unwrap());

        // At upper bound (excluded)
        properties.insert("version".to_string(), json!("1.3.0"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Above upper bound
        properties.insert("version".to_string(), json!("1.3.1"));
        assert!(!match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("2.0.0"));
        assert!(!match_property(&prop, &properties).unwrap());

        // Below lower bound
        properties.insert("version".to_string(), json!("1.1.9"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_semver_wildcard_zero() {
        // 0.* means >=0.0.0 <1.0.0
        let prop = Property {
            key: "version".to_string(),
            value: json!("0.*"),
            operator: "semver_wildcard".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        properties.insert("version".to_string(), json!("0.0.0"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("0.99.99"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.0.0"));
        assert!(!match_property(&prop, &properties).unwrap());
    }

    // ==================== Semver error handling tests ====================

    #[test]
    fn test_semver_invalid_property_value() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3"),
            operator: "semver_eq".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // Invalid semver strings
        properties.insert("version".to_string(), json!("not-a-version"));
        assert!(match_property(&prop, &properties).is_err());

        properties.insert("version".to_string(), json!(""));
        assert!(match_property(&prop, &properties).is_err());

        properties.insert("version".to_string(), json!(".1.2.3"));
        assert!(match_property(&prop, &properties).is_err());

        properties.insert("version".to_string(), json!("abc.def.ghi"));
        assert!(match_property(&prop, &properties).is_err());
    }

    #[test]
    fn test_semver_invalid_target_value() {
        let mut properties = HashMap::new();
        properties.insert("version".to_string(), json!("1.2.3"));

        // Invalid target semver
        let prop = Property {
            key: "version".to_string(),
            value: json!("not-valid"),
            operator: "semver_eq".to_string(),
            property_type: None,
        };
        assert!(match_property(&prop, &properties).is_err());

        let prop = Property {
            key: "version".to_string(),
            value: json!(""),
            operator: "semver_gt".to_string(),
            property_type: None,
        };
        assert!(match_property(&prop, &properties).is_err());
    }

    #[test]
    fn test_semver_invalid_wildcard_pattern() {
        let mut properties = HashMap::new();
        properties.insert("version".to_string(), json!("1.2.3"));

        // Invalid wildcard patterns
        let invalid_patterns = vec![
            "*",       // Just wildcard
            "*.2.3",   // Wildcard in wrong position
            "1.*.3",   // Wildcard in wrong position
            "1.2.3.*", // Too many parts
            "abc.*",   // Non-numeric major
        ];

        for pattern in invalid_patterns {
            let prop = Property {
                key: "version".to_string(),
                value: json!(pattern),
                operator: "semver_wildcard".to_string(),
                property_type: None,
            };
            assert!(
                match_property(&prop, &properties).is_err(),
                "Pattern '{}' should be invalid",
                pattern
            );
        }
    }

    #[test]
    fn test_semver_missing_property() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3"),
            operator: "semver_eq".to_string(),
            property_type: None,
        };

        let properties = HashMap::new(); // Empty properties
        assert!(match_property(&prop, &properties).is_err());
    }

    #[test]
    fn test_semver_null_property_value() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3"),
            operator: "semver_eq".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("version".to_string(), json!(null));

        // null converts to "null" string which is not a valid semver
        assert!(match_property(&prop, &properties).is_err());
    }

    #[test]
    fn test_semver_numeric_property_value() {
        // When property value is a number, it gets converted to string
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.0.0"),
            operator: "semver_eq".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        // Number 1 becomes "1" which parses as (1, 0, 0)
        properties.insert("version".to_string(), json!(1));
        assert!(match_property(&prop, &properties).unwrap());
    }

    // ==================== Semver edge cases ====================

    #[test]
    fn test_semver_four_part_versions() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1.2.3.4"),
            operator: "semver_eq".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();

        // 1.2.3.4 should equal 1.2.3 (extra parts ignored)
        properties.insert("version".to_string(), json!("1.2.3"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.2.3.4"));
        assert!(match_property(&prop, &properties).unwrap());

        properties.insert("version".to_string(), json!("1.2.3.999"));
        assert!(match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_semver_large_version_numbers() {
        let prop = Property {
            key: "version".to_string(),
            value: json!("1000.2000.3000"),
            operator: "semver_eq".to_string(),
            property_type: None,
        };

        let mut properties = HashMap::new();
        properties.insert("version".to_string(), json!("1000.2000.3000"));
        assert!(match_property(&prop, &properties).unwrap());
    }

    #[test]
    fn test_semver_comparison_ordering() {
        // Test that version ordering is correct across major/minor/patch
        let cases = vec![
            ("0.0.1", "0.0.2", "semver_lt", true),
            ("0.1.0", "0.0.99", "semver_gt", true),
            ("1.0.0", "0.99.99", "semver_gt", true),
            ("1.0.0", "1.0.0", "semver_eq", true),
            ("2.0.0", "10.0.0", "semver_lt", true), // Numeric, not string comparison
            ("9.0.0", "10.0.0", "semver_lt", true), // Numeric, not string comparison
            ("1.9.0", "1.10.0", "semver_lt", true), // Numeric, not string comparison
            ("1.2.9", "1.2.10", "semver_lt", true), // Numeric, not string comparison
        ];

        for (prop_val, target_val, op, expected) in cases {
            let prop = Property {
                key: "version".to_string(),
                value: json!(target_val),
                operator: op.to_string(),
                property_type: None,
            };

            let mut properties = HashMap::new();
            properties.insert("version".to_string(), json!(prop_val));

            assert_eq!(
                match_property(&prop, &properties).unwrap(),
                expected,
                "{} {} {} should be {}",
                prop_val,
                op,
                target_val,
                expected
            );
        }
    }
}