eggsact 1.2.7

Deterministic MCP and in-process utility tools for coding agents
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
use fancy_regex::{Captures, Regex};
use std::collections::HashMap;
use std::sync::LazyLock;

/// Map a `fancy_regex::Error` to a deterministic, bounded normalization error
/// message. The stage name is a compile-time constant so the message is stable
/// and does not include raw user input.
fn normalization_regex_error(stage: &'static str, err: fancy_regex::Error) -> String {
    format!("calculator normalization regex stage '{stage}' failed: {err}")
}

/// Fallible all-matches replacement for user-driven calculator text.
///
/// In `fancy-regex 0.18`, `Regex::replace_all` delegates to infallible
/// replacement that panics on runtime errors (e.g. `BacktrackLimitExceeded`).
/// `try_replacen(text, 0, replacement)` performs replace-all behaviour while
/// returning runtime errors as `Result::Err`, which we propagate as a
/// deterministic `String` error.
fn try_replace_all<R>(
    stage: &'static str,
    re: &Regex,
    text: &str,
    replacement: R,
) -> Result<String, String>
where
    R: fancy_regex::Replacer,
{
    re.try_replacen(text, 0, replacement)
        .map(|value| value.into_owned())
        .map_err(|err| normalization_regex_error(stage, err))
}

static PCT_SYMBOL_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\d+(?:\.\d+)?)\s*%(?!\s*\d)").unwrap());
static PERCENT_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\d+(?:\.\d+)?)\s*percent\b").unwrap());
static COMPLEX_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\d+(?:\.\d+)?)\s*([+-])\s*(\d+(?:\.\d+)?)\s*i").unwrap());

// --- Cached alternation strings ---

static UNIT_ALT: LazyLock<String> = LazyLock::new(|| {
    // BUG-009 / parity B9: sort by length descending so compound units like
    // "km/h", "mi/h", "m/s" are tried before single-character units (m, h,
    // s) that would otherwise swallow the prefix.
    let mut keys: Vec<&str> = crate::calc::units::UNIT_ALIASES.keys().copied().collect();
    keys.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b)));
    keys.iter()
        .map(|u| regex_escape(u))
        .collect::<Vec<_>>()
        .join("|")
});

static NUMBER_WORD_ALT: LazyLock<String> = LazyLock::new(|| {
    NUMBER_WORDS
        .keys()
        .map(|w| regex_escape(w))
        .collect::<Vec<_>>()
        .join("|")
});

static TEMP_UNITS_LIST: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
    vec![
        "f",
        "c",
        "k",
        "fahrenheit",
        "celsius",
        "kelvin",
        "rankine",
        "degf",
        "degc",
        "degk",
        "degr",
        "ra",
    ]
});

// --- Static regex patterns (no dynamic data) ---

static TEMP_CONVERSION_RE: LazyLock<Regex> = LazyLock::new(|| {
    let temp_unit = r"(?:[cfk]|celsius|fahrenheit|kelvin|rankine|degc|degf|degk|degr|ra)";
    // NOTE (BUG-007 / parity B7): \s* instead of \s+ so that compact forms
    // like "100c in f" trigger the canonicalization pass.
    Regex::new(&format!(
        r"(?i)(\d+(?:\.\d+)?)\s*({temp_unit})\s+(in|to|as|into)\s+({temp_unit})\b"
    ))
    .unwrap()
});

static BINARY_WORD_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)(\d+(?:\.\d+)?|\((?:[^()]|\([^()]*\))*\))\s+(not|in|to|as|into)\s+(\d+(?:\.\d+)?)\b",
    )
    .unwrap()
});

static BINARY_WORD_INNER_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?i)\b(not|in|to|as|into)\b").unwrap());

static TO_THE_POWER_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\d+(?:\.\d+)?)\s+to\s+the\s+(\d+(?:\.\d+)?)").unwrap());

static DEGREES_NON_TEMP_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\d+(?:\.\d+)?)\s*(?:degrees?|deg)\s+(\w+)").unwrap());

static DEGREES_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\d+(?:\.\d+)?)\s*(?:degrees?|deg)\b").unwrap());

static POINT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?<=[\d)])\s*point\s*").unwrap());

static MERGE_DECIMAL_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\d+\.\d*)\s+(\d)").unwrap());

static IMPLICIT_MUL_FUNC_RE: LazyLock<Regex> = LazyLock::new(|| {
    let funcs = [
        "sqrt",
        "sin",
        "cos",
        "tan",
        "asin",
        "acos",
        "atan",
        "sinh",
        "cosh",
        "tanh",
        "log",
        "log10",
        "log2",
        "exp",
        "abs",
        "factorial",
        "cbrt",
        "floor",
        "ceil",
        "round",
        "sign",
        "mean",
        "median",
        "mode",
        "std",
        "variance",
        "gcd",
        "lcm",
        "perm",
        "comb",
        "isprime",
        "nextprime",
        "prevprime",
        "primefactors",
        "random",
        "randint",
        "gauss",
        "sum",
        "max",
        "min",
        "hypot",
        "clamp",
        "asinh",
        "acosh",
        "atanh",
    ];
    Regex::new(&format!(r"(\d|\))\s*({})\b", funcs.join("|"))).unwrap()
});

static IMPLICIT_MUL_PAREN_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\))\s*(\d|\()").unwrap());

static IMPLICIT_MUL_DIGIT_PAREN_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(\d)\s*\(").unwrap());

static FACTORIAL_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(\d+(?:\.\d+)?|\((?:[^()]*|\([^()]*\))*\)|[a-zA-Z_]\w*\((?:[^()]*|\([^()]*\))*\))(\!+)",
    )
    .unwrap()
});

static SPLIT_NUM_MINUS_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\d+(?:-\d+)+$").unwrap());

static SPLIT_DOUBLE_MINUS_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\d+--\d+").unwrap());

static SPLIT_TRAILING_MINUS_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\d+-$").unwrap());

static UNIT_INLINE_RE: LazyLock<Regex> = LazyLock::new(|| {
    // B-M1: Restrict to word-boundary so that `2*3*s` is not overmatched as
    // a unit unless `s` is a known alias (post-filtered via
    // `resolve_unit_alias`). The original `[a-zA-Z°]+(?:/[a-zA-Z°]+)?` is
    // retained but anchored with `\b` to prevent prefix capture. A future
    // fix could restrict to `UNIT_ALT` directly; the current post-filter
    // already ensures only known aliases or `a/b` rates are treated as units.
    Regex::new(r"(?P<num>\d+(?:\.\d+)?)\*?(?P<unit>[a-zA-Z°]+(?:/[a-zA-Z°]+)?)\b").unwrap()
});

static SAME_UNIT_DIV_RE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\b([a-zA-Z]+)/(\d+(?:\.\d+)?)\*([a-zA-Z]+)\b").unwrap());

static CONVERT_SIMPLE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^convert\((\d+(?:\.\d+)?)\*([a-zA-Z°][a-zA-Z0-9°/]*),([a-zA-Z°][a-zA-Z0-9°/]*)\)$")
        .unwrap()
});

static CONVERT_BARE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^convert\((\d+(?:\.\d+)?),([a-zA-Z°][a-zA-Z0-9°/]*)\)$").unwrap()
});

static TEMP_HANDLE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^temp\(([^,]+),([a-zA-Z°][a-zA-Z0-9°]*),([a-zA-Z°][a-zA-Z0-9°]*)\)$").unwrap()
});

// --- Dynamic regex patterns (depend on LazyLock data) ---

static HYPHEN_RE: LazyLock<Regex> = LazyLock::new(|| {
    let nwa = &*NUMBER_WORD_ALT;
    Regex::new(&format!(r"\b({})-({})\b", nwa, nwa)).unwrap()
});

static NUMBER_WORD_RE: LazyLock<Regex> = LazyLock::new(|| {
    let nwa = &*NUMBER_WORD_ALT;
    Regex::new(&format!("\\b({})\\b", nwa)).unwrap()
});

fn unit_caret_attach_re() -> &'static Regex {
    static RE: LazyLock<Regex> = LazyLock::new(|| {
        let ua = &*UNIT_ALT;
        Regex::new(&format!(r"(?i)(\d+(?:\.\d+)?)\s+({ua})\s*\^\s*([23])\b")).unwrap()
    });
    &RE
}

fn unit_caret_denom_re() -> &'static Regex {
    static RE: LazyLock<Regex> = LazyLock::new(|| {
        let ua = &*UNIT_ALT;
        Regex::new(&format!(r"(?i)/\s*({ua})\s*\^\s*(\d+)\b")).unwrap()
    });
    &RE
}

fn unit_caret_paren_re() -> &'static Regex {
    static RE: LazyLock<Regex> = LazyLock::new(|| {
        let ua = &*UNIT_ALT;
        Regex::new(&format!(r"(?i)/\(\s*({ua})\s*\)\s*\^\s*(\d+)\b")).unwrap()
    });
    &RE
}

static UNIT_POWER_RE: LazyLock<Regex> = LazyLock::new(|| {
    let ua = &*UNIT_ALT;
    Regex::new(&format!(r"(?i)\b({ua})\s+(squared|cubed)\b")).unwrap()
});

static UNIT_SPELLED_RE: LazyLock<Regex> = LazyLock::new(|| {
    let ua = &*UNIT_ALT;
    // (BUG-009 / parity B9) Accept optional "*" between number and unit
    // so that the form inserted by BARE_SIMPLE_UNIT_RE / BARE_COMPOUND_UNIT_RE
    // also matches here.
    Regex::new(&format!(
        r"(?i)(\d+(?:\.\d+)?)\s*\*?\s*({ua})\s+(?:in|to)\s+({ua})\b"
    ))
    .unwrap()
});

static UNIT_COMPOUND_RE: LazyLock<Regex> = LazyLock::new(|| {
    let ua = &*UNIT_ALT;
    Regex::new(&format!(
        r"(?i)(\d+(?:\.\d+)?)\s*\*?\s*({ua})\s*/\s*({ua})\s+(?:in|to)\s*({ua})\s*/\s*({ua})\b"
    ))
    .unwrap()
});

