quamina 0.4.0

Fast pattern-matching library for filtering JSON events
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
//! Core tests for quamina-rs
//!
//! Go lineage: core_matcher_test.go, arrays_test.go, flatten_json_test.go
//!
//! This module covers:
//! - Basic matching (exact, numeric, boolean, null)
//! - Exists operator (true/false, empty array)
//! - Nested fields and deeply nested patterns
//! - Array element matching
//! - Delete/rebuild, pruner stats
//! - Builder API tests
//! - Clone, Send+Sync
//! - Custom flattener
//! - Error handling

use super::*;

// ============================================================================
// Basic Matching Tests
// ============================================================================

#[test]
fn test_exact_match() {
    let q = q!("p1" => r#"{"status": ["active"]}"#);
    assert_matches!(q, r#"{"status": "active"}"#, vec!["p1"]);
}

#[test]
fn test_no_match() {
    let q = q!("p1" => r#"{"status": ["active"]}"#);
    assert_no_match!(q, r#"{"status": "inactive"}"#);
}

#[test]
fn test_numeric_match() {
    let q = q!("p1" => r#"{"count": [42]}"#);
    assert_matches!(
        q,
        r#"{"count": 42}"#,
        vec!["p1"],
        "Should match numeric value 42"
    );
}

#[test]
fn test_numeric_variant_matching() {
    // All these numeric representations of 35 should match pattern [35]
    let q = q!("p1" => r#"{"x": [35]}"#);

    // All numeric representations of 35 should match (Go's numbers_test.go:174)
    for event in [
        r#"{"x": 35}"#,
        r#"{"x": 35.0}"#,
        r#"{"x": 3.5e1}"#,
        r#"{"x": 35.000}"#,
        r#"{"x": 0.000035e6}"#,
    ] {
        assert_matches!(q, event, vec!["p1"]);
    }
}

#[test]
fn test_boolean_match() {
    let q = q!("p1" => r#"{"enabled": [true]}"#);
    assert_matches!(
        q,
        r#"{"enabled": true}"#,
        vec!["p1"],
        "Should match boolean true"
    );
}

#[test]
fn test_null_match() {
    let q = q!("p1" => r#"{"value": [null]}"#);
    assert_matches!(
        q,
        r#"{"value": null}"#,
        vec!["p1"],
        "Should match null value"
    );
}

// ============================================================================
// Exists Operator Tests
// ============================================================================

#[test]
fn test_exists_true() {
    let q = q!("p1" => r#"{"name": [{"exists": true}]}"#);

    assert_matches!(
        q,
        r#"{"name": "anything", "other": 1}"#,
        vec!["p1"],
        "Should match when field exists"
    );
    assert_no_match!(
        q,
        r#"{"other": 1}"#,
        "Should not match when field is missing"
    );
}

#[test]
fn test_exists_false() {
    let q = q!("p1" => r#"{"name": [{"exists": false}]}"#);

    assert_matches!(q, r#"{"other": 1}"#, vec!["p1"]);
    assert_no_match!(q, r#"{"name": "value"}"#);
}

#[test]
fn test_exists_with_empty_array() {
    // Per Go quamina: {"a": []} with exists:true does NOT match
    // but exists:false DOES match (no leaf values)
    let q_true = q!("p1" => r#"{"a": [{"exists": true}]}"#);
    let q_false = q!("p2" => r#"{"a": [{"exists": false}]}"#);

    // Event with empty array
    let event = r#"{"a": []}"#;

    // exists:true should NOT match (no leaf values in empty array)
    assert_no_match!(q_true, event, "exists:true should not match empty array");

    // exists:false SHOULD match (no leaf values means field effectively absent)
    assert_matches!(
        q_false,
        event,
        vec!["p2"],
        "exists:false should match empty array"
    );
}

// ============================================================================
// Nested Field Tests
// ============================================================================

#[test]
fn test_nested_object_pattern() {
    let q = q!("p1" => r#"{"user": {"role": ["admin"]}}"#);

    assert_matches!(
        q,
        r#"{"user": {"role": "admin", "name": "alice"}}"#,
        vec!["p1"],
        "Should match nested field"
    );
    assert_no_match!(q, r#"{"user": {"role": "guest"}}"#);
}

#[test]
fn test_deeply_nested() {
    let q = q!("p1" => r#"{"a": {"b": {"c": ["value"]}}}"#);
    assert_matches!(q, r#"{"a": {"b": {"c": "value"}}}"#, vec!["p1"]);
}

// ============================================================================
// Array Element Matching Tests
// ============================================================================

#[test]
fn test_array_element_matching() {
    // Pattern should match if value is ANY element of the array
    let q = q!("p1" => r#"{"ids": [943]}"#);

    // Event has array - should match if 943 is in the array
    let event = r#"{"ids": [116, 943, 234]}"#;
    assert_matches!(
        q,
        event,
        vec!["p1"],
        "Should match when pattern value is in event array"
    );
}

#[test]
fn test_array_cross_element_matching() {
    // Test cross-element array matching behavior (matches Go quamina behavior)
    // Pattern {"members": {"given": ["Mick"], "surname": ["Strummer"]}}
    // Event: members=[{given: "Joe", surname: "Strummer"}, {given: "Mick", surname: "Jones"}]
    //
    // Should NOT match because no single array element has both given=Mick AND surname=Strummer

    let q = q!("cross" => r#"{"members": {"given": ["Mick"], "surname": ["Strummer"]}}"#);

    let event = r#"{"members": [
        {"given": "Joe", "surname": "Strummer"},
        {"given": "Mick", "surname": "Jones"}
    ]}"#;

    // Should NOT match - cross-element matching is correctly prevented
    assert_no_match!(q, event, "Should not match across different array elements");
}

#[test]
fn test_array_cross_element_comprehensive() {
    // Comprehensive test from Go's arrays_test.go TestArrayCorrectness
    let bands = r#"{
        "bands": [
            {
                "name": "The Clash",
                "members": [
                    {"given": "Joe", "surname": "Strummer", "role": ["guitar", "vocals"]},
                    {"given": "Mick", "surname": "Jones", "role": ["guitar", "vocals"]},
                    {"given": "Paul", "surname": "Simonon", "role": ["bass"]},
                    {"given": "Topper", "surname": "Headon", "role": ["drums"]}
                ]
            },
            {
                "name": "Boris",
                "members": [
                    {"given": "Wata", "role": ["guitar", "vocals"]},
                    {"given": "Atsuo", "role": ["drums"]},
                    {"given": "Takeshi", "role": ["bass", "vocals"]}
                ]
            }
        ]
    }"#;

    let q = q!(
        // Pattern 1: Mick with surname Strummer - SHOULD NOT match (cross-element)
        "mick_strummer" => r#"{"bands": {"members": {"given": ["Mick"], "surname": ["Strummer"]}}}"#,
        // Pattern 2: Wata with role drums - SHOULD NOT match (cross-element)
        "wata_drums" => r#"{"bands": {"members": {"given": ["Wata"], "role": ["drums"]}}}"#,
        // Pattern 3: Wata with role guitar - SHOULD match (same element)
        "wata_guitar" => r#"{"bands": {"members": {"given": ["Wata"], "role": ["guitar"]}}}"#
    );

    assert_match_count!(q, bands, 1);
    assert_has_match!(q, bands, "wata_guitar");
    assert_no_has_match!(q, bands, "mick_strummer");
    assert_no_has_match!(q, bands, "wata_drums");
}

// ============================================================================
// Multiple Patterns Tests
// ============================================================================

#[test]
fn test_multiple_patterns_same_id() {
    // Multiple patterns with same ID - any match counts
    let q = q!(
        "p1" => r#"{"status": ["active"]}"#,
        "p1" => r#"{"status": ["pending"]}"#
    );

    assert_matches!(q, r#"{"status": "active"}"#, vec!["p1"]);
    assert_matches!(q, r#"{"status": "pending"}"#, vec!["p1"]);
}

#[test]
fn test_or_within_field() {
    // Multiple values in array = OR
    let q = q!("p1" => r#"{"status": ["active", "pending", "review"]}"#);

    for status in &["active", "pending", "review"] {
        let event = format!(r#"{{"status": "{}"}}"#, status);
        assert_matches!(q, event, vec!["p1"]);
    }

    assert_no_match!(q, r#"{"status": "deleted"}"#);
}

#[test]
fn test_and_across_fields() {
    // Multiple fields = AND
    let q = q!(
        "p1" => r#"{"type": ["order"], "status": ["pending"], "priority": ["high"]}"#
    );

    assert_matches!(
        q,
        r#"{"type": "order", "status": "pending", "priority": "high"}"#,
        vec!["p1"]
    );

    // Missing one field
    assert_no_match!(q, r#"{"type": "order", "status": "pending"}"#);
}

// ============================================================================
// Delete and Rebuild Tests
// ============================================================================

#[test]
fn test_delete_patterns() {
    let mut q = Quamina::new();
    q.add_pattern("p1", r#"{"status": ["active"]}"#).unwrap();
    q.add_pattern("p2", r#"{"status": ["pending"]}"#).unwrap();

    // Both match initially
    assert_has_match!(q, r#"{"status": "active"}"#, "p1");

    // Delete p1
    q.delete_patterns(&"p1").unwrap();

    // p1 no longer matches
    assert_no_match!(q, r#"{"status": "active"}"#);

    // p2 still works
    assert_has_match!(q, r#"{"status": "pending"}"#, "p2");
}

#[test]
fn test_rebuild_after_delete() {
    let mut q = Quamina::new();
    q.add_pattern("p1", r#"{"status": ["active"]}"#).unwrap();
    q.add_pattern("p2", r#"{"status": ["pending"]}"#).unwrap();
    q.add_pattern("p3", r#"{"status": ["review"]}"#).unwrap();

    // Initial count
    assert_eq!(q.pattern_count(), 3);

    // Delete p1
    q.delete_patterns(&"p1").unwrap();
    assert_eq!(q.pattern_count(), 2);

    // p1 is in deleted set
    assert!(q.deleted_patterns.contains(&"p1"));

    // Rebuild should purge deleted patterns
    let purged = q.rebuild();
    assert_eq!(purged, 1);

    // After rebuild, deleted set is clear
    assert!(q.deleted_patterns.is_empty());
    assert_eq!(q.pattern_count(), 2);

    // p2 and p3 still work
    assert_has_match!(q, r#"{"status": "pending"}"#, "p2");
    assert_has_match!(q, r#"{"status": "review"}"#, "p3");

    // p1 does not match (and is not in deleted set, was purged)
    assert_no_match!(q, r#"{"status": "active"}"#);
}

#[test]
fn test_pruner_stats() {
    let mut q = Quamina::new();
    q.add_pattern("p1", r#"{"status": ["active"]}"#).unwrap();
    q.add_pattern("p2", r#"{"status": ["pending"]}"#).unwrap();

    // Initially stats are zero
    assert_eq!(q.pruner_stats().emitted(), 0);
    assert_eq!(q.pruner_stats().filtered(), 0);

    // Match - should increment emitted
    let _ = q
        .matches_for_event(r#"{"status": "active"}"#.as_bytes())
        .unwrap();
    assert_eq!(q.pruner_stats().emitted(), 1);
    assert_eq!(q.pruner_stats().filtered(), 0);

    // Delete p1
    q.delete_patterns(&"p1").unwrap();

    // Match active - should increment filtered (was deleted)
    let _ = q
        .matches_for_event(r#"{"status": "active"}"#.as_bytes())
        .unwrap();
    assert_eq!(q.pruner_stats().emitted(), 1);
    assert_eq!(q.pruner_stats().filtered(), 1);

    // Match pending - should increment emitted
    let _ = q
        .matches_for_event(r#"{"status": "pending"}"#.as_bytes())
        .unwrap();
    assert_eq!(q.pruner_stats().emitted(), 2);
    assert_eq!(q.pruner_stats().filtered(), 1);

    // Rebuild resets stats
    q.rebuild();
    assert_eq!(q.pruner_stats().emitted(), 0);
    assert_eq!(q.pruner_stats().filtered(), 0);
}

// MIRI SKIP RATIONALE: 500 iterations of matches_for_event with 5 patterns takes ~48s under
// Miri. Coverage: test_should_rebuild_threshold_miri_friendly exercises the same rebuild
// threshold logic with fewer iterations.
#[test]
#[cfg_attr(miri, ignore)]
fn test_should_rebuild_threshold() {
    let mut q = Quamina::new();

    // Add patterns that will match many events
    q.add_pattern("p1", r#"{"x": ["a"]}"#).unwrap();
    q.add_pattern("p2", r#"{"x": ["a"]}"#).unwrap();
    q.add_pattern("p3", r#"{"x": ["a"]}"#).unwrap();
    q.add_pattern("p4", r#"{"x": ["a"]}"#).unwrap();
    q.add_pattern("p5", r#"{"x": ["a"]}"#).unwrap();

    // Delete half
    q.delete_patterns(&"p1").unwrap();
    q.delete_patterns(&"p2").unwrap();

    // Not enough activity yet - should not trigger rebuild
    assert!(!q.should_rebuild());

    // Simulate lots of matches
    let event = br#"{"x": "a"}"#;
    for _ in 0..500 {
        let _ = q.matches_for_event(event).unwrap();
    }

    // After 500 matches with 5 patterns, 3 emit, 2 filtered
    // filtered = 500 * 2 = 1000
    // emitted = 500 * 3 = 1500
    // Total activity = 2500 > 1000 threshold
    // Ratio = 1000/1500 = 0.67 > 0.2
    assert!(q.should_rebuild());

    // maybe_rebuild should trigger
    let purged = q.maybe_rebuild();
    assert_eq!(purged, 2);

    // After rebuild, no longer needs rebuild
    assert!(!q.should_rebuild());
}

/// Miri-only: exercises the same rebuild threshold logic with 100 iterations instead of 500.
/// With 3 patterns (2 deleted, 1 remaining), 100 matches yields:
///   filtered = 100 * 2 = 200, emitted = 100 * 1 = 100, total = 300.
/// We use 3 patterns total so threshold math still triggers (needs total > 1000 with
/// ratio > 0.2). We run 400 iterations: filtered=800, emitted=400, total=1200 > 1000,
/// ratio=800/400=2.0 > 0.2.
#[test]
#[cfg(miri)]
fn test_should_rebuild_threshold_miri_friendly() {
    let mut q = Quamina::new();

    q.add_pattern("p1", r#"{"x": ["a"]}"#).unwrap();
    q.add_pattern("p2", r#"{"x": ["a"]}"#).unwrap();
    q.add_pattern("p3", r#"{"x": ["a"]}"#).unwrap();

    q.delete_patterns(&"p1").unwrap();
    q.delete_patterns(&"p2").unwrap();

    assert!(!q.should_rebuild());

    let event = br#"{"x": "a"}"#;
    // 400 iterations: filtered=800, emitted=400, total=1200 > 1000
    for _ in 0..400 {
        let _ = q.matches_for_event(event).unwrap();
    }

    assert!(q.should_rebuild());

    let purged = q.maybe_rebuild();
    assert_eq!(purged, 2);

    assert!(!q.should_rebuild());
}

// MIRI SKIP RATIONALE: 2000 iterations of matches_for_event is slow under Miri (~100s).
// Coverage: test_auto_rebuild_disabled_miri_friendly exercises same logic with 5 iterations.
#[test]
#[cfg_attr(miri, ignore)]
fn test_auto_rebuild_disabled() {
    let mut q = Quamina::new();
    q.set_auto_rebuild(false);

    q.add_pattern("p1", r#"{"x": ["a"]}"#).unwrap();
    q.add_pattern("p2", r#"{"x": ["a"]}"#).unwrap();

    q.delete_patterns(&"p1").unwrap();

    // Simulate enough activity to trigger
    let event = br#"{"x": "a"}"#;
    for _ in 0..2000 {
        let _ = q.matches_for_event(event).unwrap();
    }

    // Should want rebuild but auto is disabled
    assert!(q.should_rebuild());

    // maybe_rebuild returns 0 when disabled
    let purged = q.maybe_rebuild();
    assert_eq!(purged, 0);
}

/// Miri-friendly version of test_auto_rebuild_disabled
#[test]
fn test_auto_rebuild_disabled_miri_friendly() {
    let mut q = Quamina::new();
    q.set_auto_rebuild(false);

    q.add_pattern("p1", r#"{"x": ["a"]}"#).unwrap();
    q.add_pattern("p2", r#"{"x": ["a"]}"#).unwrap();

    q.delete_patterns(&"p1").unwrap();

    // Small number of iterations
    let event = br#"{"x": "a"}"#;
    for _ in 0..5 {
        let _ = q.matches_for_event(event).unwrap();
    }

    // maybe_rebuild returns 0 when disabled
    let purged = q.maybe_rebuild();
    assert_eq!(purged, 0);
}

// ============================================================================
// Clone and Thread Safety Tests
// ============================================================================

#[test]
fn test_clone_for_snapshot() {
    let mut q = Quamina::new();
    q.add_pattern("p1", r#"{"status": ["active"]}"#).unwrap();

    // Clone creates an independent snapshot
    let snapshot = q.clone();

    // Modify original
    q.add_pattern("p2", r#"{"status": ["pending"]}"#).unwrap();

    // Snapshot doesn't have p2
    assert_no_match!(snapshot, r#"{"status": "pending"}"#);

    // Original has p2
    assert_has_match!(q, r#"{"status": "pending"}"#, "p2");
}

#[test]
fn test_send_sync() {
    // Verify Quamina is Send + Sync for thread safety
    fn assert_send_sync<T: Send + Sync>() {}
    assert_send_sync::<Quamina<String>>();
}

#[test]
fn test_has_matches() {
    let q = q!("p1" => r#"{"status": ["active"]}"#);

    assert!(q.has_matches(r#"{"status": "active"}"#.as_bytes()).unwrap());
    assert!(!q
        .has_matches(r#"{"status": "inactive"}"#.as_bytes())
        .unwrap());
}

#[test]
fn test_count_matches() {
    let q = q!(
        "p1" => r#"{"status": ["active"]}"#,
        "p2" => r#"{"status": ["active"]}"#,
        "p3" => r#"{"status": ["pending"]}"#
    );

    assert_eq!(
        q.count_matches(r#"{"status": "active"}"#.as_bytes())
            .unwrap(),
        2
    );
    assert_eq!(
        q.count_matches(r#"{"status": "pending"}"#.as_bytes())
            .unwrap(),
        1
    );
    assert_eq!(
        q.count_matches(r#"{"status": "deleted"}"#.as_bytes())
            .unwrap(),
        0
    );
}

#[test]
fn test_pattern_count_and_clear() {
    let mut q = Quamina::new();
    assert!(q.is_empty());
    assert_eq!(q.pattern_count(), 0);

    q.add_pattern("p1", r#"{"a": ["1"]}"#).unwrap();
    q.add_pattern("p2", r#"{"b": ["2"]}"#).unwrap();
    assert!(!q.is_empty());
    assert_eq!(q.pattern_count(), 2);

    q.clear();
    assert!(q.is_empty());
    assert_eq!(q.pattern_count(), 0);
}

// ============================================================================
// Error Handling Tests
// ============================================================================

#[test]
fn test_invalid_json_events() {
    // Based on Go quamina's TestFJErrorCases
    let q = q!("p1" => r#"{"a": [1]}"#);

    let bad_events: &[(&[u8], &str)] = &[
        // Truncated JSON
        (br#"{"a"#, "Truncated JSON"),
        (br#"{"a": "#, "Truncated value"),
        (br#"{"a": ["#, "Truncated array"),
        // Empty input
        (b"", "Empty input"),
        // Non-object at top level
        (br#""string""#, "String at top level"),
        (br#"[1, 2]"#, "Array at top level"),
        (b"123", "Number at top level"),
        // Malformed JSON
        (br#"{ "a" : }"#, "Missing value"),
        // Invalid escape sequences
        (br#"{"a": "a\zb"}"#, "Invalid escape \\z in value"),
        (br#"{"a\zb": 2}"#, "Invalid escape in field name"),
        // Invalid value identifier
        (br#"{"a": xx}"#, "Invalid value xx"),
        // Truncated/invalid literals
        (br#"{"a": tru}"#, "Truncated 'tru'"),
        (br#"{"a": truse}"#, "Invalid 'truse'"),
    ];

    for (event, desc) in bad_events {
        assert!(q.matches_for_event(event).is_err(), "{} should error", desc);
    }
}

#[test]
fn test_invalid_pattern_handling() {
    let mut q = Quamina::new();

    // Empty pattern
    assert!(q.add_pattern("p1", "").is_err());

    // Non-object at top level
    assert!(q.add_pattern("p2", "33").is_err());
    assert!(q.add_pattern("p3", "[1,2]").is_err());

    // Malformed JSON
    assert!(q.add_pattern("p4", "{").is_err());
    assert!(q.add_pattern("p5", r#"{"foo": }"#).is_err());

    // Pattern field must be array or nested object
    assert!(q.add_pattern("p6", r#"{"foo": "string"}"#).is_err());
    assert!(q.add_pattern("p7", r#"{"foo": 123}"#).is_err());
    assert!(q.add_pattern("p8", r#"{"foo": true}"#).is_err());

    // Valid patterns should work
    assert!(q.add_pattern("valid1", r#"{"x": [1]}"#).is_ok());
    assert!(q.add_pattern("valid2", r#"{"x": ["string"]}"#).is_ok());
    assert!(q.add_pattern("valid3", r#"{"x": {"y": [1]}}"#).is_ok());
}

#[test]
fn test_bad_pattern_error_handling() {
    let mut q = Quamina::new();

    // Go quamina returns errors for these patterns (anything_but_test.go:134)
    // Empty anything-but
    assert!(q
        .add_pattern("p1", r#"{"x": [{"anything-but": []}]}"#)
        .is_err());

    // Mixed types in anything-but
    assert!(q
        .add_pattern("p2", r#"{"x": [{"anything-but": ["a", 1]}]}"#)
        .is_err());
}

#[test]
fn test_bad_event_error_handling() {
    let q = q!("p1" => r#"{"x": [1]}"#);

    // Invalid JSON
    assert!(q.matches_for_event(b"not json").is_err());
    assert!(q.matches_for_event(b"{").is_err());
    assert!(q.matches_for_event(b"").is_err());
}

#[test]
fn test_rebuild_zero_filtered_denominator() {
    let mut q = Quamina::new();

    // Add and immediately delete a pattern
    q.add_pattern("p1", r#"{"likes": ["tacos"]}"#).unwrap();
    q.delete_patterns(&"p1").unwrap();

    // Matching should not panic with zero patterns
    let result = q.matches_for_event(r#"{"likes": "tacos"}"#.as_bytes());
    assert!(result.is_ok(), "Should not panic with empty matcher");
    assert!(result.unwrap().is_empty(), "No matches expected");
}

// ============================================================================
// Builder API Tests
// ============================================================================

#[test]
fn test_builder_basic() {
    let q = QuaminaBuilder::<String>::new().build().unwrap();
    assert!(q.is_empty(), "New builder should create empty matcher");
    assert!(
        q.auto_rebuild_enabled(),
        "Auto-rebuild should be enabled by default"
    );
}

#[test]
fn test_builder_with_media_type_json() {
    let q = QuaminaBuilder::<String>::new()
        .with_media_type("application/json")
        .unwrap()
        .build()
        .unwrap();
    assert!(q.is_empty());
}

#[test]
fn test_builder_with_invalid_media_type() {
    let result = QuaminaBuilder::<String>::new().with_media_type("text/html");
    assert!(result.is_err(), "Should reject text/html");

    if let Err(QuaminaError::UnsupportedMediaType(mt)) = result {
        assert_eq!(mt, "text/html");
    } else {
        panic!("Expected UnsupportedMediaType error");
    }

    // Test other invalid types
    let result = QuaminaBuilder::<String>::new().with_media_type("application/xml");
    assert!(result.is_err(), "Should reject application/xml");

    let result = QuaminaBuilder::<String>::new().with_media_type("");
    assert!(result.is_err(), "Should reject empty media type");
}

#[test]
fn test_builder_with_auto_rebuild() {
    // Disable auto-rebuild
    let q = QuaminaBuilder::<String>::new()
        .with_auto_rebuild(false)
        .build()
        .unwrap();
    assert!(!q.auto_rebuild_enabled(), "Auto-rebuild should be disabled");

    // Enable auto-rebuild (explicit)
    let q = QuaminaBuilder::<String>::new()
        .with_auto_rebuild(true)
        .build()
        .unwrap();
    assert!(q.auto_rebuild_enabled(), "Auto-rebuild should be enabled");
}

#[test]
fn test_builder_combined_options() {
    let mut q = QuaminaBuilder::<String>::new()
        .with_media_type("application/json")
        .unwrap()
        .with_auto_rebuild(false)
        .build()
        .unwrap();

    q.add_pattern("p1".to_string(), r#"{"status": ["active"]}"#)
        .unwrap();
    let matches = q
        .matches_for_event(r#"{"status": "active"}"#.as_bytes())
        .unwrap();
    assert_eq!(matches, vec!["p1".to_string()]);
    assert!(!q.auto_rebuild_enabled());
}

#[test]
fn test_builder_default() {
    let q = QuaminaBuilder::<String>::default().build().unwrap();
    assert!(q.is_empty());
    assert!(q.auto_rebuild_enabled());
}

#[test]
fn test_builder_generic_type() {
    // With i32 as pattern ID
    let mut q = QuaminaBuilder::<i32>::new().build().unwrap();
    q.add_pattern(42, r#"{"x": [1]}"#).unwrap();
    let matches = q.matches_for_event(r#"{"x": 1}"#.as_bytes()).unwrap();
    assert_eq!(matches, vec![42]);

    // With &str as pattern ID
    let mut q = QuaminaBuilder::<&str>::new().build().unwrap();
    q.add_pattern("test", r#"{"x": [1]}"#).unwrap();
    let matches = q.matches_for_event(r#"{"x": 1}"#.as_bytes()).unwrap();
    assert_eq!(matches, vec!["test"]);
}

// ============================================================================
// Custom Flattener Tests
// ============================================================================

/// A simple custom flattener that returns hardcoded fields for testing
struct MockFlattener {
    fields: Vec<OwnedField>,
}

impl MockFlattener {
    fn new(fields: Vec<OwnedField>) -> Self {
        Self { fields }
    }
}

impl Flattener for MockFlattener {
    fn flatten(
        &mut self,
        _event: &[u8],
        _tracker: &dyn SegmentsTreeTracker,
    ) -> Result<Vec<OwnedField>, QuaminaError> {
        Ok(self.fields.clone())
    }

    fn copy(&self) -> Box<dyn Flattener> {
        Box::new(MockFlattener {
            fields: self.fields.clone(),
        })
    }
}

#[test]
fn test_custom_flattener_basic() {
    // Create a custom flattener that always returns a specific field
    // Note: path doesn't have trailing newline, string values need quotes
    let flattener = MockFlattener::new(vec![OwnedField {
        path: b"status".to_vec(),
        val: b"\"active\"".to_vec(),
        array_trail: vec![],
        is_number: false,
    }]);

    let mut q = QuaminaBuilder::<String>::new()
        .with_flattener(Box::new(flattener))
        .unwrap()
        .build()
        .unwrap();

    q.add_pattern("p1".to_string(), r#"{"status": ["active"]}"#)
        .unwrap();

    // The custom flattener ignores the event and returns "status": "active"
    let matches = q.matches_for_event(b"ignored event data").unwrap();
    assert_eq!(matches, vec!["p1".to_string()]);
}

#[test]
fn test_custom_flattener_no_match() {
    // Create a custom flattener that returns a different field
    let flattener = MockFlattener::new(vec![OwnedField {
        path: b"status".to_vec(),
        val: b"\"inactive\"".to_vec(),
        array_trail: vec![],
        is_number: false,
    }]);

    let mut q = QuaminaBuilder::<String>::new()
        .with_flattener(Box::new(flattener))
        .unwrap()
        .build()
        .unwrap();

    q.add_pattern("p1".to_string(), r#"{"status": ["active"]}"#)
        .unwrap();

    let matches = q.matches_for_event(b"ignored").unwrap();
    assert!(matches.is_empty());
}

#[test]
fn test_custom_flattener_with_numbers() {
    let flattener = MockFlattener::new(vec![OwnedField {
        path: b"count".to_vec(),
        val: b"42".to_vec(),
        array_trail: vec![],
        is_number: true,
    }]);

    let mut q = QuaminaBuilder::<String>::new()
        .with_flattener(Box::new(flattener))
        .unwrap()
        .build()
        .unwrap();

    q.add_pattern("p1".to_string(), r#"{"count": [42]}"#)
        .unwrap();

    let matches = q.matches_for_event(b"ignored").unwrap();
    assert_eq!(matches, vec!["p1".to_string()]);
}

#[test]
fn test_custom_flattener_clone() {
    let flattener = MockFlattener::new(vec![OwnedField {
        path: b"x".to_vec(),
        val: b"\"y\"".to_vec(),
        array_trail: vec![],
        is_number: false,
    }]);

    let mut q = QuaminaBuilder::<String>::new()
        .with_flattener(Box::new(flattener))
        .unwrap()
        .build()
        .unwrap();

    q.add_pattern("p1".to_string(), r#"{"x": ["y"]}"#).unwrap();

    // Clone the Quamina instance
    let q_clone = q.clone();

    // Both should match
    let m1 = q.matches_for_event(b"ignored").unwrap();
    let m2 = q_clone.matches_for_event(b"ignored").unwrap();
    assert_eq!(m1, vec!["p1".to_string()]);
    assert_eq!(m2, vec!["p1".to_string()]);
}

#[test]
fn test_with_flattener_conflicts_with_media_type() {
    let flattener = MockFlattener::new(vec![]);

    // Should fail if media type is set first
    let result = QuaminaBuilder::<String>::new()
        .with_media_type("application/json")
        .unwrap()
        .with_flattener(Box::new(flattener));

    assert!(result.is_err());
}

#[test]
fn test_with_flattener_cannot_be_set_twice() {
    let flattener1 = MockFlattener::new(vec![]);
    let flattener2 = MockFlattener::new(vec![]);

    let result = QuaminaBuilder::<String>::new()
        .with_flattener(Box::new(flattener1))
        .unwrap()
        .with_flattener(Box::new(flattener2));

    assert!(result.is_err());
}

#[test]
fn test_json_flattener_through_trait() {
    // Test that the built-in JsonFlattener works through the Flattener trait
    use crate::flattener::JsonFlattener;

    let mut q = QuaminaBuilder::<String>::new()
        .with_flattener(Box::new(JsonFlattener::new()))
        .unwrap()
        .build()
        .unwrap();

    q.add_pattern("p1".to_string(), r#"{"status": ["active"]}"#)
        .unwrap();

    let matches = q
        .matches_for_event(r#"{"status": "active"}"#.as_bytes())
        .unwrap();
    assert_eq!(matches, vec!["p1"]);
}

// ============================================================================
// Additional Core Tests (recovered from original)
// ============================================================================

#[test]
fn test_same_pattern_id_multiple_value_types() {
    // Based on Go quamina's TestExerciseSingletonReplacement and TestMergeNfaAndNumeric
    // Same pattern ID can match via different value types (string OR number)
    let q = q!("x" => r#"{"x": ["a"]}"#, "x" => r#"{"x": [1]}"#);

    // Both string and number should match pattern "x"
    assert_matches!(q, r#"{"x": 1}"#, vec!["x"], "number 1 should match");
    assert_matches!(q, r#"{"x": "a"}"#, vec!["x"], "string 'a' should match");

    // Test wildcard OR number for same pattern ID
    let q2 = q!("x" => r#"{"x": [{"wildcard": "x*y"}]}"#, "x" => r#"{"x": [3]}"#);

    assert_matches!(q2, r#"{"x": 3}"#, vec!["x"], "number 3 should match");
    assert_matches!(
        q2,
        r#"{"x": "xasdfy"}"#,
        vec!["x"],
        "wildcard pattern should match"
    );
}

#[test]
fn test_field_name_ordering_with_exists() {
    // Based on Go quamina's TestFieldNameOrdering
    // Tests patterns with exists:false against a simple event with field "b"
    // All patterns should match because the absent fields (a, c) don't exist
    let event = r#"{"b": 1}"#;

    let patterns = [
        // b=1 AND a doesn't exist (true - a is absent)
        (r#"{"b": [1], "a": [{"exists": false}]}"#, "p0"),
        // b=1 AND c doesn't exist (true - c is absent)
        (r#"{"b": [1], "c": [{"exists": false}]}"#, "p1"),
        // b=1 (true)
        (r#"{"b": [1]}"#, "p2"),
        // a doesn't exist (true - a is absent)
        (r#"{"a": [{"exists": false}]}"#, "p3"),
    ];

    // Add all patterns and verify all match
    let mut q = Quamina::new();
    for (pattern, name) in &patterns {
        q.add_pattern(*name, pattern).unwrap();
    }

    assert_match_count!(q, event, patterns.len());
    for (_, name) in &patterns {
        assert_has_match!(q, event, *name);
    }
}

#[test]
fn test_invalid_pattern_validation() {
    // Based on Go quamina's TestPatternFromJSON
    // Tests that various invalid patterns are properly rejected
    let invalid_patterns = [
        // Value not in array (must be array or object)
        (r#"{"foo": 11}"#, "number not in array"),
        (r#"{"foo": "x"}"#, "string not in array"),
        (r#"{"foo": true}"#, "boolean not in array"),
        (r#"{"foo": null}"#, "null not in array"),
        // Invalid exists operator
        (r#"{"x": [{"exists": 23}]}"#, "exists with number"),
        (r#"{"x": [{"exists": "yes"}]}"#, "exists with string"),
        // Invalid shellstyle
        (r#"{"x": [{"shellstyle": 15}]}"#, "shellstyle with number"),
        (r#"{"x": [{"shellstyle": "a**b"}]}"#, "shellstyle with **"),
        // Invalid prefix
        (r#"{"x": [{"prefix": 23}]}"#, "prefix with number"),
        // Invalid suffix
        (r#"{"x": [{"suffix": 23}]}"#, "suffix with number"),
        // Invalid equals-ignore-case
        (
            r#"{"x": [{"equals-ignore-case": 5}]}"#,
            "equals-ignore-case with number",
        ),
        // Invalid numeric
        (r#"{"x": [{"numeric": ">=5"}]}"#, "numeric with string"),
        // Invalid regex
        (
            r#"{"x": [{"regex": "[invalid"}]}"#,
            "regex with invalid pattern",
        ),
        // Unknown operator
        (r#"{"x": [{"unknown-op": "val"}]}"#, "unknown operator"),
    ];

    for (pattern, desc) in &invalid_patterns {
        let mut q = Quamina::new();
        let result = q.add_pattern("test", pattern);
        assert!(result.is_err(), "{} should be rejected: {}", desc, pattern);
    }
}

#[test]
fn test_numbits_boundary_values() {
    // Test float64 boundary values for numeric matching
    use crate::numbits::{numbits_from_f64, q_num_from_f64, to_q_number};

    // Float64 boundary categories:
    // - Subnormal (smallest positive): 2^-1074 to 2^-1022
    // - Normal minimum: 2^-1022 ~ 2.225e-308
    // - Normal maximum: (2 - 2^-52) x 2^1023 ~ 1.798e+308

    // Test zero
    let nb_zero = numbits_from_f64(0.0);
    let q_zero = q_num_from_f64(0.0);
    assert!(nb_zero > 0, "Zero should have non-zero numbits");
    assert!(!q_zero.is_empty(), "Zero should have non-empty Q-number");

    // Test smallest positive subnormal: f64::MIN_POSITIVE / 2^52 ~ 4.94e-324
    let smallest_subnormal = 5e-324_f64;
    let nb_small = numbits_from_f64(smallest_subnormal);
    let q_small = q_num_from_f64(smallest_subnormal);
    assert!(nb_small > nb_zero, "Smallest subnormal > 0");
    assert!(
        q_small > q_zero,
        "Smallest subnormal Q-number > zero Q-number"
    );

    // Test smallest normal: f64::MIN_POSITIVE ~ 2.225e-308
    let smallest_normal = f64::MIN_POSITIVE;
    let nb_min_normal = numbits_from_f64(smallest_normal);
    let q_min_normal = q_num_from_f64(smallest_normal);
    assert!(
        nb_min_normal > nb_small,
        "Smallest normal > smallest subnormal"
    );
    assert!(q_min_normal > q_small, "Q-number ordering preserved");

    // Test largest normal: f64::MAX ~ 1.798e+308
    let largest_normal = f64::MAX;
    let nb_max = numbits_from_f64(largest_normal);
    let q_max = q_num_from_f64(largest_normal);
    assert!(nb_max > nb_min_normal, "Max > min positive");
    assert!(q_max > q_min_normal, "Q-number ordering preserved");

    // Test negative boundaries
    let nb_neg_max = numbits_from_f64(-f64::MAX);
    let nb_neg_min = numbits_from_f64(-f64::MIN_POSITIVE);
    let nb_neg_small = numbits_from_f64(-5e-324_f64);

    // Negative ordering: -MAX < -MIN_POSITIVE < -subnormal < 0
    assert!(nb_neg_max < nb_neg_min, "-MAX < -MIN_POSITIVE");
    assert!(nb_neg_min < nb_neg_small, "-MIN_POSITIVE < -subnormal");
    assert!(nb_neg_small < nb_zero, "-subnormal < 0");

    // Test that all Q-numbers are valid (bytes in 0-127 range)
    let test_values = [
        0.0,
        1.0,
        -1.0,
        f64::MIN_POSITIVE,
        f64::MAX,
        -f64::MAX,
        5e-324,
        -5e-324,
        1e100,
        -1e100,
        0.5,
        -0.5,
    ];
    for &val in &test_values {
        let q = q_num_from_f64(val);
        for &byte in &q {
            assert!(
                byte < 128,
                "Q-number byte {} >= 128 for value {}",
                byte,
                val
            );
        }
    }

    // Test numbits round-trip consistency
    for &val in &test_values {
        let nb = numbits_from_f64(val);
        let q1 = q_num_from_f64(val);
        let q2 = to_q_number(nb);
        assert_eq!(q1, q2, "Q-number should match via both paths for {}", val);
    }
}

#[test]
#[cfg_attr(miri, ignore)]
fn test_numbits_to_qnumber_utf8() {
    // Test that Q-numbers are valid for automaton processing
    // Q-numbers use base-128 encoding (bytes 0-127), which is ASCII-compatible
    use crate::numbits::q_num_from_f64;

    // Generate 10K random floats and verify Q-number properties
    let mut rng_state = 0xDEADBEEF_u64;

    for i in 0..10_000 {
        // Simple LCG for reproducibility
        rng_state = rng_state
            .wrapping_mul(6364136223846793005)
            .wrapping_add(1442695040888963407);

        // Generate a random f64 in a wide range
        let sign = if rng_state & 1 == 0 { 1.0 } else { -1.0 };
        let exp = ((rng_state >> 1) % 600) as i32 - 300; // -300 to +299
        let mantissa = ((rng_state >> 10) as f64) / (1u64 << 54) as f64;
        let val = sign * (1.0 + mantissa) * 10f64.powi(exp);

        // Skip if not finite (shouldn't happen with our construction, but be safe)
        if !val.is_finite() {
            continue;
        }

        let q = q_num_from_f64(val);

        // Property 1: Non-empty
        assert!(
            !q.is_empty(),
            "Q-number should be non-empty for value at index {}",
            i
        );

        // Property 2: All bytes < 128 (valid for automaton)
        for (j, &byte) in q.iter().enumerate() {
            assert!(
                byte < 128,
                "Q-number byte {} at pos {} >= 128 for value at index {}",
                byte,
                j,
                i
            );
        }

        // Property 3: Valid UTF-8 (since all bytes are ASCII)
        assert!(
            std::str::from_utf8(&q).is_ok(),
            "Q-number should be valid UTF-8 for value at index {}",
            i
        );

        // Property 4: Length bounded
        assert!(
            q.len() <= 10,
            "Q-number length {} exceeds max 10 for value at index {}",
            q.len(),
            i
        );
    }

    // Test ordering preservation across 1000 random pairs
    let mut prev_val = f64::NEG_INFINITY;
    let mut prev_q = q_num_from_f64(-1e308);

    rng_state = 0x12345678_u64;
    let mut ordered_vals: Vec<f64> = Vec::new();

    for _ in 0..1000 {
        rng_state = rng_state.wrapping_mul(6364136223846793005).wrapping_add(1);
        let val = ((rng_state as f64) / (u64::MAX as f64)) * 2e100 - 1e100;
        if val.is_finite() {
            ordered_vals.push(val);
        }
    }

    ordered_vals.sort_by(|a, b| a.partial_cmp(b).unwrap());

    for val in ordered_vals {
        let q = q_num_from_f64(val);
        if prev_val < val {
            assert!(
                prev_q <= q,
                "Q-number ordering violated: {} ({:?}) should be <= {} ({:?})",
                prev_val,
                prev_q,
                val,
                q
            );
        }
        prev_val = val;
        prev_q = q;
    }
}

#[test]
fn test_multi_condition_pattern_fields() {
    // Test MultiConditionPattern structure
    use crate::json::{LookaroundCondition, MultiConditionPattern};
    use crate::regexp::parse_regexp;

    // Create a multi-condition pattern manually
    let primary = parse_regexp("foo").unwrap();
    let combined = parse_regexp("foobar").unwrap();
    let conditions = vec![LookaroundCondition::PositiveLookahead(combined)];

    let mc = MultiConditionPattern::new(primary, conditions);

    // Verify structure
    assert_eq!(mc.primary.len(), 1, "Primary should have 1 branch");
    assert_eq!(mc.conditions.len(), 1, "Should have 1 condition");
    assert!(!mc.conditions[0].is_negative(), "Should be positive");
    assert!(
        !mc.conditions[0].is_lookbehind(),
        "Should not be lookbehind"
    );
}

#[test]
fn test_condition_cost_ordering() {
    // Test that conditions are sorted by cost
    use crate::json::{LookaroundCondition, MultiConditionPattern};
    use crate::regexp::parse_regexp;

    let primary = parse_regexp("test").unwrap();
    let pattern1 = parse_regexp("a").unwrap();
    let pattern2 = parse_regexp("b").unwrap();
    let pattern3 = parse_regexp("c").unwrap();

    // Create conditions in reverse cost order
    let conditions = vec![
        LookaroundCondition::NegativeLookbehind {
            pattern: pattern3.clone(),
            byte_length: 1,
        }, // cost 40
        LookaroundCondition::PositiveLookbehind {
            pattern: pattern2.clone(),
            byte_length: 1,
        }, // cost 30
        LookaroundCondition::NegativeLookahead(pattern1.clone()), // cost 20
    ];

    let mc = MultiConditionPattern::new(primary, conditions);

    // Verify conditions are sorted by cost (lowest first)
    assert_eq!(
        mc.conditions[0].cost_estimate(),
        20,
        "First should be cost 20"
    );
    assert_eq!(
        mc.conditions[1].cost_estimate(),
        30,
        "Second should be cost 30"
    );
    assert_eq!(
        mc.conditions[2].cost_estimate(),
        40,
        "Third should be cost 40"
    );
}

#[test]
fn test_string_number_type_distinction() {
    // Verify that string patterns don't match number events and vice versa.
    // In Go, the outer quotes on string values act as an implicit type tag
    // (NFA expects `"123"` for strings vs `123` for numbers).
    // In Rust, quotes are stripped by value_bytes(), so we need to verify
    // the type distinction is maintained by other means.

    let q = q!("string_pat" => r#"{"key": ["123"]}"#);

    // String "123" SHOULD match
    assert_matches!(
        q,
        r#"{"key": "123"}"#,
        vec!["string_pat"],
        "String '123' should match string pattern '123'"
    );

    // Number 123 should NOT match string pattern "123"
    assert_no_match!(
        q,
        r#"{"key": 123}"#,
        "Number 123 should NOT match string pattern '123' - type distinction must be preserved"
    );
}

#[test]
fn test_numeric_pattern_should_not_match_string_event() {
    // The reverse: numeric pattern should not match a string with the same digits
    let q = q!("num_pat" => r#"{"key": [42]}"#);

    // Number 42 SHOULD match
    assert_matches!(
        q,
        r#"{"key": 42}"#,
        vec!["num_pat"],
        "Number 42 should match numeric pattern"
    );

    // String "42" should NOT match numeric pattern
    assert_no_match!(
        q,
        r#"{"key": "42"}"#,
        "String '42' should NOT match numeric pattern 42"
    );
}

#[test]
fn test_mixed_string_and_number_patterns_same_digits() {
    // Both a string pattern and a numeric pattern for "123"/123
    let q = q!("str" => r#"{"key": ["123"]}"#, "num" => r#"{"key": [123]}"#);

    // String event should only match string pattern
    assert_matches!(
        q,
        r#"{"key": "123"}"#,
        vec!["str"],
        "String '123' should match only string pattern"
    );

    // Number event should only match numeric pattern
    assert_matches!(
        q,
        r#"{"key": 123}"#,
        vec!["num"],
        "Number 123 should match only numeric pattern"
    );
}

#[test]
fn test_mixed_number_and_string_in_same_value_array() {
    // Go's TestBasicMatching: a single pattern field with both numbers and strings
    // e.g. {"b": [1, "3"]} should match number 1 OR string "3" but NOT number 3
    let q = q!("p1" => r#"{"a": [1, 2], "b": [1, "3"]}"#);

    // String "3" on field b should match
    assert_matches!(
        q,
        r#"{"a": 1, "b": "3"}"#,
        vec!["p1"],
        "String '3' should match the string literal in [1, \"3\"]"
    );

    // Number 1 on field b should match
    assert_matches!(
        q,
        r#"{"a": 2, "b": 1}"#,
        vec!["p1"],
        "Number 1 should match the numeric literal in [1, \"3\"]"
    );

    // Number 3 on field b should NOT match (it's string "3" in the pattern, not number 3)
    assert_no_match!(
        q,
        r#"{"a": 1, "b": 3}"#,
        "Number 3 should NOT match string '3' in [1, \"3\"]"
    );

    // Reversed field order in the event should still work
    assert_matches!(
        q,
        r#"{"b": "3", "a": 1}"#,
        vec!["p1"],
        "Reversed field order should still match"
    );

    // Extra fields in the event should not interfere
    assert_matches!(
        q,
        r#"{"a": 2, "b": "3", "x": 99}"#,
        vec!["p1"],
        "Extra fields should not prevent match"
    );

    // Missing field b should not match
    assert_no_match!(q, r#"{"a": 1}"#, "Missing field b should not match");

    // Missing field a should not match
    assert_no_match!(q, r#"{"b": "3"}"#, "Missing field a should not match");

    // Wrong value on field a should not match
    assert_no_match!(
        q,
        r#"{"b": "3", "a": 6}"#,
        "Wrong value on field a should not match"
    );
}

#[test]
fn test_empty_matcher_returns_no_matches() {
    // A brand-new Quamina with no patterns should return empty matches for any event
    let q = Quamina::<&str>::new();

    assert_no_match!(
        q,
        r#"{"status": "active"}"#,
        "Empty matcher should return no matches"
    );
    assert_no_match!(
        q,
        r#"{"a": 1, "b": "hello"}"#,
        "Empty matcher should return no matches for any event"
    );
}

#[test]
fn test_idempotent_add_and_delete() {
    // Adding the same pattern ID with the same pattern twice, and deleting twice
    let mut q = Quamina::new();

    // Add same ID + same pattern twice
    q.add_pattern("p1", r#"{"x": ["a"]}"#).unwrap();
    q.add_pattern("p1", r#"{"x": ["a"]}"#).unwrap();

    // Should still match (and only return "p1" once, not duplicated)
    assert_matches!(
        q,
        r#"{"x": "a"}"#,
        vec!["p1"],
        "Duplicate add should still match"
    );

    // Delete once
    q.delete_patterns(&"p1").unwrap();
    assert_no_match!(q, r#"{"x": "a"}"#, "After delete, should not match");

    // Delete again (idempotent) -- should not panic
    q.delete_patterns(&"p1").unwrap();
    assert_no_match!(q, r#"{"x": "a"}"#, "Second delete should be idempotent");

    // Rebuild after double delete should not panic
    let purged = q.rebuild();
    // Both adds registered under "p1", so rebuild purges them
    assert!(purged >= 1, "Rebuild should purge the deleted pattern(s)");
}

#[test]
fn test_delete_multi_pattern_id_removes_all() {
    // Add multiple different patterns under the same ID, then delete that ID
    let mut q = Quamina::new();
    q.add_pattern("shared", r#"{"x": ["a"]}"#).unwrap();
    q.add_pattern("shared", r#"{"x": [1]}"#).unwrap();
    q.add_pattern("shared", r#"{"y": [{"prefix": "b"}]}"#)
        .unwrap();

    // All three patterns should match under "shared"
    assert_matches!(
        q,
        r#"{"x": "a"}"#,
        vec!["shared"],
        "String pattern should match"
    );
    assert_matches!(
        q,
        r#"{"x": 1}"#,
        vec!["shared"],
        "Numeric pattern should match"
    );
    assert_matches!(
        q,
        r#"{"y": "bcd"}"#,
        vec!["shared"],
        "Prefix pattern should match"
    );

    // Delete "shared" -- should remove ALL three patterns
    q.delete_patterns(&"shared").unwrap();

    assert_no_match!(
        q,
        r#"{"x": "a"}"#,
        "String pattern should be gone after delete"
    );
    assert_no_match!(
        q,
        r#"{"x": 1}"#,
        "Numeric pattern should be gone after delete"
    );
    assert_no_match!(
        q,
        r#"{"y": "bcd"}"#,
        "Prefix pattern should be gone after delete"
    );

    // Rebuild should purge the one deleted ID
    let purged = q.rebuild();
    assert_eq!(purged, 1, "Rebuild should purge 1 deleted ID");

    // After rebuild, still no matches (patterns are permanently gone)
    assert_no_match!(
        q,
        r#"{"x": "a"}"#,
        "String pattern should stay gone after rebuild"
    );
    assert_no_match!(
        q,
        r#"{"x": 1}"#,
        "Numeric pattern should stay gone after rebuild"
    );
    assert_no_match!(
        q,
        r#"{"y": "bcd"}"#,
        "Prefix pattern should stay gone after rebuild"
    );
}

// ============================================================================
// Pattern Complexity Limit Tests
// ============================================================================

// --- Depth Limit Tests ---

#[test]
fn test_pattern_depth_at_limit() {
    // Pattern nested exactly 256 levels deep should succeed with default limits
    let mut q = Quamina::new();
    let mut pattern = String::new();
    let mut closing = String::new();
    for i in 0..256 {
        pattern.push_str(&format!("{{\"f{}\": ", i));
        closing.push('}');
    }
    pattern.push_str("[\"val\"]");
    pattern.push_str(&closing);

    assert!(
        q.add_pattern("deep", &pattern).is_ok(),
        "Pattern at exactly max depth (256) should succeed"
    );
}

#[test]
fn test_pattern_depth_exceeds_limit() {
    // Pattern nested 257 levels should fail
    let mut q = Quamina::new();
    let mut pattern = String::new();
    let mut closing = String::new();
    for i in 0..257 {
        pattern.push_str(&format!("{{\"f{}\": ", i));
        closing.push('}');
    }
    pattern.push_str("[\"val\"]");
    pattern.push_str(&closing);

    let result = q.add_pattern("deep", &pattern);
    assert!(result.is_err(), "Pattern exceeding max depth should fail");
    let err_msg = format!("{}", result.unwrap_err());
    assert!(
        err_msg.contains("depth"),
        "Error should mention depth: {}",
        err_msg
    );
    assert!(
        err_msg.contains("257"),
        "Error should mention actual depth 257: {}",
        err_msg
    );
    assert!(
        err_msg.contains("256"),
        "Error should mention max depth 256: {}",
        err_msg
    );
}

#[test]
fn test_pattern_depth_custom_limit() {
    // Builder with max_depth=5, pattern at depth 6 should fail
    let mut q = QuaminaBuilder::<&str>::new()
        .with_max_pattern_depth(5)
        .build()
        .unwrap();

    let pattern = r#"{"a": {"b": {"c": {"d": {"e": {"f": ["val"]}}}}}}"#;
    let result = q.add_pattern("deep", pattern);
    assert!(
        result.is_err(),
        "Pattern at depth 6 should fail with max_depth=5"
    );
    let err_msg = format!("{}", result.unwrap_err());
    assert!(err_msg.contains("depth"), "Error should mention depth");
}

#[test]
fn test_pattern_depth_shallow_ok() {
    // Normal 3-level nesting with defaults should succeed
    let mut q = Quamina::new();
    let result = q.add_pattern("p1", r#"{"a": {"b": {"c": ["value"]}}}"#);
    assert!(
        result.is_ok(),
        "Normal 3-level nesting should succeed with defaults"
    );
}

// --- Field Count Limit Tests ---

#[test]
fn test_pattern_fields_at_limit() {
    // Pattern with exactly 256 fields should succeed
    let mut q = Quamina::new();
    let mut fields: Vec<String> = Vec::new();
    for i in 0..256 {
        fields.push(format!("\"f{}\": [\"v\"]", i));
    }
    let pattern = format!("{{{}}}", fields.join(", "));
    assert!(
        q.add_pattern("wide", &pattern).is_ok(),
        "Pattern with exactly 256 fields should succeed"
    );
}

#[test]
fn test_pattern_fields_exceeds_limit() {
    // Pattern with 257 fields should fail
    let mut q = Quamina::new();
    let mut fields: Vec<String> = Vec::new();
    for i in 0..257 {
        fields.push(format!("\"f{}\": [\"v\"]", i));
    }
    let pattern = format!("{{{}}}", fields.join(", "));

    let result = q.add_pattern("wide", &pattern);
    assert!(
        result.is_err(),
        "Pattern with 257 fields should exceed limit"
    );
    let err_msg = format!("{}", result.unwrap_err());
    assert!(
        err_msg.contains("257"),
        "Error should mention actual count 257: {}",
        err_msg
    );
    assert!(
        err_msg.contains("256"),
        "Error should mention max count 256: {}",
        err_msg
    );
}

#[test]
fn test_pattern_fields_custom_limit() {
    // Builder with max_fields=3, pattern with 4 fields should fail
    let mut q = QuaminaBuilder::<&str>::new()
        .with_max_fields_per_pattern(3)
        .build()
        .unwrap();

    let pattern = r#"{"a": ["1"], "b": ["2"], "c": ["3"], "d": ["4"]}"#;
    let result = q.add_pattern("wide", pattern);
    assert!(
        result.is_err(),
        "Pattern with 4 fields should fail with max_fields=3"
    );
    let err_msg = format!("{}", result.unwrap_err());
    assert!(
        err_msg.contains("fields"),
        "Error should mention fields: {}",
        err_msg
    );
}

// --- Arena Byte Budget Tests ---

#[test]
fn test_arena_budget_exceeded() {
    // Builder with tiny budget (1KB), pattern triggering arena construction should fail
    let mut q = QuaminaBuilder::<&str>::new()
        .with_arena_byte_budget(1024)
        .build()
        .unwrap();

    // Add many patterns to trigger arena growth beyond 1KB
    // First pattern may succeed (singleton optimization), but subsequent ones will build arena
    let _ = q.add_pattern("p1", r#"{"x": ["a"]}"#);
    let _ = q.add_pattern("p2", r#"{"x": ["b"]}"#);

    // Add enough patterns to exceed the tiny budget
    let mut exceeded = false;
    for i in 0..100 {
        let pattern = format!("{{\"x\": [\"value_that_is_long_enough_{}\"]}}", i);
        if q.add_pattern("px", &pattern).is_err() {
            exceeded = true;
            break;
        }
    }
    assert!(exceeded, "Arena budget should be exceeded with 1KB limit");
}

#[test]
fn test_arena_budget_sufficient() {
    // Default budget (10MB), normal patterns should work fine
    let mut q = Quamina::new();
    for i in 0..50 {
        let pattern = format!("{{\"field{}\": [\"value{}\"]}}", i, i);
        assert!(
            q.add_pattern("p1", &pattern).is_ok(),
            "Normal patterns should work within default 10MB budget"
        );
    }
}

#[test]
fn test_arena_budget_custom() {
    // Builder with 1MB budget, patterns work within it
    let mut q = QuaminaBuilder::<&str>::new()
        .with_arena_byte_budget(1024 * 1024)
        .build()
        .unwrap();

    for i in 0..20 {
        let pattern = format!("{{\"field{}\": [\"value{}\"]}}", i, i);
        assert!(
            q.add_pattern("p1", &pattern).is_ok(),
            "Moderate patterns should work within 1MB budget"
        );
    }
}

// --- Error Message Quality Tests ---

#[test]
fn test_depth_error_includes_path() {
    // The error should contain the field path where depth was exceeded
    let mut q = QuaminaBuilder::<&str>::new()
        .with_max_pattern_depth(2)
        .build()
        .unwrap();

    let pattern = r#"{"a": {"b": {"c": ["val"]}}}"#;
    let result = q.add_pattern("deep", pattern);
    assert!(result.is_err());
    let err_msg = format!("{}", result.unwrap_err());
    assert!(
        err_msg.contains("pattern too complex"),
        "Error should start with 'pattern too complex': {}",
        err_msg
    );
}

#[test]
fn test_field_count_error_includes_count() {
    let mut q = QuaminaBuilder::<&str>::new()
        .with_max_fields_per_pattern(2)
        .build()
        .unwrap();

    let pattern = r#"{"a": ["1"], "b": ["2"], "c": ["3"]}"#;
    let result = q.add_pattern("wide", pattern);
    assert!(result.is_err());
    let err_msg = format!("{}", result.unwrap_err());
    assert!(
        err_msg.contains("3"),
        "Error should contain actual field count: {}",
        err_msg
    );
    assert!(
        err_msg.contains("2"),
        "Error should contain max field count: {}",
        err_msg
    );
}

#[test]
fn test_arena_error_includes_bytes() {
    let mut q = QuaminaBuilder::<&str>::new()
        .with_arena_byte_budget(1)
        .build()
        .unwrap();

    // This should fail because budget is 1 byte
    let _ = q.add_pattern("p1", r#"{"x": ["a"]}"#);
    let result = q.add_pattern("p2", r#"{"x": ["b"]}"#);
    if let Err(e) = result {
        let err_msg = format!("{}", e);
        assert!(
            err_msg.contains("bytes") && err_msg.contains("budget"),
            "Error should mention bytes and budget: {}",
            err_msg
        );
    }
    // With a 1-byte budget, at least one of the two patterns should fail
}

// --- Integration Tests ---

#[test]
fn test_default_limits_allow_normal_patterns() {
    // All operator types should work under default limits
    let mut q = Quamina::new();

    assert!(q.add_pattern("exact", r#"{"x": ["hello"]}"#).is_ok());
    assert!(q.add_pattern("num", r#"{"x": [42]}"#).is_ok());
    assert!(q
        .add_pattern("prefix", r#"{"x": [{"prefix": "he"}]}"#)
        .is_ok());
    assert!(q
        .add_pattern("suffix", r#"{"x": [{"suffix": "lo"}]}"#)
        .is_ok());
    assert!(q
        .add_pattern("shell", r#"{"x": [{"shellstyle": "h*o"}]}"#)
        .is_ok());
    assert!(q
        .add_pattern("wild", r#"{"x": [{"wildcard": "h*o"}]}"#)
        .is_ok());
    assert!(q
        .add_pattern("ab", r#"{"x": [{"anything-but": ["no"]}]}"#)
        .is_ok());
    assert!(q
        .add_pattern("eic", r#"{"x": [{"equals-ignore-case": "HELLO"}]}"#)
        .is_ok());
    assert!(q
        .add_pattern("re", r#"{"x": [{"regex": "[a-z]+"}]}"#)
        .is_ok());
    assert!(q
        .add_pattern("numr", r#"{"x": [{"numeric": [">=", 1, "<", 100]}]}"#)
        .is_ok());
    assert!(q
        .add_pattern("cidr", r#"{"x": [{"cidr": "10.0.0.0/8"}]}"#)
        .is_ok());
    assert!(q
        .add_pattern("exists", r#"{"x": [{"exists": true}]}"#)
        .is_ok());
}

/// Patterns with many distinct values on the same field must be rejected
/// once the arena byte budget is exhausted. This is a regression test for C3
/// (add_string_transition previously skipped the budget check entirely).
#[test]
fn test_arena_budget_enforced_on_repeated_exact_strings() {
    let mut q = QuaminaBuilder::<&str>::new()
        .with_arena_byte_budget(4096)
        .build()
        .unwrap();

    let mut rejected = false;
    for i in 0..500 {
        let pattern = format!(r#"{{"x": ["long_value_string_number_{}"]}}"#, i);
        if q.add_pattern("p", &pattern).is_err() {
            rejected = true;
            break;
        }
    }
    assert!(
        rejected,
        "Budget should be enforced when many exact strings are added to the same field"
    );
}

/// After a rejected add_pattern, existing patterns must still match correctly.
/// This is a regression test for C1 (rejected patterns must not corrupt state)
/// and for M4 (partial transitions must not produce false positives).
#[test]
fn test_matcher_correct_after_rejected_pattern() {
    let mut q = QuaminaBuilder::<&str>::new()
        .with_arena_byte_budget(4096)
        .build()
        .unwrap();

    // Add a pattern that succeeds
    q.add_pattern("good", r#"{"x": ["hello"]}"#).unwrap();

    // Keep adding until one is rejected
    let mut rejected = false;
    for i in 0..500 {
        let pattern = format!(r#"{{"x": ["overflow_value_{}"]}}"#, i);
        if q.add_pattern("bad", &pattern).is_err() {
            rejected = true;
            break;
        }
    }
    assert!(rejected, "Should have hit budget limit");

    // The original "good" pattern must still match
    assert_has_match!(q, r#"{"x": "hello"}"#, "good");

    // A non-matching event must still return empty
    assert_no_match!(
        q,
        r#"{"x": "nope"}"#,
        "Non-matching event must not produce false positives"
    );
}

/// Clone must preserve the configured arena budget.
/// This is a regression test for C2 (clone previously used usize::MAX).
#[test]
fn test_clone_preserves_arena_budget() {
    let mut q = QuaminaBuilder::<String>::new()
        .with_arena_byte_budget(4096)
        .build()
        .unwrap();

    q.add_pattern("a".into(), r#"{"x": ["val"]}"#).unwrap();
    let mut cloned = q.clone();

    // The clone should enforce the same budget
    let mut rejected = false;
    for i in 0..500 {
        let pattern = format!(r#"{{"x": ["clone_test_value_{}"]}}"#, i);
        if cloned.add_pattern("b".into(), &pattern).is_err() {
            rejected = true;
            break;
        }
    }
    assert!(
        rejected,
        "Cloned instance must enforce the original arena budget"
    );
}

/// Errors must return the PatternTooComplex variant specifically.
#[test]
fn test_errors_return_pattern_too_complex_variant() {
    let mut q = QuaminaBuilder::<&str>::new()
        .with_max_pattern_depth(1)
        .build()
        .unwrap();

    let result = q.add_pattern("deep", r#"{"a": {"b": ["val"]}}"#);
    assert!(
        matches!(result, Err(QuaminaError::PatternTooComplex(_))),
        "Depth violation must return PatternTooComplex, got {:?}",
        result
    );

    let mut q2 = QuaminaBuilder::<&str>::new()
        .with_max_fields_per_pattern(1)
        .build()
        .unwrap();
    let result = q2.add_pattern("wide", r#"{"a": ["1"], "b": ["2"]}"#);
    assert!(
        matches!(result, Err(QuaminaError::PatternTooComplex(_))),
        "Field count violation must return PatternTooComplex, got {:?}",
        result
    );
}

/// Zero limits must panic at build time, not silently reject all patterns.
#[test]
#[should_panic(expected = "max_pattern_depth must be at least 1")]
fn test_zero_depth_panics() {
    QuaminaBuilder::<&str>::new().with_max_pattern_depth(0);
}

#[test]
#[should_panic(expected = "max_fields_per_pattern must be at least 1")]
fn test_zero_fields_panics() {
    QuaminaBuilder::<&str>::new().with_max_fields_per_pattern(0);
}

#[test]
#[should_panic(expected = "arena_byte_budget must be at least 1")]
fn test_zero_budget_panics() {
    QuaminaBuilder::<&str>::new().with_arena_byte_budget(0);
}

#[test]
#[should_panic(expected = "max_states_per_pattern must be at least 1")]
fn test_zero_states_panics() {
    QuaminaBuilder::<&str>::new().with_max_states_per_pattern(0);
}

// --- State Count Limit Tests ---

#[test]
fn test_state_limit_exceeded() {
    // With a tiny state limit of 2, a pattern with 2 mixed-type fields
    // each having 2 matchers would produce 4 states (2^2), exceeding the limit.
    let mut q = QuaminaBuilder::<&str>::new()
        .with_max_states_per_pattern(2)
        .build()
        .unwrap();

    // Single field with mixed matchers: exact + prefix → 2 states (within limit)
    let r1 = q.add_pattern("ok", r#"{"a": ["x", {"prefix": "y"}]}"#);
    assert!(r1.is_ok(), "2 states should be within limit of 2");

    // Two fields with mixed matchers: 2 * 2 = 4 states (exceeds limit)
    let r2 = q.add_pattern(
        "bad",
        r#"{"a": ["x", {"prefix": "y"}], "b": ["m", {"prefix": "n"}]}"#,
    );
    assert!(r2.is_err(), "4 states should exceed limit of 2");
    assert!(
        r2.unwrap_err()
            .to_string()
            .contains("field-matcher state count"),
        "error should mention state count"
    );
}

#[test]
fn test_state_limit_default_allows_normal_patterns() {
    // Default limit (1024) should easily handle normal mixed-type patterns
    let mut q = Quamina::new();

    // Mixed exact + prefix on one field
    assert!(q
        .add_pattern("p1", r#"{"status": ["active", {"prefix": "pend"}]}"#)
        .is_ok());

    // Multiple fields with single matchers (no multiplication)
    assert!(q
        .add_pattern("p2", r#"{"a": ["1"], "b": ["2"], "c": ["3"]}"#)
        .is_ok());

    // Verify matching still works
    let matches = q
        .matches_for_event(r#"{"status": "active"}"#.as_bytes())
        .unwrap();
    assert!(matches.contains(&&"p1"));
    let matches = q
        .matches_for_event(r#"{"status": "pending"}"#.as_bytes())
        .unwrap();
    assert!(matches.contains(&&"p1"));
}