// --- BUG-009 / parity B9: bare compound / spaced unit handling ---
//
// Compound units (km/h, mi/h, m/s, …) contain a "/" which the operator
// splitter would otherwise turn into division, splitting "60 km/h" into
// ["60", "km", "/", "h"]. Insert "*" before the compound unit so the
// whole token survives tokenization.
//
// Single-unit spaced forms ("60 mph") become ["60", "mph"] after operator
// splitting and "mph" then collides with the evaluator's identifier table.
// Inserting "*" produces "60*mph" which the unit preprocessor can convert
// to the target unit when mixed-unit arithmetic follows.
//
// Both patterns run BEFORE the operator splitter via the normalize() pass.

static BARE_COMPOUND_UNITS: &[&str] = &[
    "km/h",
    "mi/h",
    "m/s",
    "km/s",
    "mi/s",
    "bit/s",
    "bits/s",
    "kilobit/s",
    "kilobits/s",
    "megabit/s",
    "megabits/s",
    "gigabit/s",
    "gigabits/s",
];

static BARE_COMPOUND_UNIT_RE: LazyLock<Regex> = LazyLock::new(|| {
    let alt = BARE_COMPOUND_UNITS
        .iter()
        .map(|u| regex_escape(u))
        .collect::<Vec<_>>()
        .join("|");
    Regex::new(&format!(r"(?i)(\d+(?:\.\d+)?)(\s*)({alt})\b")).unwrap()
});

static SPLIT_UNIT_DIV_RE: LazyLock<Regex> = LazyLock::new(|| {
    // "<num> <u1> / <u2>" forms where u1/u2 are canonical rate units
    // (e.g. "60 km / h" -> "(60*km)/h" so the right-hand unit isn't
    // consumed as the Planck constant `h`).
    let pairs = [
        ("km", "h"),
        ("km", "hr"),
        ("km", "hour"),
        ("km", "hours"),
        ("mi", "h"),
        ("mi", "hr"),
        ("mi", "hour"),
        ("mi", "hours"),
        ("m", "s"),
        ("m", "sec"),
        ("m", "second"),
        ("m", "seconds"),
        ("km", "s"),
        ("km", "sec"),
        ("km", "second"),
        ("km", "seconds"),
        ("mi", "s"),
        ("mi", "sec"),
        ("mi", "second"),
        ("mi", "seconds"),
        ("km", "min"),
        ("km", "minute"),
        ("km", "minutes"),
        ("mi", "min"),
        ("mi", "minute"),
        ("mi", "minutes"),
    ];
    let alt = pairs
        .iter()
        .map(|(a, b)| format!(r"({})\s+/\s+({})", regex_escape(a), regex_escape(b)))
        .collect::<Vec<_>>()
        .join("|");
    Regex::new(&format!(r"(?i)(\d+(?:\.\d+)?)\s*(?:{})", alt)).unwrap()
});

static PER_UNIT_RE: LazyLock<Regex> = LazyLock::new(|| {
    // "<num> <distance> per <time>" forms (e.g. "60 kilometer per hour",
    // "60 miles per hour") -> "(60*km)/h" so the rate expression survives
    // tokenization.
    Regex::new(
        r"(?i)(\d+(?:\.\d+)?)\s*(kilometers?|kilometres?|miles?|meters?|metres?|feet|foot|inches?|inch|km|mi|yd|ft)\s+per\s+(hours?|hr|minutes?|min|seconds?|sec|h|s)\b",
    ).unwrap()
});

static BARE_SIMPLE_UNIT_RE: LazyLock<Regex> = LazyLock::new(|| {
    // BUG-009 / parity B9: Spaced `<num> <unit>` forms (e.g. "60 mph",
    // "100 m", "50 ft") become "<num>*<unit>" so the unit survives operator
    // splitting. The list deliberately skips ambiguous one-letter
    // identifiers in identifier-only contexts; single-letter units are
    // accepted because they're unambiguous when preceded by a number with
    // whitespace (Python parity).
    let units = [
        // Speed / velocity
        "mph",
        "kph",
        "knot",
        "knots",
        "ft/s",
        "ft/min",
        "ft/h",
        "yd/s",
        "yd/min",
        "yd/h",
        "mi/s",
        "mi/min",
        "mi/h",
        "km/s",
        "km/min",
        "km/h",
        "m/s",
        "m/min",
        "m/h",
        "mach",
        // Length
        "m",
        "cm",
        "mm",
        "km",
        "ft",
        "yd",
        "mi",
        "in",
        "inch",
        "inches",
        "foot",
        "feet",
        "mile",
        "miles",
        "meter",
        "meters",
        "metre",
        "metres",
        "yard",
        "yards",
        "rod",
        "fathom",
        // Mass
        "kg",
        "g",
        "mg",
        "lb",
        "lbs",
        "oz",
        "ton",
        "tonne",
        // Time
        "s",
        "sec",
        "secs",
        "second",
        "seconds",
        "min",
        "mins",
        "minute",
        "minutes",
        "h",
        "hr",
        "hrs",
        "hour",
        "hours",
        "day",
        "days",
        "week",
        "weeks",
        "year",
        "years",
        // Volume
        "l",
        "L",
        "ml",
        "liter",
        "liters",
        "litre",
        "litres",
        "gal",
        "qt",
        "pt",
        "cup",
        // Energy / power
        "j",
        "J",
        "kJ",
        "kj",
        "cal",
        "kcal",
        "wh",
        "kWh",
        "kwh",
        "w",
        "W",
        "kw",
        "KW",
        "hp",
        // Pressure
        "pa",
        "Pa",
        "kpa",
        "KPa",
        "kPa",
        "mpa",
        "MPa",
        "psi",
        "bar",
        "atm",
        "torr",
        "mmHg",
        // Temperature (long forms; short f/c/k handled elsewhere)
        "celsius",
        "fahrenheit",
        "kelvin",
        "rankine",
        "degc",
        "degf",
        "degk",
        "degr",
        // Data
        "bit",
        "bits",
        "byte",
        "bytes",
        "kb",
        "mb",
        "gb",
        "tb",
    ];
    let alt = {
        // Sort by length descending so longer units (e.g., "miles") are
        // tried before shorter prefixes ("mile", "mi", "m"). Without this,
        // the regex engine would greedily match "m" inside "miles" and
        // misread expressions like "10 miles" as "10*m ...".
        let mut sorted = units.to_vec();
        sorted.sort_by(|a, b| b.len().cmp(&a.len()).then_with(|| a.cmp(b)));
        sorted
            .iter()
            .map(|u| regex_escape(u))
            .collect::<Vec<_>>()
            .join("|")
    };
    Regex::new(&format!(r"(?i)(\d+(?:\.\d+)?)(\s+)({})\b", alt)).unwrap()
});

// --- Loop patterns (cached per-entry) ---

static TEMP_DEG_CONV_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    TEMP_UNITS_LIST
        .iter()
        .map(|tu| {
            Regex::new(&format!(
                r"(?i)(\d+(?:\.\d+)?)\s*(?:degrees?|deg)\s+(?:in|to|as|into)\s+{}\b",
                regex_escape(tu)
            ))
            .unwrap()
        })
        .collect()
});

static TEMP_DEG_UNIT_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    TEMP_UNITS_LIST
        .iter()
        .map(|tu| {
            Regex::new(&format!(
                r"(?i)(\d+(?:\.\d+)?)\s*(?:degrees?|deg)\s+{}\b",
                regex_escape(tu)
            ))
            .unwrap()
        })
        .collect()
});

static DIGIT_SCALE_PATTERNS: LazyLock<Vec<(Regex, f64)>> = LazyLock::new(|| {
    let scales: &[(&str, &str)] = &[
        ("hundred", "100"),
        ("thousand", "1000"),
        ("million", "1000000"),
        ("billion", "1000000000"),
        ("trillion", "1000000000000"),
        ("quadrillion", "1000000000000000"),
        ("quintillion", "1000000000000000000"),
    ];
    scales
        .iter()
        .map(|(word, val)| {
            let re = Regex::new(&format!(r"\b(\d+(?:\.\d+)?)\s*{}\b", regex_escape(word))).unwrap();
            (re, val.parse::<f64>().unwrap())
        })
        .collect()
});

static CONSTANT_PATTERNS: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {
    let mut entries: Vec<_> = CONSTANT_WORDS.iter().collect::<Vec<_>>();
    entries.sort_by_key(|(phrase, _)| std::cmp::Reverse(phrase.len()));
    entries
        .iter()
        .map(|(phrase, canonical)| {
            (
                Regex::new(&word_boundary_regex(phrase)).unwrap(),
                **canonical,
            )
        })
        .collect()
});

static MULTI_WORD_PATTERNS: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {
    MULTI_WORD_NUMBERS
        .iter()
        .map(|(phrase, replacement)| {
            (
                Regex::new(&word_boundary_regex(phrase)).unwrap(),
                *replacement,
            )
        })
        .collect()
});

static STRIPPED_LONG_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    STRIPPED_PHRASES
        .iter()
        .filter(|p| p.len() > 10)
        .map(|p| Regex::new(&word_boundary_regex(p)).unwrap())
        .collect()
});

static STRIPPED_SHORT_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
    STRIPPED_PHRASES
        .iter()
        .filter(|p| p.len() <= 10)
        .map(|p| Regex::new(&word_boundary_regex(p)).unwrap())
        .collect()
});

static OPERATOR_PATTERNS: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {
    let mut entries: Vec<_> = OPERATOR_CONVERSIONS.iter().collect::<Vec<_>>();
    entries.sort_by_key(|(word, _)| std::cmp::Reverse(word.len()));
    entries
        .iter()
        .map(|(word, symbol)| (Regex::new(&word_boundary_regex(word)).unwrap(), **symbol))
        .collect()
});

static FUNC_NAME_PATTERNS: LazyLock<Vec<(Regex, &'static str)>> = LazyLock::new(|| {
    let mut entries: Vec<_> = FUNCTION_MAPPINGS.iter().collect::<Vec<_>>();
    entries.sort_by_key(|(name, _)| std::cmp::Reverse(name.len()));
    entries
        .iter()
        .map(|(name, standard)| (Regex::new(&word_boundary_regex(name)).unwrap(), **standard))
        .collect()
});

static COMPACT_FUNC_RE: LazyLock<Option<Regex>> = LazyLock::new(|| {
    let funcs: Vec<&str> = FUNCTION_MAPPINGS
        .values()
        .copied()
        .filter(|name| {
            !name.ends_with(|c: char| c.is_ascii_digit()) && *name != "log10" && *name != "log2"
        })
        .collect();
    if funcs.is_empty() {
        None
    } else {
        Some(
            Regex::new(&format!(
                r"(?<![A-Za-z_])({})\s*([+-]?\d+(?:\.\d+)?)",
                funcs
                    .iter()
                    .map(|f| regex_escape(f))
                    .collect::<Vec<_>>()
                    .join("|")
            ))
            .unwrap(),
        )
    }
});

static FUNC_FIX_PATTERNS: LazyLock<Vec<(Regex, bool, &'static str)>> = LazyLock::new(|| {
    let multi_arg_funcs: &[&str] = &[
        "mean", "median", "mode", "std", "variance", "var", "gcd", "lcm", "perm", "comb", "nPr",
        "nCr", "sum", "max", "min", "clamp", "gauss", "hypot", "randint",
    ];
    FUNCTION_MAPPINGS
        .values()
        .copied()
        .map(|func| {
            let escaped = regex_escape(func);
            let is_multi = multi_arg_funcs.contains(&func);
            let pattern = if is_multi {
                format!(r"\b{0}\s*\*\s*([^()]+)", escaped)
            } else {
                format!(r"\b{0}\s*\*\s*([^()+\-]*)", escaped)
            };
            let re = Regex::new(&pattern).unwrap_or_else(|e| {
                panic!(
                    "FUNC_FIX_PATTERNS: invalid regex for func '{func}': {e} (pattern: {pattern})"
                )
            });
            (re, is_multi, func)
        })
        .collect()
});

fn regex_escape(s: &str) -> String {
    let mut result = String::new();
    for c in s.chars() {
        match c {
            '\\' | '(' | ')' | '[' | ']' | '{' | '}' | '.' | '*' | '+' | '?' | '^' | '$' | '|' => {
                result.push('\\');
                result.push(c);
            }
            _ => result.push(c),
        }
    }
    result
}

const MAX_TEXT_LENGTH: usize = 100_000;

#[doc(hidden)]
pub static NUMBER_WORDS: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
    let mut m = HashMap::new();

    // Single digits
    m.insert("zero", "0");
    m.insert("one", "1");
    m.insert("two", "2");
    m.insert("three", "3");
    m.insert("four", "4");
    m.insert("five", "5");
    m.insert("six", "6");
    m.insert("seven", "7");
    m.insert("eight", "8");
    m.insert("nine", "9");

    // Teens
    m.insert("ten", "10");
    m.insert("eleven", "11");
    m.insert("twelve", "12");
    m.insert("thirteen", "13");
    m.insert("fourteen", "14");
    m.insert("fifteen", "15");
    m.insert("sixteen", "16");
    m.insert("seventeen", "17");
    m.insert("eighteen", "18");
    m.insert("nineteen", "19");

    // Tens
    m.insert("twenty", "20");
    m.insert("thirty", "30");
    m.insert("forty", "40");
    m.insert("fifty", "50");
    m.insert("sixty", "60");
    m.insert("seventy", "70");
    m.insert("eighty", "80");
    m.insert("ninety", "90");

    // Multipliers
    m.insert("hundred", "100");
    m.insert("thousand", "1000");
    m.insert("million", "1000000");
    m.insert("billion", "1000000000");
    m.insert("trillion", "1000000000000");
    m.insert("quadrillion", "1000000000000000");
    m.insert("quintillion", "1000000000000000000");

    // Fractions
    m.insert("half", "0.5");
    m.insert("quarter", "0.25");
    m.insert("thousandth", "0.001");
    m.insert("millionth", "0.000001");
    m.insert("billionth", "0.000000001");

    m
});

/// Multi-word fraction numbers (e.g., "one half" → "0.5").
/// Applied before individual number word replacement.
#[doc(hidden)]
pub static MULTI_WORD_NUMBERS: LazyLock<Vec<(&'static str, &'static str)>> = LazyLock::new(|| {
    vec![
        ("one half", "0.5"),
        ("one quarter", "0.25"),
        ("one third", "0.3333333333333333"),
        ("two thirds", "0.6666666666666666"),
        ("three quarters", "0.75"),
    ]
});

#[doc(hidden)]
pub static OPERATOR_CONVERSIONS: LazyLock<HashMap<&'static str, &'static str>> =
    LazyLock::new(|| {
        let mut m = HashMap::new();
        m.insert("plus", "+");
        m.insert("positive", "+");
        m.insert("minus", "-");
        m.insert("negative", "-");
        m.insert("times", "*");
        m.insert("multiplied by", "*");
        m.insert("divided by", "/");
        m.insert("over", "/");
        m.insert("per", "/");
        m.insert("divide", "/");
        m.insert("raised to the power of", "**");
        m.insert("raised to", "**");
        m.insert("to the power of", "**");
        m.insert("mod", "%");
        m.insert("modulo", "%");
        m.insert("remainder", "%");

        m.insert("bitand", "&");
        m.insert("bit and", "&");
        m.insert("bitor", "|");
        m.insert("bit or", "|");
        m.insert("or", "|");
        m.insert("bitxor", "^");
        m.insert("bit xor", "^");
        m.insert("xor", "^");
        m.insert("bitnot", "~");
        m.insert("bit not", "~");
        m.insert("not", "~");
        m.insert("left shift", "<<");
        m.insert("shift left", "<<");
        m.insert("lshift", "<<");
        m.insert("right shift", ">>");
        m.insert("shift right", ">>");
        m.insert("rshift", ">>");
        m.insert("of", "*");
        m.insert("in", "IN");
        m.insert("into", "IN");
        m.insert("to", "TO");
        m.insert("as", "TO");

        m
    });

#[doc(hidden)]
pub static FUNCTION_MAPPINGS: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
    let mut m = HashMap::new();

    // Trigonometric
    m.insert("sine", "sin");
    m.insert("cosine", "cos");
    m.insert("tangent", "tan");
    m.insert("arc sine", "asin");
    m.insert("arcsine", "asin");
    m.insert("arcsin", "asin");
    m.insert("arc cosine", "acos");
    m.insert("arccos", "acos");
    m.insert("arccosine", "acos");
    m.insert("arc tangent", "atan");
    m.insert("arctan", "atan");
    m.insert("arctangent", "atan");
    m.insert("hyperbolic sine", "sinh");
    m.insert("hyperbolic cosine", "cosh");
    m.insert("hyperbolic tangent", "tanh");
    m.insert("arcsinh", "asinh");
    m.insert("arccosh", "acosh");
    m.insert("arctanh", "atanh");
    m.insert("inverse sine", "asin");
    m.insert("inverse cosine", "acos");
    m.insert("inverse tangent", "atan");
    m.insert("inverse hyperbolic sine", "asinh");
    m.insert("inverse hyperbolic cosine", "acosh");
    m.insert("inverse hyperbolic tangent", "atanh");
    m.insert("arc cos", "acos");
    m.insert("arc sin", "asin");
    m.insert("arc tan", "atan");
    m.insert("hyperbolic arcsine", "asinh");
    m.insert("hyperbolic arccosine", "acosh");
    m.insert("hyperbolic arctangent", "atanh");

    // Logarithmic
    m.insert("logarithm", "log");
    m.insert("natural log", "log");
    m.insert("natural logarithm", "log");
    m.insert("ln", "log");
    m.insert("log base ten", "log10");
    m.insert("log ten", "log10");
    m.insert("log two", "log2");
    m.insert("log base two", "log2");

    // Power/Root
    m.insert("square root", "sqrt");
    m.insert("cube root", "cbrt");
    m.insert("root", "sqrt");

    // Rounding/Absolute
    m.insert("absolute value", "abs");
    m.insert("abs value", "abs");
    m.insert("absolute", "abs");
    m.insert("magnitude", "abs");
    m.insert("ceiling", "ceil");

    // Factorial/Combinatorics
    m.insert("fact", "factorial");
    m.insert("factorial", "factorial");
    m.insert("nPr", "nPr");
    m.insert("nCr", "nCr");

    // Statistical
    m.insert("average", "mean");
    m.insert("stdev", "std");
    m.insert("gcd", "gcd");
    m.insert("lcm", "lcm");
    m.insert("perm", "perm");
    m.insert("comb", "comb");

    // Percentage
    m.insert("percent_of", "percentof");
    m.insert("as_percent", "aspercent");

    // Prime
    m.insert("is_prime", "isprime");
    m.insert("prime_factors", "primefactors");
    m.insert("next_prime", "nextprime");
    m.insert("prev_prime", "prevprime");

    // Self-mappings (function name maps to itself)
    m.insert("convert", "convert");
    m.insert("temp", "temp");
    m.insert("floor", "floor");
    m.insert("trunc", "trunc");
    m.insert("sign", "sign");
    m.insert("degrees", "degrees");
    m.insert("radians", "radians");
    m.insert("hypot", "hypot");
    m.insert("round", "round");
    m.insert("pow", "pow");
    m.insert("atan2", "atan2");
    m.insert("log1p", "log1p");
    m.insert("expm1", "expm1");
    m.insert("uniform", "uniform");
    m.insert("cbrt", "cbrt");
    m.insert("sqrt", "sqrt");
    m.insert("log", "log");
    m.insert("log10", "log10");
    m.insert("log2", "log2");
    m.insert("abs", "abs");
    m.insert("exp", "exp");
    m.insert("ceil", "ceil");
    m.insert("clamp", "clamp");
    m.insert("sin", "sin");
    m.insert("cos", "cos");
    m.insert("tan", "tan");
    m.insert("asin", "asin");
    m.insert("acos", "acos");
    m.insert("atan", "atan");
    m.insert("sinh", "sinh");
    m.insert("cosh", "cosh");
    m.insert("tanh", "tanh");
    m.insert("asinh", "asinh");
    m.insert("acosh", "acosh");
    m.insert("atanh", "atanh");

    // Aggregate functions
    m.insert("mean", "mean");
    m.insert("median", "median");
    m.insert("mode", "mode");
    m.insert("std", "std");
    m.insert("std_sample", "std_sample");
    m.insert("stds", "std_sample");
    m.insert("variance", "variance");
    m.insert("var", "var");
    m.insert("variance_sample", "variance_sample");
    m.insert("vars", "vars");
    m.insert("var_sample", "var_sample");
    m.insert("sum", "sum");
    m.insert("max", "max");
    m.insert("min", "min");
    m.insert("product", "product");

    // Complex number functions
    m.insert("real", "real");
    m.insert("imag", "imag");
    m.insert("conj", "conj");
    m.insert("conjugate", "conj");
    m.insert("phase", "phase");
    m.insert("polar", "polar");
    m.insert("rect", "rect");

    // Bitwise functions
    m.insert("bitand", "bitand");
    m.insert("bitor", "bitor");
    m.insert("bitxor", "bitxor");
    m.insert("bitnot", "bitnot");
    m.insert("bitlshift", "bitlshift");
    m.insert("bitrshift", "bitrshift");

    // Memory functions
    m.insert("store", "store");
    m.insert("recall", "recall");
    m.insert("Mplus", "Mplus");
    m.insert("Mminus", "Mminus");
    m.insert("MC", "MC");
    m.insert("MR", "MR");
    m.insert("M", "MR");
    m.insert("setvar", "setvar");
    m.insert("getvar", "getvar");
    m.insert("delvar", "delvar");
    m.insert("listvars", "listvars");
    m.insert("clearvars", "clearvars");

    // Random functions
    m.insert("random", "random");
    m.insert("randint", "randint");
    m.insert("randrange", "randrange");
    m.insert("randn", "randn");
    m.insert("gauss", "gauss");
    m.insert("seed", "seed");

    m
});

#[doc(hidden)]
pub static CONSTANT_WORDS: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
    let mut m = HashMap::new();
    m.insert("avogadro number", "na");
    m.insert("avogadro", "na");
    m.insert("avogadros", "na");
    m.insert("gas constant", "r");
    m.insert("molar gas constant", "r");
    m.insert("ideal gas constant", "r");
    m.insert("planck constant", "planckconstant");
    m.insert("planck", "planckconstant");
    m.insert("boltzmann constant", "k");
    m.insert("boltzmann", "k");
    m.insert("speed of light", "c");
    m.insert("speed of light in vacuum", "c");
    m.insert("c zero", "c");
    m.insert("elementary charge", "elementarycharge");
    m.insert("e charge", "elementarycharge");
    m.insert("faraday constant", "f");
    m.insert("faraday", "f");
    m.insert("atomic mass", "u");
    m.insert("atomic mass unit", "u");
    m.insert("amu", "u");
    m.insert("vacuum permittivity", "epsilon0");
    m.insert("permittivity of free space", "epsilon0");
    m.insert("vacuum permeability", "mu0");
    m.insert("permeability of free space", "mu0");
    m.insert("magnetic constant", "mu0");
    m.insert("standard gravity", "standardgravity");
    m.insert("gravity", "standardgravity");
    m.insert("earth gravity", "standardgravity");
    m.insert("gravitational constant", "gravitationalconstant");
    m.insert("newton constant", "gravitationalconstant");
    m.insert("big g", "G");
    m.insert("electron mass", "me");
    m.insert("proton mass", "mp");
    m.insert("neutron mass", "mn");
    m.insert("classical electron radius", "re");
    m.insert("electron radius", "re");
    m.insert("fine structure constant", "alpha");
    m.insert("sommerfeld", "alpha");
    m.insert("rydberg constant", "rydberg");
    m.insert("stefan boltzmann", "stefan");
    m.insert("stefan-boltzmann constant", "stefan");
    m.insert("wien constant", "wien");
    m.insert("wien displacement", "wien");
    m
});

#[doc(hidden)]
pub static STRIPPED_PHRASES: LazyLock<Vec<&'static str>> = LazyLock::new(|| {
    vec![
        "what's",
        "what is",
        "a",
        "?",
        "calculate",
        "compute",
        "tell me",
        "give me",
        "the ",
        "please ",
        "hey ",
        "hi ",
        "can you ",
        "could you ",
        "would you ",
        "i want to know ",
        "i'd like to know ",
        "what's the value of ",
        "what's the result of ",
        "what is the value of ",
        "what is the result of ",
        "the value of ",
        "the result of ",
        "the answer is ",
        "and ",
    ]
});

fn word_boundary_regex(word: &str) -> String {
    format!(r"\b{}\b", regex_escape(word))
}

/// Compile all calculator normalization patterns before a bounded call starts.
///
/// The MCP budget measures handler execution, so one-time regex compilation
/// must not be charged to the first request that happens to normalize text.
///
/// NOTE: callers must invoke this OFF the async runtime thread (see
/// `ensure_calculator_warmed_detached` in `mcp::execution`). In debug builds
/// the unit-alternation patterns below take multiple wall-clock seconds to
/// compile, and running that inline on a runtime thread starves its timer
/// wheel.
pub fn warm_calculator_regex_cache() {
    let _ = &*PCT_SYMBOL_RE;
    let _ = &*PERCENT_RE;
    let _ = &*COMPLEX_RE;
    let _ = &*UNIT_ALT;
    let _ = &*NUMBER_WORD_ALT;
    let _ = &*TEMP_UNITS_LIST;
    let _ = &*TEMP_CONVERSION_RE;
    let _ = &*BINARY_WORD_RE;
    let _ = &*BINARY_WORD_INNER_RE;
    let _ = &*TO_THE_POWER_RE;
    let _ = &*DEGREES_NON_TEMP_RE;
    let _ = &*DEGREES_RE;
    let _ = &*POINT_RE;
    let _ = &*MERGE_DECIMAL_RE;
    let _ = &*IMPLICIT_MUL_FUNC_RE;
    let _ = &*IMPLICIT_MUL_PAREN_RE;
    let _ = &*IMPLICIT_MUL_DIGIT_PAREN_RE;
    let _ = &*FACTORIAL_RE;
    let _ = &*SPLIT_NUM_MINUS_RE;
    let _ = &*SPLIT_DOUBLE_MINUS_RE;
    let _ = &*SPLIT_TRAILING_MINUS_RE;
    let _ = &*UNIT_INLINE_RE;
    let _ = &*SAME_UNIT_DIV_RE;
    let _ = &*CONVERT_SIMPLE_RE;
    let _ = &*CONVERT_BARE_RE;
    let _ = &*TEMP_HANDLE_RE;
    let _ = &*HYPHEN_RE;
    let _ = &*NUMBER_WORD_RE;
    let _ = unit_caret_attach_re();
    let _ = unit_caret_denom_re();
    let _ = unit_caret_paren_re();
    let _ = &*UNIT_POWER_RE;
    let _ = &*UNIT_SPELLED_RE;
    let _ = &*UNIT_COMPOUND_RE;
    let _ = &*BARE_COMPOUND_UNIT_RE;
    let _ = &*SPLIT_UNIT_DIV_RE;
    let _ = &*PER_UNIT_RE;
    let _ = &*BARE_SIMPLE_UNIT_RE;
    let _ = &*TEMP_DEG_CONV_PATTERNS;
    let _ = &*TEMP_DEG_UNIT_PATTERNS;
    let _ = &*DIGIT_SCALE_PATTERNS;
    let _ = &*CONSTANT_PATTERNS;
    let _ = &*MULTI_WORD_PATTERNS;
    let _ = &*STRIPPED_LONG_PATTERNS;
    let _ = &*STRIPPED_SHORT_PATTERNS;
    let _ = &*OPERATOR_PATTERNS;
    let _ = &*FUNC_NAME_PATTERNS;
    let _ = &*COMPACT_FUNC_RE;
    let _ = &*FUNC_FIX_PATTERNS;
    let _ = &*NUMBER_WORDS;
    let _ = &*MULTI_WORD_NUMBERS;
    let _ = &*OPERATOR_CONVERSIONS;
    let _ = &*FUNCTION_MAPPINGS;
    let _ = &*CONSTANT_WORDS;
    let _ = &*STRIPPED_PHRASES;
}

/// Combine consecutive number words in a string.
///
/// After number word replacement, "twenty one" becomes "20 1". This function
/// scans for sequences of space-separated numbers and combines them:
/// - "20 1" -> "21" (tens + ones)
/// - "100 2 3" -> "123" (hundreds + tens + ones)
/// - "1 100 20 2" -> "1*100+22" (single + compound)
fn combine_consecutive_number_words(input: &str) -> String {
    let parts: Vec<&str> = input.split_whitespace().collect();
    if parts.is_empty() {
        return input.to_string();
    }

    // Find runs of consecutive numeric tokens (possibly with spaces between them)
    let mut result = Vec::new();
    let mut i = 0;

    while i < parts.len() {
        // Check if this part is a number (possibly with leading/trailing sign)
        if let Some(first_num) = parse_simple_number(parts[i]) {
            // Collect the run of numbers
            let mut run: Vec<(String, f64)> = vec![(parts[i].to_string(), first_num)];
            let mut j = i + 1;
            while j < parts.len() {
                if let Some(n) = parse_simple_number(parts[j]) {
                    run.push((parts[j].to_string(), n));
                    j += 1;
                } else {
                    break;
                }
            }

            if run.len() > 1 {
                // We have a run of numbers to combine
                let combined = combine_number_run(&run);
                for token in combined {
                    result.push(token);
                }
            } else {
                result.push(parts[i].to_string());
            }
            i = j;
        } else {
            result.push(parts[i].to_string());
            i += 1;
        }
    }

    result.join(" ")
}

/// Try to parse a simple integer or float from a token.
///
/// `+` is stripped explicitly so `+1` normalizes the same as `1`; `-`
/// is preserved so `parse::<f64>` handles the sign (asymmetric but
/// intentional — `+` is filler, `-` is semantic).
fn parse_simple_number(token: &str) -> Option<f64> {
    let s = token.strip_prefix('+').unwrap_or(token);
    s.parse::<f64>().ok()
}

/// Combine a run of numbers into final tokens.
///
/// Uses the same logic as Python's combine_number_parts:
/// - Tens + ones combine: [20, 2] -> ["22"]
/// - Hundreds chain with multiplication: [3, 100, 20, 2] -> ["3", "*", "100", "+", "22"]
/// - Simple additions stay as-is: [5, 3] -> ["5", "+", "3"]
///
/// Scientific notation tokens (e.g. "32e73") are never combined with adjacent
/// numbers via compound-number logic. They are standalone numeric literals and
/// are joined with `+` (matching Python/eggcalc parity where "32E73 33"
/// normalizes to "32E73+33").
fn combine_number_run(run: &[(String, f64)]) -> Vec<String> {
    if run.is_empty() {
        return vec![];
    }

    let values: Vec<f64> = run.iter().map(|(_, v)| *v).collect();

    // Scientific notation numbers (containing 'e') must not be treated as
    // compound-number components (hundreds, thousands, etc.). Without this
    // guard, "32e73 33" would combine 3.2e74 with 33 via the large-scale
    // branch of combine_number_parts, producing a 74-digit literal that
    // exhausts the fancy-regex backtrack limit in later normalization stages.
    let has_scientific = run.iter().any(|(s, _)| s.contains('e'));

    // Check if this is a compound number (has tens >= 20 or hundreds)
    let has_compound = !has_scientific
        && values
            .iter()
            .any(|&v| v >= 100.0 || ((20.0..100.0).contains(&v) && v % 10.0 == 0.0));

    if has_compound && values.len() > 1 {
        combine_number_parts(&values)
    } else {
        // Simple addition: keep as separate numbers with + between
        let mut result = Vec::new();
        for (i, (orig, _)) in run.iter().enumerate() {
            if i > 0 {
                result.push("+".to_string());
            }
            result.push(orig.clone());
        }
        result
    }
}

/// Combine number parts into a single numeric token.
///
/// English cardinal numbers are built from an accumulating group below the
/// current large scale:
/// - [20, 2] -> 22
/// - [3, 100, 20, 2] -> 322
/// - [1, 100, 20, 1, 1000] -> 121000
fn combine_number_parts(values: &[f64]) -> Vec<String> {
    if values.is_empty() {
        return vec![];
    }

    let mut total = 0.0;
    let mut group = 0.0;

    for &part in values {
        if part == 100.0 {
            if group == 0.0 {
                group = 1.0;
            }
            group *= part;
        } else if part >= 1000.0 {
            if group == 0.0 {
                group = 1.0;
            }
            total += group * part;
            group = 0.0;
        } else {
            group += part;
        }
    }

    vec![format_integer_or_float(total + group)]
}

/// Format a number for output, showing integers without decimal point.
pub(crate) fn format_integer_or_float(v: f64) -> String {
    if v.fract() == 0.0
        && v.abs() <= 9_007_199_254_740_992.0
        && v >= i64::MIN as f64
        && v < 9_223_372_036_854_775_808.0
    {
        format!("{}", v as i64)
    } else {
        format!("{}", v)
    }
}

/// NZ-2: Canonicalize compact lowercase temperature conversion phrases.
///
/// Lowercase c/f/k are accepted as temperature units by the unit preprocessor,
/// but conversion words are replaced before token handling. A phrase like
/// "100 c in f" otherwise collapses into "100cINf" and the conversion detector
/// never sees separate source/target unit tokens.
fn normalize_lowercase_temperature_conversion(expr: &str) -> Result<String, String> {
    try_replace_all(
        "normalize_lowercase_temperature_conversion",
        &TEMP_CONVERSION_RE,
        expr,
        |caps: &Captures| {
            let from_unit = caps[2].to_uppercase();
            let to_unit = caps[4].to_uppercase();
            let conv_word = caps[3].to_uppercase();
            format!("{} {} {} {}", &caps[1], from_unit, conv_word, to_unit)
        },
    )
}

/// NZ-7: Check for ambiguous binary word usage like "5 not 6" or "1 in 2".
/// These words are reserved for unary bitwise NOT or unit conversion. When
/// they appear between two numeric values, the meaning is ambiguous.
fn binary_word_check(expr: &str) -> Result<(), String> {
    let m = BINARY_WORD_RE
        .find(expr)
        .map_err(|err| normalization_regex_error("binary_word_check", err))?;
    if let Some(m) = m {
        let matched = m.as_str();
        let wm = BINARY_WORD_INNER_RE
            .find(matched)
            .map_err(|err| normalization_regex_error("binary_word_check_inner", err))?;
        if let Some(wm) = wm {
            let word = wm.as_str().to_lowercase();
            return Err(format!(
                "Syntax error: '{}' is not a binary operator in this context. \
                 Use parentheses for unary 'not' (e.g., '~(5+6)'); \
                 for unit conversion, follow the pattern '<value> in <unit>'.",
                word
            ));
        }
    }
    Ok(())
}

pub fn normalize(expr: &str) -> Result<String, String> {
    if expr.len() > MAX_TEXT_LENGTH {
        return Err(format!("Input exceeds {} bytes", MAX_TEXT_LENGTH));
    }

    // M16: Replace unicode math operators with ASCII equivalents BEFORE lowercasing
    let mut result = expr.replace('\u{00d7}', "*"); // × → *
    result = result.replace('\u{00f7}', "/"); // ÷ → /
    result = result.replace('\u{2212}', "-"); // − → -

    let result = result.to_lowercase();

    // NZ-7: Binary word validation - check before any word replacement
    binary_word_check(&result)?;

    // NZ-2: Normalize lowercase temperature conversions before operator word replacement
    let result = normalize_lowercase_temperature_conversion(&result)?;

    // M18: Convert hyphens between number words to spaces
    // e.g., "twenty-one" -> "twenty one" (prevents hyphen being treated as minus)
    let mut result = try_replace_all("hyphen_between_number_words", &HYPHEN_RE, &result, "$1 $2")?;

    // Strip long filler phrases first (e.g., "what's the value of", "what is the result of")
    // These must be stripped before operator conversion to avoid partial matches
    for re in STRIPPED_LONG_PATTERNS.iter() {
        result = try_replace_all("strip_long_phrases", re, &result, "")?;
    }

    // M19: Handle "N to the M" power phrases BEFORE "to" is converted to operator
    result = try_replace_all("to_the_power", &TO_THE_POWER_RE, &result, "$1**$2")?;

    // NZ-8 + M24: Handle degrees → radian conversion BEFORE operator word replacement
    // Skip conversion for temperature units: "100 degrees in fahrenheit" stays as temperature
    // Temperature units that should NOT trigger angle conversion
    // First handle "N degrees in/to <temp_unit>" - keep as temperature, strip degrees
    for tu_re in TEMP_DEG_CONV_PATTERNS.iter() {
        result = try_replace_all("temp_deg_conv", tu_re, &result, "$1")?;
    }
    // Handle "N degrees <temp_unit>" (without in/to keyword) - keep as temperature
    for tu_re in TEMP_DEG_UNIT_PATTERNS.iter() {
        result = try_replace_all("temp_deg_unit", tu_re, &result, "$1")?;
    }
    // Handle "N degrees <non-temp-unit>" → convert angle to radians
    // e.g., "5 degrees radians" → "(5*pi/180)*radian"
    result = try_replace_all(
        "degrees_non_temp",
        &DEGREES_NON_TEMP_RE,
        &result,
        "($1*pi/180)*$2",
    )?;
    // Then handle remaining "N degrees" → radian conversion
    result = try_replace_all("degrees", &DEGREES_RE, &result, "($1*pi/180)")?;

    // NZ-4: Normalize spaced unit caret exponents: "5 m ^ 2" → "5 m2"
    // "5 m ^ 2" → "5 m2" (attached quantity with unit)
    if result.contains('^') {
        result = try_replace_all(
            "unit_caret_attach",
            unit_caret_attach_re(),
            &result,
            |caps: &Captures| {
                let unit = &caps[2];
                let power = &caps[3];
                format!("{} {}{}", &caps[1], unit, power)
            },
        )?;
        // "/ m ^ 2" → "/m**2" (denominator form)
        result = try_replace_all(
            "unit_caret_denom",
            unit_caret_denom_re(),
            &result,
            |caps: &Captures| {
                let unit = caps[1].to_lowercase();
                format!("/{}**{}", unit, &caps[2])
            },
        )?;
        // "/(m) ^ 2" → "/(m)**2" (parenthesized denominator)
        result = try_replace_all(
            "unit_caret_paren",
            unit_caret_paren_re(),
            &result,
            |caps: &Captures| {
                let unit = caps[1].to_lowercase();
                format!("/({})**{}", unit, &caps[2])
            },
        )?;
    }

    // M23: Handle "N thousand" scale words (evaluate to product)
    for (re, sv) in DIGIT_SCALE_PATTERNS.iter() {
        result = try_replace_all("digit_scale", re, &result, |caps: &Captures| {
            let v: f64 = caps[1].parse().unwrap_or(0.0);
            let product = v * sv;
            if product.fract() == 0.0 && product.abs() < 1e15 {
                format!("{}", product as i64)
            } else {
                format!("{}", product)
            }
        })?;
    }

    // Handle "N%" -> N/100
    result = try_replace_all("pct_symbol", &PCT_SYMBOL_RE, &result, "($1/100)")?;

    // Handle "N percent" -> N/100
    result = try_replace_all("percent", &PERCENT_RE, &result, "($1/100)")?;

    // Convert constant phrases (e.g., "gas constant" -> "R")
    // Sort by phrase length descending so multi-word phrases match before shorter ones
    for (re, canonical) in CONSTANT_PATTERNS.iter() {
        result = try_replace_all("constant_phrases", re, &result, *canonical)?;
    }

    // NZ-6: Replace multi-word fraction numbers before individual word replacement
    // e.g., "one half" -> "0.5", "two thirds" -> "0.666..."
    for (re, replacement) in MULTI_WORD_PATTERNS.iter() {
        result = try_replace_all("multi_word_fractions", re, &result, *replacement)?;
    }

    // Convert number words
    result = try_replace_all(
        "number_words",
        &NUMBER_WORD_RE,
        &result,
        |caps: &Captures| {
            NUMBER_WORDS
                .get(caps.get(1).map(|m| m.as_str()).unwrap_or(""))
                .copied()
                .unwrap_or("")
        },
    )?;

    // M20: Handle "point" as decimal separator: "5 point 3" -> "5.3"
    // Only when preceded by a digit or ')'
    // NOTE (BUG-006 / parity B6): This MUST run before
    // `combine_consecutive_number_words()` so that digit words following a
    // decimal point are absorbed into the fractional part rather than being
    // treated as a separate number ("three point one four" -> "3.14",
    // not "3.1 + 4").
    result = try_replace_all("point_decimal", &POINT_RE, &result, ".")?;

    // Merge digits following a decimal point: "3.1 4" -> "3.14"
    // After "point" replacement, space-separated digit words after the decimal
    // become separate tokens. Iteratively concatenate them into a single
    // decimal number.
    // A bounded pass prevents pathological input from consuming the entire
    // normalization budget while still handling ordinary decimal word runs.
    for _ in 0..16 {
        let next_result = try_replace_all("merge_decimal", &MERGE_DECIMAL_RE, &result, "$1$2")?;
        if next_result == result {
            break;
        }
        result = next_result;
    }

    // Combine consecutive number words: "twenty one" -> "21", "one hundred twenty two" -> "122"
    result = combine_consecutive_number_words(&result);

    // BUG-009 / parity B9: "kilometer per hour" / "miles per hour" forms.
    // Must run BEFORE the operator-word replacement (which converts "per"
    // into "/") and BEFORE the bare-unit "*" insertion below so the full
    // phrase is collapsed into a canonical compound unit first.
    result = try_replace_all("per_unit", &PER_UNIT_RE, &result, |caps: &Captures| {
        let num = &caps[1];
        let distance = caps[2].to_lowercase();
        let time = caps[3].to_lowercase();
        let dist_unit: &str = match distance.as_str() {
            "kilometer" | "kilometers" | "kilometre" | "kilometres" | "km" => "km",
            "mile" | "miles" | "mi" => "mi",
            "meter" | "meters" | "metre" | "metres" | "m" => "m",
            "foot" | "feet" | "ft" => "ft",
            "inch" | "inches" => "in",
            "yard" | "yards" | "yd" => "yd",
            _ => return caps[0].to_string(),
        };
        let time_unit: &str = match time.as_str() {
            "hour" | "hours" | "hr" | "h" => "h",
            "minute" | "minutes" | "min" => "min",
            "second" | "seconds" | "sec" | "s" => "s",
            _ => return caps[0].to_string(),
        };
        format!("{}*{}/{}", num, dist_unit, time_unit)
    })?;

    // BUG-009 / parity B9: "<num> <unit1> / <unit2>" split-rate forms.
    // "60 km / h" -> "(60*km)/h" so the right-hand unit isn't consumed as
    // the Planck constant `h` by the evaluator.
    result = try_replace_all(
        "split_unit_div",
        &SPLIT_UNIT_DIV_RE,
        &result,
        |caps: &Captures| {
            let num = caps.get(1).map(|m| m.as_str()).unwrap_or("0");
            let u1 = caps.get(2).map(|m| m.as_str()).unwrap_or("");
            let u2 = caps.get(3).map(|m| m.as_str()).unwrap_or("");
            // Emit "<num>*<u1>/<u2>" without parens so the inline regex
            // can still see the full compound unit when scanning the joined
            // expression. BUG-009 / parity B9.
            format!("{}*{}/{}", num, u1, u2)
        },
    )?;

    // BUG-009 / parity B9: bare compound unit forms. Insert "*" between
    // number and a compound unit ("60 km/h" -> "60*km/h") so the operator
    // splitter doesn't turn the embedded "/" into division.
    result = try_replace_all(
        "bare_compound_unit",
        &BARE_COMPOUND_UNIT_RE,
        &result,
        "$1*$3",
    )?;

    // BUG-009 / parity B9: bare simple unit forms. Insert "*" between a
    // number and a known spaced unit ("60 mph" -> "60*mph") so the token
    // survives operator splitting. Limited to long unit names to avoid
    // false positives with short identifiers.
    result = try_replace_all("bare_simple_unit", &BARE_SIMPLE_UNIT_RE, &result, "$1*$3")?;

    // M17: Split compact function forms: "sin30" -> "sin 30"
    // Guard names that already end in digits so "log10" remains as-is
    if let Some(ref compact_re) = *COMPACT_FUNC_RE {
        result = try_replace_all("compact_func", compact_re, &result, "$1 $2")?;
    }

    // Convert operator words - sort by length descending to ensure longer patterns match first
    for (re, symbol) in OPERATOR_PATTERNS.iter() {
        result = try_replace_all("operator_words", re, &result, *symbol)?;
    }

    // Convert function names - sort by length descending to ensure longer patterns match first
    for (re, standard) in FUNC_NAME_PATTERNS.iter() {
        result = try_replace_all("function_names", re, &result, *standard)?;
    }

    // Fix "func * expr" patterns caused by "of" → "*" conversion
    // Convert "cbrt * 8" → "cbrt(8)" for known function names
    // For multi-arg functions like "mean * 1+2+3", convert +/- to commas: "mean(1,2,3)"
    for (re, is_multi, func) in FUNC_FIX_PATTERNS.iter() {
        result = try_replace_all("func_fix", re, &result, |caps: &Captures| {
            let arg = caps[1].trim();
            if arg.is_empty() {
                format!("{} *", func)
            } else if *is_multi {
                // Replace top-level +/- with commas, preserving signs on numbers
                // e.g., "1+2+3" → "1,2,3", "-1+2" → "-1,2"
                let mut comma_parts = Vec::new();
                let mut current = String::new();
                let mut paren_depth = 0;
                let chars: Vec<char> = arg.chars().collect();
                let mut i = 0;
                while i < chars.len() {
                    match chars[i] {
                        '(' => {
                            paren_depth += 1;
                            current.push(chars[i]);
                            i += 1;
                        }
                        ')' => {
                            paren_depth -= 1;
                            current.push(chars[i]);
                            i += 1;
                        }
                        '+' | '-' if paren_depth == 0 && !current.is_empty() => {
                            // Check if this +/- is a sign (after operator or at start) or separator
                            let last_non_space = current.trim_end().chars().last();
                            match last_non_space {
                                Some('(') | Some('+') | Some('-') | Some('*') | Some('/')
                                | Some(',') => {
                                    // This is a sign character, not a separator
                                    current.push(chars[i]);
                                    i += 1;
                                }
                                _ => {
                                    // This is a separator
                                    let trimmed = current.trim().to_string();
                                    if !trimmed.is_empty() {
                                        comma_parts.push(trimmed);
                                    }
                                    current = String::new();
                                    // Include the sign as part of the next number
                                    if chars[i] == '-' {
                                        current.push('-');
                                    }
                                    i += 1;
                                }
                            }
                        }
                        _ => {
                            current.push(chars[i]);
                            i += 1;
                        }
                    }
                }
                let trimmed = current.trim().to_string();
                if !trimmed.is_empty() {
                    comma_parts.push(trimmed);
                }
                format!("{}({})", func, comma_parts.join(","))
            } else {
                format!("{}({})", func, arg)
            }
        })?;
    }

    // NZ-9 + M25: Postfix unit power words: "m squared" -> "m2", "cm cubed" -> "cm3"
    // Uses full UNIT_ALIASES to match any known unit before "squared"/"cubed"
    result = try_replace_all("unit_power", &UNIT_POWER_RE, &result, |caps: &Captures| {
        let unit = &caps[1];
        let power = if caps[2].eq_ignore_ascii_case("squared") {
            "2"
        } else {
            "3"
        };
        format!("{}{}", unit, power)
    })?;

    // BUG-009 / parity B9 patterns moved earlier in the pipeline (see the
    // pass inserted after `combine_consecutive_number_words()` above) so
    // they run before the operator-word replacement consumes "per".

    // NZ-10 + M26: Spelled unit conversions with full unit list
    // "30 km/h in mph" -> "convert(30*km/h,mph)"
    result = try_replace_all(
        "unit_spelled",
        &UNIT_SPELLED_RE,
        &result,
        "convert($1*$2,$3)",
    )?;

    // NZ-10 + M27: Compound unit conversions: "60mi/h in m/s" -> "convert(60*mi/h,m/s)"
    result = try_replace_all(
        "unit_compound",
        &UNIT_COMPOUND_RE,
        &result,
        |caps: &Captures| {
            let num = &caps[1];
            let from_num = &caps[2];
            let from_den = &caps[3];
            let to_num = &caps[4];
            let to_den = &caps[5];
            format!(
                "convert({}*{}/{},{}/{})",
                num, from_num, from_den, to_num, to_den
            )
        },
    )?;

    // Strip short filler phrases AFTER operator conversion (e.g., "the ", "please ")
    for re in STRIPPED_SHORT_PATTERNS.iter() {
        result = try_replace_all("strip_short_phrases", re, &result, "")?;
    }

    // M20 (relocated): "point" and decimal-merge have already been applied
    // before `combine_consecutive_number_words()` above (BUG-006 / parity B6).

    // Handle complex numbers: 3+4i -> 3+4j, 3 + 4i -> 3+4j, 3 + 4 i -> 3+4j
    result = try_replace_all("complex_number", &COMPLEX_RE, &result, "($1$2$3j)")?;

    // Normalize whitespace
    let mut result = result.split_whitespace().collect::<Vec<_>>().join(" ");

    // M22: Insert implicit * between adjacent tokens (5sin -> 5*sin, (2+3)(4) -> (2+3)*(4))
    // Handle: digit/)/(func, func/digit/)(, )(, digit)(

    // Insert * between digit/ ) and function name: "5sin" -> "5*sin", "(2+3)sin" -> "(2+3)*sin"
    result = try_replace_all("implicit_mul_func", &IMPLICIT_MUL_FUNC_RE, &result, "$1*$2")?;

    // Insert * between ) and digit/(: "(2+3)4" -> "(2+3)*4", "(2+3)(4+5)" -> "(2+3)*(4+5)"
    result = try_replace_all(
        "implicit_mul_paren",
        &IMPLICIT_MUL_PAREN_RE,
        &result,
        "$1*$2",
    )?;

    // Insert * between digit and (: "3(4+5)" -> "3*(4+5)"
    result = try_replace_all(
        "implicit_mul_digit_paren",
        &IMPLICIT_MUL_DIGIT_PAREN_RE,
        &result,
        "$1*(",
    )?;

    // NZ-13 + M21: Factorial postfix: "5!" -> "factorial(5)"
    // Iteratively handle nested factorial: "5!!" -> "factorial(5)!" -> "factorial(factorial(5))"
    // Also handles func(args)! e.g. "factorial(5)!" -> "factorial(factorial(5))"
    loop {
        let next = try_replace_all("factorial", &FACTORIAL_RE, &result, |caps: &Captures| {
            let content = &caps[1];
            let bangs = &caps[2];
            let mut out = format!("factorial({})", content);
            if bangs.len() > 1 {
                out.push_str(&"!".repeat(bangs.len() - 1));
            }
            out
        })?;
        if next == result {
            break;
        }
        result = next;
    }

    Ok(result)
}

pub fn split_at_operators(expr: &str) -> Vec<String> {
    let mut tokens = Vec::new();
    let mut current = String::new();
    let mut paren_depth = 0;
    let chars: Vec<char> = expr.chars().collect();
    let mut i = 0;

    while i < chars.len() {
        let ch = chars[i];
        match ch {
            '(' | '[' => {
                paren_depth += 1;
                current.push(ch);
                i += 1;
            }
            ')' | ']' => {
                paren_depth -= 1;
                current.push(ch);
                i += 1;
            }
            '+' | '-' if paren_depth == 0 => {
                // Use negative lookbehind to preserve "e+/e-" in scientific notation
                let is_scientific =
                    !current.is_empty() && matches!(current.chars().last(), Some('e') | Some('E'));
                if is_scientific {
                    current.push(ch);
                    i += 1;
                    continue;
                }
                if !current.trim().is_empty() {
                    tokens.push(current.trim().to_string());
                }
                tokens.push(ch.to_string());
                current = String::new();
                i += 1;
            }
            '/' | '%' if paren_depth == 0 => {
                if !current.trim().is_empty() {
                    tokens.push(current.trim().to_string());
                }
                tokens.push(ch.to_string());
                current = String::new();
                i += 1;
            }
            '*' | '^' if paren_depth == 0 => {
                // Handle ** (power operator)
                if ch == '*' && i + 1 < chars.len() && chars[i + 1] == '*' {
                    if !current.trim().is_empty() {
                        tokens.push(current.trim().to_string());
                    }
                    tokens.push("**".to_string());
                    current = String::new();
                    i += 2;
                    continue;
                }
                if !current.trim().is_empty() {
                    tokens.push(current.trim().to_string());
                }
                tokens.push(ch.to_string());
                current = String::new();
                i += 1;
            }
            _ => {
                current.push(ch);
                i += 1;
            }
        }
    }

    if !current.trim().is_empty() {
        tokens.push(current.trim().to_string());
    }

    // Post-split cleanup: handle edge cases the main loop leaves behind.
    // Walk with a while-loop so newly-inserted tokens get re-checked.
    let mut i = 0;
    while i < tokens.len() {
        let token = tokens[i].clone();
        let is_op = token == "+"
            || token == "-"
            || token == "/"
            || token == "%"
            || token == "*"
            || token == "**"
            || token == "^";

        if !is_op {
            // Case 1: "4-5-3" (multiple subtractions in one token)
            if should_split_number_minus(&token) {
                let parts: Vec<&str> = token.splitn(2, '-').collect();
                tokens[i] = parts[0].to_string();
                tokens.insert(i + 1, "-".to_string());
                tokens.insert(i + 2, parts[1].to_string());
                continue; // re-check the new token at i (now parts[0])
            }
            // Case 2: "5-" trailing minus (e.g., "5-(3+2)" → "5-" then "(3+2)")
            else if should_split_trailing_minus(&token) {
                let num_part = &token[..token.len() - 1];
                tokens[i] = num_part.to_string();
                tokens.insert(i + 1, "-".to_string());
                continue; // re-check
            }
            // Case 3: "4--5" (double minus → subtraction of negative)
            else if should_split_double_minus(&token) {
                let parts: Vec<&str> = token.splitn(2, "--").collect();
                tokens[i] = parts[0].to_string();
                tokens.insert(i + 1, "-".to_string());
                tokens.insert(i + 2, format!("-{}", parts[1]));
                // Don't advance — re-check the new token at i
                continue;
            }
            // Case 4: Space-separated number sequences
            else if should_split_number_sequence(&token) {
                let parts: Vec<&str> = token.split_whitespace().collect();
                let mut new_tokens: Vec<String> = Vec::new();
                for (pi, part) in parts.iter().enumerate() {
                    if pi > 0 {
                        new_tokens.push("+".to_string());
                    }
                    new_tokens.push(part.to_string());
                }
                tokens.splice(i..i + 1, new_tokens);
                continue; // re-check
            }
        }
        i += 1;
    }

    tokens
}

/// Check if token matches pattern: digit-sequence minus digit-sequence (e.g., "4-5-3").
///
/// `unwrap_or(false)` is safe here: `SPLIT_NUM_MINUS_RE` is a static pattern
/// (`^\d+(?:-\d+)+$`) with no fancy features and no backtracking ambiguity,
/// so a runtime error cannot occur in practice. Treating a hypothetical error
/// as "no match" does not alter normalization semantics for this anchored,
/// linear-time pattern.
fn should_split_number_minus(token: &str) -> bool {
    SPLIT_NUM_MINUS_RE.is_match(token).unwrap_or(false)
}

/// Check if token matches pattern: digit-sequence -- digit-sequence (e.g., "4--5").
///
/// Same justification as `should_split_number_minus`: the pattern
/// (`^\d+--\d+`) is static, linear-time, and cannot produce a runtime error.
fn should_split_double_minus(token: &str) -> bool {
    SPLIT_DOUBLE_MINUS_RE.is_match(token).unwrap_or(false)
}

/// Check if token ends with a trailing minus (e.g., "5-" when followed by parenthesized expr).
///
/// Same justification as `should_split_number_minus`: the pattern
/// (`^\d+-$`) is static, linear-time, and cannot produce a runtime error.
fn should_split_trailing_minus(token: &str) -> bool {
    SPLIT_TRAILING_MINUS_RE.is_match(token).unwrap_or(false)
}

/// Check if token is a space-separated number sequence (e.g., "3 100 20 2").
fn should_split_number_sequence(token: &str) -> bool {
    if !token.contains(' ') {
        return false;
    }
    let parts: Vec<&str> = token.split_whitespace().collect();
    if parts.len() < 2 {
        return false;
    }
    for part in &parts {
        let stripped = part.trim_start_matches('+').trim_start_matches('-');
        if stripped.is_empty() {
            return false;
        }
        // Must be a number (integer or float, possibly scientific notation)
        if stripped.parse::<f64>().is_err() {
            return false;
        }
    }
    true
}

#[doc(hidden)]
pub fn preprocess_units(tokens: &[String]) -> Result<(Vec<String>, Option<String>), String> {
    // BUG-009 / parity B9: After split_at_operators(), unit-bearing tokens
    // like "60*mph" may have been broken into ["60", "*", "mph"]. We need to
    // operate on the joined string so the regex can see contiguous
    // "<num>*<unit>" segments.

    let joined = tokens.join("");

    // First pass: find the first unit segment in the joined string. Search
    // the inline regex (for normal units) first, then check for the percent
    // operator as a unit suffix only when it isn't followed by a digit (to
    // avoid misreading `17 % 5` as `<num>=17, unit=%`).
    let mut detected_unit: Option<String> = UNIT_INLINE_RE
        .captures(&joined)
        .map_err(|err| normalization_regex_error("preprocess_units_detect", err))?
        .and_then(|caps| {
            let unit = caps.name("unit").map(|m| m.as_str()).unwrap_or("");
            // Accept known aliases OR compound forms (e.g. "mi/min"). Python
            // preserves "1 mi/min" verbatim even though mi/min isn't in its
            // UNIT_ALIASES table.
            if let Some(canon) = resolve_unit_alias(unit) {
                return Some(canon);
            }
            if unit.contains('/') {
                return Some(unit.to_string());
            }
            None
        });

    if detected_unit.is_none() {
        // Look for percent as a unit suffix: `<num>%` not followed by a
        // digit (so we don't catch `17 % 5` modulo).
        if let Some(idx) = joined.find('%') {
            // Walk backwards from `%` to confirm it's preceded by digits.
            let prefix = &joined[..idx];
            if prefix.ends_with(|c: char| c.is_ascii_digit() || c == '.') {
                // Confirm next char (if any) is NOT a digit.
                let after = joined.as_bytes().get(idx + 1).copied().unwrap_or(b' ');
                if !after.is_ascii_digit() {
                    detected_unit = Some("%".to_string());
                }
            }
        }
    }

    let target_unit = match detected_unit.as_deref() {
        Some(u) => u,
        None => return Ok((tokens.to_vec(), None)),
    };

    // Second pass: convert every "<num>*<unit>" segment to the target unit.
    // We rewrite the joined string, leaving non-unit text untouched.
    let rewritten = try_replace_all(
        "preprocess_units_convert",
        &UNIT_INLINE_RE,
        &joined,
        |caps: &Captures| {
            let num_str = caps.name("num").map(|m| m.as_str()).unwrap_or("0");
            let unit = caps.name("unit").map(|m| m.as_str()).unwrap_or("");
            match resolve_unit_alias(unit) {
                None => caps[0].to_string(),
                Some(canon) if canon == target_unit => num_str.to_string(),
                Some(canon) => {
                    // BUG-009 / parity B9: preserve compound units (e.g.,
                    // "mi/min", "km/s") that aren't tracked in UNIT_ALIASES as
                    // plain display strings rather than mangling them. Python
                    // parity preserves "1 mi/min" verbatim.
                    if canon.contains('/')
                        && !crate::calc::units::UNIT_ALIASES.contains_key(canon.as_str())
                    {
                        return caps[0].to_string();
                    }
                    match crate::calc::units::get_conversion_factor(&canon, target_unit) {
                        Ok(factor) => {
                            if let Ok(num) = num_str.parse::<f64>() {
                                let converted = num * factor;
                                if converted.fract() == 0.0 && converted.abs() < 1e15 {
                                    format!("{}", converted as i64)
                                } else {
                                    format!("{}", converted)
                                }
                            } else {
                                num_str.to_string()
                            }
                        }
                        Err(_) => caps[0].to_string(),
                    }
                }
            }
        },
    )?;

    // Re-tokenize the rewritten string so downstream consumers (which expect
    // a Vec<String>) see the converted values.
    let mut re_tokens = split_at_operators(&rewritten);

    // If target_unit is "%", strip "%" from the rewritten string because
    // the evaluator doesn't understand unit suffixes for percent; the
    // caller's run() will append "%" to the formatted value.
    if target_unit == "%" {
        re_tokens.retain(|t| t != "%");
    }

    Ok((re_tokens, Some(target_unit.to_string())))
}

fn resolve_unit_alias(unit: &str) -> Option<String> {
    if let Some(canon) = crate::calc::units::UNIT_ALIASES.get(unit) {
        return Some(canon.to_string());
    }
    let lower = unit.to_lowercase();
    if let Some(canon) = crate::calc::units::UNIT_ALIASES.get(lower.as_str()) {
        return Some(canon.to_string());
    }
    None
}

/// Result of run - tuple of (string_representation, type_name)
pub type RunResult = (String, String);

/// Error type for `run()` that distinguishes evaluation errors from other errors.
#[derive(Debug, Clone)]
pub enum RunError {
    /// An error during expression evaluation (parse error, division by zero, etc.)
    Evaluation(String),
    /// An error during normalization or other processing
    Internal(String),
}

impl std::fmt::Display for RunError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RunError::Evaluation(msg) => write!(f, "{}", msg),
            RunError::Internal(msg) => write!(f, "{}", msg),
        }
    }
}

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

/// NZ-3: Wrap the denominator in parentheses for unit-on-division-right.
///
/// Detects patterns like "5*m/3*s" or "10*km/5*hr" where the right
/// operand of a division has a trailing unit, and wraps the entire
/// right operand in parens to preserve correct operator precedence.
pub fn add_same_unit_division_parens(expr: &str) -> Result<String, String> {
    try_replace_all(
        "add_same_unit_division_parens",
        &SAME_UNIT_DIV_RE,
        expr,
        |caps: &Captures| {
            let left_unit = &caps[1];
            let denom = &caps[2];
            let right_unit = &caps[3];
            format!("{}/({}*{})", left_unit, denom, right_unit)
        },
    )
}

/// Run natural language expression through the full pipeline.
///
/// This function normalizes the input (converting number words to digits,
/// operator words to symbols), tokenizes it, and evaluates the result.
///
/// # Arguments
///
/// * `expr` - A string slice containing the natural language expression
///
/// # Returns
///
/// * `Ok((String, String))` - The result and type
/// * `Err(RunError)` - An error if processing fails, distinguished by type
///
/// # Examples
///
/// ```
/// use eggsact::calc::run;
///
/// assert_eq!(run("thirty plus five").unwrap(), ("35".to_string(), "int".to_string()));
/// assert_eq!(run("two to the power of ten").unwrap(), ("1024".to_string(), "int".to_string()));
/// ```
pub fn run(expr: &str) -> Result<RunResult, RunError> {
    let normalized = normalize(expr).map_err(RunError::Internal)?;

    // Handle convert() and temp() patterns before evaluation
    if let Some(result) = handle_convert_pattern(&normalized) {
        return result.map_err(RunError::Evaluation);
    }
    if let Some(result) = handle_temp_pattern(&normalized) {
        return result.map_err(RunError::Evaluation);
    }

    let tokens = split_at_operators(&normalized);
    let (tokens, detected_unit) = preprocess_units(&tokens).map_err(RunError::Internal)?;
    let processed = tokens.join("");

    let processed = add_same_unit_division_parens(&processed).map_err(RunError::Internal)?;

    let (value, value_type) =
        crate::calc::evaluator::evaluate(&processed).map_err(RunError::Evaluation)?;
    if let Some(unit) = detected_unit {
        Ok((format!("{} {}", value, unit), value_type))
    } else {
        Ok((value, value_type))
    }
}

/// Run natural language expression through the full pipeline with explicit context.
///
/// This is the context-aware version of [`run`] that uses the provided
/// [`EvalContext`](crate::calc::EvalContext) for evaluation instead of global statics.
pub fn run_with_context(
    expr: &str,
    ctx: &mut crate::calc::context::EvalContext,
) -> Result<RunResult, RunError> {
    let normalized = normalize(expr).map_err(RunError::Internal)?;

    // Handle convert() and temp() patterns before evaluation
    if let Some(result) = handle_convert_pattern(&normalized) {
        return result.map_err(RunError::Evaluation);
    }
    if let Some(result) = handle_temp_pattern(&normalized) {
        return result.map_err(RunError::Evaluation);
    }

    let tokens = split_at_operators(&normalized);
    let (tokens, detected_unit) = preprocess_units(&tokens).map_err(RunError::Internal)?;
    let processed = tokens.join("");

    // NZ-3: Wrap denominator in parens for unit-on-division-right patterns
    // "5*m/3*s" → "5*m/(3*s)" so trailing units bind to the right operand
    let processed = add_same_unit_division_parens(&processed).map_err(RunError::Internal)?;

    let (value, value_type) = crate::calc::evaluator::evaluate_with_context(&processed, ctx)
        .map_err(RunError::Evaluation)?;
    if let Some(unit) = detected_unit {
        Ok((format!("{} {}", value, unit), value_type))
    } else {
        Ok((value, value_type))
    }
}

/// Handle `convert(value*unit, target_unit)` patterns.
///
/// After normalization, expressions like "30 km/h in mph" become
/// `convert(30*km/h,mph)`. This function detects and handles those
/// patterns before they reach the evaluator (which doesn't know about units).
fn handle_convert_pattern(normalized: &str) -> Option<Result<RunResult, String>> {
    // Match: convert(NUM*UNIT/TARGET_UNIT,TARGET) or convert(NUM*UNIT,TARGET)
    // The value part can be: NUM*UNIT, NUM*UNIT/UNIT, or just NUM
    if let Ok(Some(caps)) = CONVERT_SIMPLE_RE.captures(normalized) {
        let num_str = &caps[1];
        let from_unit = &caps[2];
        let to_unit = &caps[3];

        let value = num_str.parse::<f64>().ok()?;
        return Some(handle_convert_value(value, from_unit, to_unit));
    }

    // Also match: convert(NUM, target_unit) — dimensionless value
    if let Ok(Some(caps)) = CONVERT_BARE_RE.captures(normalized) {
        let num_str = &caps[1];
        let to_unit = &caps[2];

        let value = num_str.parse::<f64>().ok()?;
        // Dimensionless to unit: just try to create the unit
        return Some(Ok((
            format!("{} {}", format_integer_or_float(value), to_unit),
            "float".to_string(),
        )));
    }

    None
}

/// Resolve a unit symbol to its canonical form using `UNIT_ALIASES`, tolerating
/// case mismatches (e.g., "CELSIUS", "Celsius", "celsius"). Mirrors the
/// case-folding done by `convert_temperature`.
fn resolve_unit_canon(unit: &str) -> String {
    if let Some(canon) = crate::calc::units::UNIT_ALIASES.get(unit).copied() {
        return canon.to_string();
    }
    let lower = unit.to_lowercase();
    if let Some(canon) = crate::calc::units::UNIT_ALIASES
        .get(lower.as_str())
        .copied()
    {
        return canon.to_string();
    }
    unit.to_string()
}

/// Perform the actual unit conversion for convert(value, from_unit, to_unit).
fn handle_convert_value(value: f64, from_unit: &str, to_unit: &str) -> Result<RunResult, String> {
    // Check if from_unit or to_unit are temperature units
    let from_resolved = resolve_unit_canon(from_unit);
    let to_resolved = resolve_unit_canon(to_unit);

    let from_is_temp = crate::calc::units::UNIT_BASE
        .get(from_resolved.as_str())
        .map(|d| d.category == "temperature")
        .unwrap_or(false);
    let to_is_temp = crate::calc::units::UNIT_BASE
        .get(to_resolved.as_str())
        .map(|d| d.category == "temperature")
        .unwrap_or(false);

    if from_is_temp && to_is_temp {
        let converted =
            crate::calc::units::convert_temperature(value, &from_resolved, &to_resolved)?;
        Ok((
            format!("{} {}", format_integer_or_float(converted), to_resolved),
            "float".to_string(),
        ))
    } else {
        let factor = crate::calc::units::get_conversion_factor(&from_resolved, &to_resolved)?;
        let converted = value * factor;
        Ok((
            format!("{} {}", format_integer_or_float(converted), to_resolved),
            "float".to_string(),
        ))
    }
}

/// Handle `temp(value, from_unit, to_unit)` patterns.
fn handle_temp_pattern(normalized: &str) -> Option<Result<RunResult, String>> {
    if let Ok(Some(caps)) = TEMP_HANDLE_RE.captures(normalized) {
        let value_str = &caps[1];
        let from_unit = &caps[2];
        let to_unit = &caps[3];

        // Try to parse the value as a number
        if let Ok(value) = value_str.parse::<f64>() {
            match crate::calc::units::convert_temperature(value, from_unit, to_unit) {
                Ok(converted) => {
                    return Some(Ok((
                        format!("{} {}", format_integer_or_float(converted), to_unit),
                        "float".to_string(),
                    )));
                }
                Err(e) => {
                    return Some(Err(e));
                }
            }
        }
    }

    None
}