ries 1.1.1

Find algebraic equations given their solution - Rust implementation
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
//! Expression generation
//!
//! Generates valid postfix expressions by enumerating "forms" (stack effect patterns).
//!
//! # Streaming Architecture
//!
//! For high complexity levels, the traditional approach of generating ALL expressions
//! into memory before matching can cause memory exhaustion. This module provides both:
//!
//! - **Batch generation**: `generate_all()` returns all expressions (backward compatible)
//! - **Streaming generation**: `generate_streaming()` processes expressions via callbacks
//!
//! Streaming reduces memory from O(expressions) to O(depth) by processing expressions
//! as they're generated rather than accumulating them.

use crate::eval::{evaluate_fast_with_context, EvalContext};
use crate::symbol_table::SymbolTable;
use std::sync::Arc;

// =============================================================================
// NAMED CONSTANTS FOR QUANTIZATION AND VALUE LIMITS
// =============================================================================

/// Scale factor for quantizing floating-point values to integers.
///
/// This preserves approximately 8 significant digits, which is sufficient
/// for deduplication while avoiding overflow when converting to i64.
/// Values are quantized as: `(v * QUANTIZE_SCALE).round() as i64`
const QUANTIZE_SCALE: f64 = 1e8;

/// Maximum absolute value for quantization before using sentinel values.
///
/// Values larger than this threshold are represented by sentinel values
/// (i64::MAX - 1 for positive, i64::MIN + 1 for negative) to avoid
/// overflow during the quantization calculation.
const MAX_QUANTIZED_VALUE: f64 = 1e10;

/// Maximum absolute value for generated expressions.
///
/// Expressions with values larger than this are considered overflow-prone
/// and unlikely to be useful, so they are filtered out during generation.
const MAX_GENERATED_VALUE: f64 = 1e12;
use crate::expr::{EvaluatedExpr, Expression, MAX_EXPR_LEN};
use crate::profile::UserConstant;
use crate::symbol::{NumType, Seft, Symbol};
use crate::udf::UserFunction;
use std::collections::HashMap;

/// Configuration for expression generation
///
/// Controls which symbols are available, complexity limits,
/// and various generation options for creating candidate expressions
/// that may solve a given equation.
///
/// # Architecture
///
/// Expressions are generated in two categories:
/// - **LHS (Left-Hand Side)**: Expressions containing `x`, representing functions like `f(x)`
/// - **RHS (Right-Hand Side)**: Constant expressions not containing `x`, like `π²` or `sqrt(2)`
///
/// The generator creates all valid expressions up to the configured complexity limits,
/// then the solver finds pairs where `LHS(target) ≈ RHS`.
///
/// # Example
///
/// ```rust
/// use ries_rs::gen::GenConfig;
/// use ries_rs::symbol::Symbol;
/// use std::collections::HashMap;
///
/// let config = GenConfig {
///     max_lhs_complexity: 50,
///     max_rhs_complexity: 30,
///     max_length: 12,
///     constants: vec![Symbol::One, Symbol::Two, Symbol::Pi, Symbol::E],
///     unary_ops: vec![Symbol::Neg, Symbol::Sqrt, Symbol::Square],
///     binary_ops: vec![Symbol::Add, Symbol::Sub, Symbol::Mul, Symbol::Div],
///     ..GenConfig::default()
/// };
/// ```
#[derive(Clone)]
pub struct GenConfig {
    /// Maximum complexity score for left-hand-side expressions.
    ///
    /// LHS expressions contain `x` and represent the function side of equations.
    /// Higher values allow more complex expressions (e.g., `sin(x) + x²`), but
    /// exponentially increase search time and memory usage.
    ///
    /// Default: 128 (allows fairly complex expressions)
    pub max_lhs_complexity: u32,

    /// Maximum complexity score for right-hand-side expressions.
    ///
    /// RHS expressions are constants not containing `x`. Since they don't need
    /// to be solved for, they can typically use lower complexity limits than LHS.
    ///
    /// Default: 128
    pub max_rhs_complexity: u32,

    /// Maximum number of symbols in a single expression.
    ///
    /// This is a hard limit on expression length regardless of complexity score.
    /// Prevents pathological cases with many low-complexity symbols.
    ///
    /// Default: `MAX_EXPR_LEN` (255)
    pub max_length: usize,

    /// Symbols available for constants and variables (Seft::A type).
    ///
    /// These push a value onto the expression stack. Typically includes:
    /// - `One`, `Two`, `Three`, etc. (numeric constants)
    /// - `Pi`, `E` (mathematical constants)
    /// - `X` (the variable to solve for)
    ///
    /// Default: All built-in constants from `Symbol::constants()`
    pub constants: Vec<Symbol>,

    /// Symbols available for unary operations (Seft::B type).
    ///
    /// These transform a single value: `f(a)`. Includes operations like:
    /// - `Neg` (negation: `-a`)
    /// - `Sqrt`, `Square` (powers and roots)
    /// - `SinPi`, `CosPi` (trigonometric functions)
    /// - `Ln`, `Exp` (logarithmic and exponential)
    /// - `Recip` (reciprocal: `1/a`)
    ///
    /// Default: All built-in unary operators from `Symbol::unary_ops()`
    pub unary_ops: Vec<Symbol>,

    /// Symbols available for binary operations (Seft::C type).
    ///
    /// These combine two values: `f(a, b)`. Includes operations like:
    /// - `Add`, `Sub`, `Mul`, `Div` (arithmetic)
    /// - `Pow`, `Root`, `Log` (power functions and logarithms)
    ///
    /// Default: All built-in binary operators from `Symbol::binary_ops()`
    pub binary_ops: Vec<Symbol>,

    /// Optional override for RHS-only constant symbols.
    ///
    /// When set, RHS expressions use these symbols instead of `constants`.
    /// Useful for generating LHS with more symbols but keeping RHS simple.
    ///
    /// Default: `None` (use `constants` for both LHS and RHS)
    pub rhs_constants: Option<Vec<Symbol>>,

    /// Optional override for RHS-only unary operators.
    ///
    /// When set, RHS expressions use these operators instead of `unary_ops`.
    /// Example: allow Lambert W in LHS only, exclude from RHS constants.
    ///
    /// Default: `None` (use `unary_ops` for both LHS and RHS)
    pub rhs_unary_ops: Option<Vec<Symbol>>,

    /// Optional override for RHS-only binary operators.
    ///
    /// When set, RHS expressions use these operators instead of `binary_ops`.
    ///
    /// Default: `None` (use `binary_ops` for both LHS and RHS)
    pub rhs_binary_ops: Option<Vec<Symbol>>,

    /// Maximum usage count per symbol within a single expression.
    ///
    /// Maps each symbol to the maximum number of times it can appear.
    /// Useful for limiting redundancy (e.g., max 2 uses of `Pi`).
    /// Corresponds to the `-O` command-line option.
    ///
    /// Default: Empty (no limits)
    pub symbol_max_counts: HashMap<Symbol, u32>,

    /// Optional RHS-only symbol count limits.
    ///
    /// When set, applies different symbol count limits to RHS expressions.
    /// Corresponds to the `--O-RHS` command-line option.
    ///
    /// Default: `None` (use `symbol_max_counts` for both)
    pub rhs_symbol_max_counts: Option<HashMap<Symbol, u32>>,

    /// Minimum numeric type required for generated expressions.
    ///
    /// Filters expressions by the "sophistication" of numbers they produce:
    /// - `Integer`: Only integer results
    /// - `Rational`: Rational numbers (fractions)
    /// - `Algebraic`: Algebraic numbers (roots of polynomials)
    /// - `Transcendental`: Any real number (including π, e, trig)
    ///
    /// Lower values restrict output to simpler mathematical constructs.
    ///
    /// Default: `NumType::Transcendental` (accept all)
    pub min_num_type: NumType,

    /// Whether to generate LHS expressions containing `x`.
    ///
    /// Set to `false` if you only need constant RHS expressions.
    /// Can significantly reduce generation time when LHS is not needed.
    ///
    /// Default: `true`
    pub generate_lhs: bool,

    /// Whether to generate RHS constant expressions.
    ///
    /// Set to `false` if you only need LHS expressions.
    /// Useful for specific analysis tasks.
    ///
    /// Default: `true`
    pub generate_rhs: bool,

    /// User-defined constants for custom searches.
    ///
    /// These constants are available during expression evaluation,
    /// allowing searches involving domain-specific values.
    /// Defined via `-N` command-line option.
    ///
    /// Default: Empty
    pub user_constants: Vec<UserConstant>,

    /// User-defined functions for custom searches.
    ///
    /// Custom functions that can appear in generated expressions,
    /// extending the available operations beyond built-in symbols.
    /// Defined via `-F` command-line option.
    ///
    /// Default: Empty
    pub user_functions: Vec<UserFunction>,

    /// Enable diagnostic output for arithmetic pruning.
    ///
    /// When `true`, prints information about expressions that were
    /// discarded due to arithmetic errors (overflow, domain errors, etc.).
    /// Useful for debugging generation behavior.
    ///
    /// Default: `false`
    pub show_pruned_arith: bool,

    /// Symbol table with weights and display names.
    ///
    /// Provides complexity weights for each symbol and custom display
    /// names. Weights control how "expensive" each symbol is toward
    /// the complexity limit.
    ///
    /// Default: Empty table (uses built-in default weights)
    pub symbol_table: Arc<SymbolTable>,
}

/// Options for additional expression constraints
///
/// These constraints allow filtering expressions based on their numeric properties
/// or structural limits (like trig cycles or exponent types).
#[derive(Debug, Clone, Copy)]
pub struct ExpressionConstraintOptions {
    /// If true, power exponents must be rational (no transcendental exponents like x^pi)
    pub rational_exponents: bool,
    /// If true, trigonometric function arguments must be rational
    pub rational_trig_args: bool,
    /// Maximum number of trigonometric operations allowed in an expression
    pub max_trig_cycles: Option<u32>,
    /// Inherited numeric types for user-defined constants 0-15
    pub user_constant_types: [NumType; 16],
    /// Inherited numeric types for user-defined functions 0-15
    pub user_function_types: [NumType; 16],
}

impl Default for ExpressionConstraintOptions {
    fn default() -> Self {
        Self {
            rational_exponents: false,
            rational_trig_args: false,
            max_trig_cycles: None,
            user_constant_types: [NumType::Transcendental; 16],
            user_function_types: [NumType::Transcendental; 16],
        }
    }
}

/// Check if an expression respects the configured structural and numeric constraints.
///
/// This performs a symbolic walkthrough of the expression to verify that it
/// matches the requested properties (e.g., no transcendental exponents).
pub fn expression_respects_constraints(
    expression: &Expression,
    opts: ExpressionConstraintOptions,
) -> bool {
    #[derive(Clone, Copy)]
    struct ConstraintValue {
        has_x: bool,
        num_type: NumType,
    }

    let mut stack: Vec<ConstraintValue> = Vec::with_capacity(expression.len());
    let mut trig_ops: u32 = 0;

    for &sym in expression.symbols() {
        match sym.seft() {
            Seft::A => {
                let num_type = if let Some(idx) = sym.user_constant_index() {
                    opts.user_constant_types[idx as usize]
                } else {
                    sym.inherent_type()
                };
                stack.push(ConstraintValue {
                    has_x: sym == Symbol::X,
                    num_type,
                });
            }
            Seft::B => {
                let Some(arg) = stack.pop() else {
                    return false;
                };

                if matches!(sym, Symbol::SinPi | Symbol::CosPi | Symbol::TanPi) {
                    trig_ops = trig_ops.saturating_add(1);
                    if opts.rational_trig_args && (arg.has_x || arg.num_type < NumType::Rational) {
                        return false;
                    }
                }

                let num_type = match sym {
                    Symbol::Neg | Symbol::Square => arg.num_type,
                    Symbol::Recip => {
                        if arg.num_type >= NumType::Rational {
                            NumType::Rational
                        } else {
                            arg.num_type
                        }
                    }
                    Symbol::Sqrt => {
                        if arg.num_type >= NumType::Rational {
                            NumType::Algebraic
                        } else {
                            arg.num_type
                        }
                    }
                    Symbol::UserFunction0
                    | Symbol::UserFunction1
                    | Symbol::UserFunction2
                    | Symbol::UserFunction3
                    | Symbol::UserFunction4
                    | Symbol::UserFunction5
                    | Symbol::UserFunction6
                    | Symbol::UserFunction7
                    | Symbol::UserFunction8
                    | Symbol::UserFunction9
                    | Symbol::UserFunction10
                    | Symbol::UserFunction11
                    | Symbol::UserFunction12
                    | Symbol::UserFunction13
                    | Symbol::UserFunction14
                    | Symbol::UserFunction15 => {
                        let idx = sym.user_function_index().unwrap_or(0) as usize;
                        opts.user_function_types[idx]
                    }
                    _ => NumType::Transcendental,
                };

                stack.push(ConstraintValue {
                    has_x: arg.has_x,
                    num_type,
                });
            }
            Seft::C => {
                let Some(rhs) = stack.pop() else {
                    return false;
                };
                let Some(lhs) = stack.pop() else {
                    return false;
                };

                if opts.rational_exponents
                    && sym == Symbol::Pow
                    && (rhs.has_x || rhs.num_type < NumType::Rational)
                {
                    return false;
                }

                let num_type = match sym {
                    Symbol::Add | Symbol::Sub | Symbol::Mul => lhs.num_type.combine(rhs.num_type),
                    Symbol::Div => {
                        let combined = lhs.num_type.combine(rhs.num_type);
                        if combined == NumType::Integer {
                            NumType::Rational
                        } else {
                            combined
                        }
                    }
                    Symbol::Pow => {
                        if rhs.has_x {
                            NumType::Transcendental
                        } else if rhs.num_type == NumType::Integer {
                            lhs.num_type
                        } else if lhs.num_type >= NumType::Rational
                            && rhs.num_type >= NumType::Rational
                        {
                            NumType::Algebraic
                        } else {
                            NumType::Transcendental
                        }
                    }
                    Symbol::Root => NumType::Algebraic,
                    Symbol::Log | Symbol::Atan2 => NumType::Transcendental,
                    _ => NumType::Transcendental,
                };

                stack.push(ConstraintValue {
                    has_x: lhs.has_x || rhs.has_x,
                    num_type,
                });
            }
        }
    }

    if stack.len() != 1 {
        return false;
    }

    opts.max_trig_cycles
        .is_none_or(|max_cycles| trig_ops <= max_cycles)
}

impl Default for GenConfig {
    fn default() -> Self {
        Self {
            max_lhs_complexity: 128,
            max_rhs_complexity: 128,
            max_length: MAX_EXPR_LEN,
            constants: Symbol::constants().to_vec(),
            unary_ops: Symbol::unary_ops().to_vec(),
            binary_ops: Symbol::binary_ops().to_vec(),
            rhs_constants: None,
            rhs_unary_ops: None,
            rhs_binary_ops: None,
            symbol_max_counts: HashMap::new(),
            rhs_symbol_max_counts: None,
            min_num_type: NumType::Transcendental,
            generate_lhs: true,
            generate_rhs: true,
            user_constants: Vec::new(),
            user_functions: Vec::new(),
            show_pruned_arith: false,
            symbol_table: Arc::new(SymbolTable::new()),
        }
    }
}

/// Result of expression generation
pub struct GeneratedExprs {
    /// LHS expressions (contain x)
    pub lhs: Vec<EvaluatedExpr>,
    /// RHS expressions (constants only)
    pub rhs: Vec<EvaluatedExpr>,
}

/// Callbacks for streaming expression generation
///
/// Using callbacks instead of accumulation allows processing expressions
/// as they're generated, reducing memory from O(expressions) to O(depth).
pub struct StreamingCallbacks<'a> {
    /// Called for each RHS (constant-only) expression generated
    /// Return false to stop generation early
    pub on_rhs: &'a mut dyn FnMut(&EvaluatedExpr) -> bool,
    /// Called for each LHS (contains x) expression generated
    /// Return false to stop generation early
    pub on_lhs: &'a mut dyn FnMut(&EvaluatedExpr) -> bool,
}

/// Quantize a value to reduce floating-point noise
/// Key for LHS deduplication: (quantized value, quantized derivative)
pub type LhsKey = (i64, i64);

/// Uses ~8 significant digits for deduplication
#[inline]
pub fn quantize_value(v: f64) -> i64 {
    if !v.is_finite() || v.abs() > MAX_QUANTIZED_VALUE {
        // For very large values, use a different quantization to avoid overflow
        if v > MAX_QUANTIZED_VALUE {
            return i64::MAX - 1;
        } else if v < -MAX_QUANTIZED_VALUE {
            return i64::MIN + 1;
        }
        return i64::MAX;
    }
    // Scale to preserve ~8 significant digits (avoid overflow)
    (v * QUANTIZE_SCALE).round() as i64
}

/// Generate all valid expressions up to the configured limits
pub fn generate_all(config: &GenConfig, target: f64) -> GeneratedExprs {
    generate_all_with_context(
        config,
        target,
        &EvalContext::from_slices(&config.user_constants, &config.user_functions),
    )
}

/// Generate all valid expressions up to the configured limits using an explicit evaluation context.
pub fn generate_all_with_context(
    config: &GenConfig,
    target: f64,
    eval_context: &EvalContext<'_>,
) -> GeneratedExprs {
    let mut lhs_raw = Vec::new();
    let mut rhs_raw = Vec::new();

    if config.generate_lhs && config.generate_rhs && has_rhs_symbol_overrides(config) {
        // LHS pass with base symbol set.
        let mut lhs_config = config.clone();
        lhs_config.generate_lhs = true;
        lhs_config.generate_rhs = false;
        generate_recursive(
            &lhs_config,
            target,
            *eval_context,
            &mut Expression::new(),
            0,
            &mut lhs_raw,
            &mut rhs_raw,
        );

        // RHS pass with RHS-specific symbol overrides.
        let rhs_config = rhs_only_config(config);
        generate_recursive(
            &rhs_config,
            target,
            *eval_context,
            &mut Expression::new(),
            0,
            &mut lhs_raw,
            &mut rhs_raw,
        );
    } else {
        // Generate expressions for each possible "form" (sequence of stack effects)
        generate_recursive(
            config,
            target,
            *eval_context,
            &mut Expression::new(),
            0, // current stack depth
            &mut lhs_raw,
            &mut rhs_raw,
        );
    }

    // Deduplicate RHS by value, keeping simplest expression for each value
    let mut rhs_map: HashMap<i64, EvaluatedExpr> = HashMap::new();
    for expr in rhs_raw {
        let key = quantize_value(expr.value);
        rhs_map
            .entry(key)
            .and_modify(|existing| {
                if expr.expr.complexity() < existing.expr.complexity() {
                    *existing = expr.clone();
                }
            })
            .or_insert(expr);
    }

    // Deduplicate LHS by (value, derivative), keeping simplest expression
    let mut lhs_map: HashMap<LhsKey, EvaluatedExpr> = HashMap::new();
    for expr in lhs_raw {
        let key = (quantize_value(expr.value), quantize_value(expr.derivative));
        lhs_map
            .entry(key)
            .and_modify(|existing| {
                if expr.expr.complexity() < existing.expr.complexity() {
                    *existing = expr.clone();
                }
            })
            .or_insert(expr);
    }

    GeneratedExprs {
        lhs: lhs_map.into_values().collect(),
        rhs: rhs_map.into_values().collect(),
    }
}

/// Generate expressions with an early-abort limit on total count.
///
/// Returns `Some(expressions)` if generation completed within the limit,
/// or `None` if the limit was exceeded (caller should use streaming mode instead).
///
/// This is a safety mechanism to prevent OOM from unexpectedly large generation
/// at high complexity levels. The limit check happens during generation, not after.
///
/// # Arguments
///
/// * `config` - Generation configuration (complexity limits, symbols)
/// * `target` - Target value for evaluation
/// * `max_expressions` - Maximum total expressions (LHS + RHS) before aborting
///
/// # Returns
///
/// * `Some(GeneratedExprs)` - if generation completed within limit
/// * `None` - if the limit was exceeded during generation
pub fn generate_all_with_limit(
    config: &GenConfig,
    target: f64,
    max_expressions: usize,
) -> Option<GeneratedExprs> {
    generate_all_with_limit_and_context(
        config,
        target,
        &EvalContext::from_slices(&config.user_constants, &config.user_functions),
        max_expressions,
    )
}

/// Generate expressions with an early-abort limit using an explicit evaluation context.
pub fn generate_all_with_limit_and_context(
    config: &GenConfig,
    target: f64,
    eval_context: &EvalContext<'_>,
    max_expressions: usize,
) -> Option<GeneratedExprs> {
    use std::sync::atomic::{AtomicUsize, Ordering};
    use std::sync::Arc;

    let count = Arc::new(AtomicUsize::new(0));
    let limit = max_expressions;

    // Collect expressions if within limit
    let mut lhs_raw = Vec::new();
    let mut rhs_raw = Vec::new();

    // Callback that counts expressions and stops when limit is hit
    let mut callbacks = StreamingCallbacks {
        on_lhs: &mut |expr| {
            let current = count.fetch_add(1, Ordering::Relaxed) + 1;
            if current > limit {
                return false; // Abort generation
            }
            lhs_raw.push(expr.clone());
            true
        },
        on_rhs: &mut |expr| {
            let current = count.fetch_add(1, Ordering::Relaxed) + 1;
            if current > limit {
                return false; // Abort generation
            }
            rhs_raw.push(expr.clone());
            true
        },
    };

    generate_streaming_with_context(config, target, eval_context, &mut callbacks);

    // Check if we exceeded the limit
    let final_count = count.load(Ordering::Relaxed);
    if final_count > limit {
        return None;
    }

    // Deduplicate (same logic as generate_all)
    let mut rhs_map: HashMap<i64, EvaluatedExpr> = HashMap::new();
    for expr in rhs_raw {
        let key = quantize_value(expr.value);
        rhs_map
            .entry(key)
            .and_modify(|existing| {
                if expr.expr.complexity() < existing.expr.complexity() {
                    *existing = expr.clone();
                }
            })
            .or_insert(expr);
    }

    let mut lhs_map: HashMap<LhsKey, EvaluatedExpr> = HashMap::new();
    for expr in lhs_raw {
        let key = (quantize_value(expr.value), quantize_value(expr.derivative));
        lhs_map
            .entry(key)
            .and_modify(|existing| {
                if expr.expr.complexity() < existing.expr.complexity() {
                    *existing = expr.clone();
                }
            })
            .or_insert(expr);
    }

    Some(GeneratedExprs {
        lhs: lhs_map.into_values().collect(),
        rhs: rhs_map.into_values().collect(),
    })
}

/// Generate expressions with streaming callbacks for memory-efficient processing
///
/// This function is the foundation of the streaming architecture. Instead of
/// accumulating all expressions in memory, it calls the provided callbacks
/// for each generated expression, allowing immediate processing.
///
/// # Memory Efficiency
///
/// - Traditional: O(expressions) memory - all expressions stored before processing
/// - Streaming: O(depth) memory - only the recursion stack is stored
///
/// # Early Exit
///
/// The callbacks can return `false` to signal early termination. This is useful
/// when good matches have been found and additional expressions aren't needed.
///
/// # Deduplication
///
/// The caller is responsible for deduplication if needed. This allows flexibility
/// in deduplication strategies (e.g., per-batch, per-tier, etc.).
///
/// # Example
///
/// ```no_run
/// use ries_rs::gen::{GenConfig, StreamingCallbacks, generate_streaming};
/// let config = GenConfig::default();
/// let target = 2.5_f64;
/// let mut rhs_count = 0;
/// let mut lhs_count = 0;
/// let mut callbacks = StreamingCallbacks {
///     on_rhs: &mut |_expr| {
///         rhs_count += 1;
///         true // continue generation
///     },
///     on_lhs: &mut |_expr| {
///         lhs_count += 1;
///         true // continue generation
///     },
/// };
/// generate_streaming(&config, target, &mut callbacks);
/// ```
pub fn generate_streaming(config: &GenConfig, target: f64, callbacks: &mut StreamingCallbacks) {
    generate_streaming_with_context(
        config,
        target,
        &EvalContext::from_slices(&config.user_constants, &config.user_functions),
        callbacks,
    );
}

/// Generate expressions with streaming callbacks using an explicit evaluation context.
pub fn generate_streaming_with_context(
    config: &GenConfig,
    target: f64,
    eval_context: &EvalContext<'_>,
    callbacks: &mut StreamingCallbacks,
) {
    if config.generate_lhs && config.generate_rhs && has_rhs_symbol_overrides(config) {
        let mut lhs_config = config.clone();
        lhs_config.generate_lhs = true;
        lhs_config.generate_rhs = false;
        if !generate_recursive_streaming(
            &lhs_config,
            target,
            *eval_context,
            &mut Expression::new(),
            0,
            callbacks,
        ) {
            return;
        }

        let rhs_config = rhs_only_config(config);
        generate_recursive_streaming(
            &rhs_config,
            target,
            *eval_context,
            &mut Expression::new(),
            0,
            callbacks,
        );
    } else {
        generate_recursive_streaming(
            config,
            target,
            *eval_context,
            &mut Expression::new(),
            0, // current stack depth
            callbacks,
        );
    }
}

#[inline]
fn has_rhs_symbol_overrides(config: &GenConfig) -> bool {
    config.rhs_constants.is_some()
        || config.rhs_unary_ops.is_some()
        || config.rhs_binary_ops.is_some()
        || config.rhs_symbol_max_counts.is_some()
}

/// Check if an evaluated expression meets generation criteria
///
/// This shared helper function is used by both batch and streaming generation
/// to validate expressions before including them in results.
#[inline]
fn should_include_expression(
    result: &crate::eval::EvalResult,
    config: &GenConfig,
    complexity: u32,
    contains_x: bool,
) -> bool {
    result.value.is_finite()
        && result.value.abs() <= MAX_GENERATED_VALUE
        && result.num_type >= config.min_num_type
        && if contains_x {
            config.generate_lhs && complexity <= config.max_lhs_complexity
        } else {
            config.generate_rhs && complexity <= config.max_rhs_complexity
        }
}

/// Calculate the appropriate complexity limit based on whether expression contains x
///
/// For expressions containing x, uses LHS limit.
/// For RHS-only paths, uses RHS limit.
/// For paths that might still add x, uses the max of both limits.
#[inline]
fn get_max_complexity(config: &GenConfig, contains_x: bool) -> u32 {
    if contains_x {
        config.max_lhs_complexity
    } else {
        // For RHS-only paths, use RHS limit
        // For paths that might still add x, use the max of both
        std::cmp::max(config.max_lhs_complexity, config.max_rhs_complexity)
    }
}

fn rhs_only_config(config: &GenConfig) -> GenConfig {
    let mut rhs_config = config.clone();
    rhs_config.generate_lhs = false;
    rhs_config.generate_rhs = true;
    if let Some(constants) = &config.rhs_constants {
        rhs_config.constants = constants.clone();
    }
    if let Some(unary_ops) = &config.rhs_unary_ops {
        rhs_config.unary_ops = unary_ops.clone();
    }
    if let Some(binary_ops) = &config.rhs_binary_ops {
        rhs_config.binary_ops = binary_ops.clone();
    }
    if let Some(rhs_symbol_max_counts) = &config.rhs_symbol_max_counts {
        rhs_config.symbol_max_counts = rhs_symbol_max_counts.clone();
    }
    rhs_config
}

#[inline]
fn exceeds_symbol_limit(config: &GenConfig, current: &Expression, sym: Symbol) -> bool {
    config
        .symbol_max_counts
        .get(&sym)
        .is_some_and(|&max| current.count_symbol(sym) >= max)
}

/// Recursively generate expressions with streaming callbacks
///
/// This is the core streaming generation function. It mirrors `generate_recursive`
/// but calls callbacks instead of accumulating expressions.
fn generate_recursive_streaming(
    config: &GenConfig,
    target: f64,
    eval_context: EvalContext<'_>,
    current: &mut Expression,
    stack_depth: usize,
    callbacks: &mut StreamingCallbacks,
) -> bool {
    // Check if we have a complete expression
    if stack_depth == 1 && !current.is_empty() {
        // Try to evaluate it with user constants and functions support
        match evaluate_fast_with_context(current, target, &eval_context) {
            Ok(result) => {
                // Use shared validation helper
                if should_include_expression(
                    &result,
                    config,
                    current.complexity(),
                    current.contains_x(),
                ) {
                    let expr = current.clone();
                    let eval_expr =
                        EvaluatedExpr::new(expr, result.value, result.derivative, result.num_type);

                    // Call the appropriate callback; return false if it signals stop
                    let should_continue = if current.contains_x() {
                        (callbacks.on_lhs)(&eval_expr)
                    } else {
                        (callbacks.on_rhs)(&eval_expr)
                    };
                    if !should_continue {
                        return false;
                    }
                }
            }
            Err(e) => {
                // Expression was pruned due to arithmetic error
                if config.show_pruned_arith {
                    eprintln!(
                        "  [pruned arith] expression=\"{}\" reason={:?}",
                        current.to_postfix(),
                        e
                    );
                }
            }
        }
    }

    // Check limits before recursing
    if current.len() >= config.max_length {
        return true;
    }

    // Use shared helper for complexity limit calculation
    let max_complexity = get_max_complexity(config, current.contains_x());

    if current.complexity() >= max_complexity {
        return true;
    }

    // Calculate minimum additional complexity needed to complete expression
    let min_remaining = min_complexity_to_complete(stack_depth, config);
    if current.complexity() + min_remaining > max_complexity {
        return true;
    }

    // Try adding each possible symbol

    // Constants (Seft::A) - always increase stack by 1
    for &sym in &config.constants {
        let sym_weight = config.symbol_table.weight(sym);
        if current.complexity() + sym_weight > max_complexity {
            continue;
        }
        if exceeds_symbol_limit(config, current, sym) {
            continue;
        }

        // Skip x if we only want RHS
        if sym == Symbol::X && !config.generate_lhs {
            continue;
        }

        current.push_with_table(sym, &config.symbol_table);
        if !generate_recursive_streaming(
            config,
            target,
            eval_context,
            current,
            stack_depth + 1,
            callbacks,
        ) {
            current.pop_with_table(&config.symbol_table);
            return false;
        }
        current.pop_with_table(&config.symbol_table);
    }

    // Also add x for LHS generation
    if config.generate_lhs && !config.constants.contains(&Symbol::X) {
        let sym = Symbol::X;
        let sym_weight = config.symbol_table.weight(sym);
        if current.complexity() + sym_weight <= max_complexity
            && !exceeds_symbol_limit(config, current, sym)
        {
            current.push_with_table(sym, &config.symbol_table);
            if !generate_recursive_streaming(
                config,
                target,
                eval_context,
                current,
                stack_depth + 1,
                callbacks,
            ) {
                current.pop_with_table(&config.symbol_table);
                return false;
            }
            current.pop_with_table(&config.symbol_table);
        }
    }

    // Unary operators (Seft::B) - need at least 1 on stack
    if stack_depth >= 1 {
        for &sym in &config.unary_ops {
            let sym_weight = config.symbol_table.weight(sym);
            if current.complexity() + sym_weight > max_complexity {
                continue;
            }
            if exceeds_symbol_limit(config, current, sym) {
                continue;
            }

            // Apply pruning rules
            if should_prune_unary(current, sym) {
                continue;
            }

            current.push_with_table(sym, &config.symbol_table);
            if !generate_recursive_streaming(
                config,
                target,
                eval_context,
                current,
                stack_depth,
                callbacks,
            ) {
                current.pop_with_table(&config.symbol_table);
                return false;
            }
            current.pop_with_table(&config.symbol_table);
        }
    }

    // Binary operators (Seft::C) - need at least 2 on stack
    if stack_depth >= 2 {
        for &sym in &config.binary_ops {
            let sym_weight = config.symbol_table.weight(sym);
            if current.complexity() + sym_weight > max_complexity {
                continue;
            }
            if exceeds_symbol_limit(config, current, sym) {
                continue;
            }

            // Apply pruning rules
            if should_prune_binary(current, sym) {
                continue;
            }

            current.push_with_table(sym, &config.symbol_table);
            if !generate_recursive_streaming(
                config,
                target,
                eval_context,
                current,
                stack_depth - 1,
                callbacks,
            ) {
                current.pop_with_table(&config.symbol_table);
                return false;
            }
            current.pop_with_table(&config.symbol_table);
        }
    }

    true
}

/// Recursively generate expressions
fn generate_recursive(
    config: &GenConfig,
    target: f64,
    eval_context: EvalContext<'_>,
    current: &mut Expression,
    stack_depth: usize,
    lhs_out: &mut Vec<EvaluatedExpr>,
    rhs_out: &mut Vec<EvaluatedExpr>,
) {
    // Check if we have a complete expression
    if stack_depth == 1 && !current.is_empty() {
        // Try to evaluate it with user constants and functions support
        match evaluate_fast_with_context(current, target, &eval_context) {
            Ok(result) => {
                // Use shared validation helper
                if should_include_expression(
                    &result,
                    config,
                    current.complexity(),
                    current.contains_x(),
                ) {
                    let expr = current.clone();
                    let eval_expr =
                        EvaluatedExpr::new(expr, result.value, result.derivative, result.num_type);

                    // Keep all LHS expressions; derivative≈0 cases handled in search
                    if current.contains_x() {
                        lhs_out.push(eval_expr);
                    } else {
                        rhs_out.push(eval_expr);
                    }
                }
            }
            Err(e) => {
                // Expression was pruned due to arithmetic error
                if config.show_pruned_arith {
                    eprintln!(
                        "  [pruned arith] expression=\"{}\" reason={:?}",
                        current.to_postfix(),
                        e
                    );
                }
            }
        }
    }

    // Check limits before recursing
    if current.len() >= config.max_length {
        return;
    }

    // Use shared helper for complexity limit calculation
    let max_complexity = get_max_complexity(config, current.contains_x());

    if current.complexity() >= max_complexity {
        return;
    }

    // Calculate minimum additional complexity needed to complete expression
    let min_remaining = min_complexity_to_complete(stack_depth, config);
    if current.complexity() + min_remaining > max_complexity {
        return;
    }

    // Try adding each possible symbol

    // Constants (Seft::A) - always increase stack by 1
    for &sym in &config.constants {
        let sym_weight = config.symbol_table.weight(sym);
        if current.complexity() + sym_weight > max_complexity {
            continue;
        }
        if exceeds_symbol_limit(config, current, sym) {
            continue;
        }

        // Skip x if we only want RHS
        if sym == Symbol::X && !config.generate_lhs {
            continue;
        }

        current.push_with_table(sym, &config.symbol_table);
        generate_recursive(
            config,
            target,
            eval_context,
            current,
            stack_depth + 1,
            lhs_out,
            rhs_out,
        );
        current.pop_with_table(&config.symbol_table);
    }

    // Also add x for LHS generation
    if config.generate_lhs && !config.constants.contains(&Symbol::X) {
        let sym = Symbol::X;
        let sym_weight = config.symbol_table.weight(sym);
        if current.complexity() + sym_weight <= max_complexity
            && !exceeds_symbol_limit(config, current, sym)
        {
            current.push_with_table(sym, &config.symbol_table);
            generate_recursive(
                config,
                target,
                eval_context,
                current,
                stack_depth + 1,
                lhs_out,
                rhs_out,
            );
            current.pop_with_table(&config.symbol_table);
        }
    }

    // Unary operators (Seft::B) - need at least 1 on stack
    if stack_depth >= 1 {
        for &sym in &config.unary_ops {
            let sym_weight = config.symbol_table.weight(sym);
            if current.complexity() + sym_weight > max_complexity {
                continue;
            }
            if exceeds_symbol_limit(config, current, sym) {
                continue;
            }

            // Apply pruning rules
            if should_prune_unary(current, sym) {
                continue;
            }

            current.push_with_table(sym, &config.symbol_table);
            generate_recursive(
                config,
                target,
                eval_context,
                current,
                stack_depth,
                lhs_out,
                rhs_out,
            );
            current.pop_with_table(&config.symbol_table);
        }
    }

    // Binary operators (Seft::C) - need at least 2 on stack
    if stack_depth >= 2 {
        for &sym in &config.binary_ops {
            let sym_weight = config.symbol_table.weight(sym);
            if current.complexity() + sym_weight > max_complexity {
                continue;
            }
            if exceeds_symbol_limit(config, current, sym) {
                continue;
            }

            // Apply pruning rules
            if should_prune_binary(current, sym) {
                continue;
            }

            current.push_with_table(sym, &config.symbol_table);
            generate_recursive(
                config,
                target,
                eval_context,
                current,
                stack_depth - 1,
                lhs_out,
                rhs_out,
            );
            current.pop_with_table(&config.symbol_table);
        }
    }
}

/// Calculate minimum complexity needed to reduce stack to depth 1
fn min_complexity_to_complete(stack_depth: usize, config: &GenConfig) -> u32 {
    if stack_depth <= 1 {
        return 0;
    }

    // Need (stack_depth - 1) binary operators to reduce to 1
    let min_binary_weight = config
        .binary_ops
        .iter()
        .map(|s| config.symbol_table.weight(*s))
        .min()
        .unwrap_or(4);

    ((stack_depth - 1) as u32) * min_binary_weight
}

/// Pruning rules for unary operators to avoid redundant expressions
fn should_prune_unary(expr: &Expression, sym: Symbol) -> bool {
    let symbols = expr.symbols();
    if symbols.is_empty() {
        return false;
    }

    let last = symbols[symbols.len() - 1];

    use Symbol::*;

    match (last, sym) {
        // Double negation: --a = a
        (Neg, Neg) => true,
        // Double reciprocal: 1/(1/a) = a
        (Recip, Recip) => true,
        // sqrt(a^2) = |a| (we don't handle absolute value)
        (Square, Sqrt) => true,
        // (sqrt(a))^2 = a
        (Sqrt, Square) => true,
        // ln(e^a) = a
        (Exp, Ln) => true,
        // e^(ln(a)) = a
        (Ln, Exp) => true,

        // Additional pruning rules for cleaner output:
        // 1/sqrt(a) and 1/a^2 are rare, prefer a^-0.5 or a^-2 notation
        (Sqrt, Recip) => true,
        (Square, Recip) => true,
        // 1/ln(a) is rarely useful
        (Ln, Recip) => true,
        // Double square: (a^2)^2 = a^4, use power directly
        (Square, Square) => true,
        // Double sqrt: sqrt(sqrt(a)) = a^0.25, use power directly
        (Sqrt, Sqrt) => true,
        // Negation after subtraction is redundant with addition
        // e.g., -(a-b) = b-a which we could express directly
        (Sub, Neg) => true,

        // ===== ENHANCED PRUNING RULES =====
        // Trig reduction: asin(sin(pi*x)/pi) = x, similar for acos
        // These are rarely useful and add many redundant expressions
        (SinPi, SinPi) => true,
        (CosPi, CosPi) => true,
        // asin after sinpi is identity (mod periodicity)
        // acos after cospi is identity (mod periodicity)
        // These patterns are captured by double application above

        // Exp grows too fast - double exp is almost never useful
        (Exp, Exp) => true,

        // LambertW after exp: W(e^a) = a, so W(e^x) = x
        (Exp, LambertW) => true,

        // LambertW on small values often doesn't converge usefully
        // W of reciprocal is rarely needed
        (Recip, LambertW) => true,

        _ => false,
    }
}

/// Pruning rules for binary operators
fn should_prune_binary(expr: &Expression, sym: Symbol) -> bool {
    let symbols = expr.symbols();
    if symbols.len() < 2 {
        return false;
    }

    let last = symbols[symbols.len() - 1];
    let prev = symbols[symbols.len() - 2];

    use Symbol::*;

    match sym {
        // a - a = 0 (if both operands are identical)
        Sub if is_same_subexpr(symbols, 2) => true,
        // x - x = 0 (trivial - always 0)
        Sub if last == X && prev == X => true,

        // a / a = 1 (degenerate if a contains x)
        Div if is_same_subexpr(symbols, 2) => true,
        // x / x = 1 (trivial identity)
        Div if last == X && prev == X => true,
        // Division by 1: a/1 = a (useless)
        Div if last == One => true,

        // Prefer a*2 over a+a
        Add if is_same_subexpr(symbols, 2) => true,
        // x + (-x) = 0 - check for negated x
        Add if last == Neg
            && symbols.len() >= 3
            && symbols[symbols.len() - 2] == X
            && prev == X =>
        {
            true
        }

        // 1^b = 1 (degenerate - always equals 1 regardless of b)
        // This catches 1^x, 1^(anything)
        Pow if prev == One => true,
        // a^1 = a (useless)
        Pow if last == One => true,

        // x * 1 = x, 1 * x = x
        Mul if last == One || prev == One => true,

        // a"/1 = a^(1/1) = a (1st root is identity)
        // But more importantly: 1"/x = 1^(1/x) = 1 (degenerate)
        Root if prev == One => true,
        // x"/1 means 1^(1/x) = 1 (degenerate)
        Root if last == One => true,
        // 2nd root is just sqrt, prefer using sqrt
        Root if last == Two => true,

        // log_x(x) = 1 (trivial identity)
        Log if last == X && prev == X => true,
        // log_1(anything) is undefined/infinite, log_a(1) = 0
        Log if prev == One || last == One => true,
        // log_e(a) = ln(a) - prefer ln notation
        Log if prev == E => true,

        // Ordering: prefer 2+3 over 3+2 for commutative ops
        Add | Mul if prev > last && is_constant(last) && is_constant(prev) => true,

        _ => false,
    }
}

/// Check if the last n stack items are identical subexpressions
///
/// This uses a stack-based approach to identify subexpression boundaries.
/// For postfix notation, we track the stack depth to find where each
/// subexpression starts.
fn is_same_subexpr(symbols: &[Symbol], n: usize) -> bool {
    if symbols.len() < n * 2 || n < 2 {
        return false;
    }

    // Find the boundaries of the last n subexpressions on the stack
    // We need to trace backwards through the postfix to find where each
    // complete subexpression starts

    let mut stack_depths: Vec<usize> = Vec::with_capacity(symbols.len() + 1);
    stack_depths.push(0); // Initial depth

    for &sym in symbols {
        let prev_depth = *stack_depths.last().unwrap();
        let new_depth = match sym.seft() {
            Seft::A => prev_depth + 1,
            Seft::B => prev_depth,     // pop 1, push 1
            Seft::C => prev_depth - 1, // pop 2, push 1
        };
        stack_depths.push(new_depth);
    }

    let final_depth = *stack_depths.last().unwrap();
    if final_depth < n {
        return false;
    }

    // Find where each of the last n subexpressions starts
    let mut subexpr_starts: Vec<usize> = Vec::with_capacity(n);
    let mut target_depth = final_depth;

    for i in (0..symbols.len()).rev() {
        if stack_depths[i] == target_depth && stack_depths[i + 1] > target_depth {
            subexpr_starts.push(i);
            target_depth -= 1;
            if subexpr_starts.len() == n {
                break;
            }
        }
    }

    if subexpr_starts.len() != n {
        return false;
    }

    // Check if all n subexpressions are identical
    // For simplicity with n=2, compare the two subexpressions
    if n == 2 && subexpr_starts.len() == 2 {
        let start1 = subexpr_starts[1]; // Earlier subexpression
        let start2 = subexpr_starts[0]; // Later subexpression
        let end1 = start2; // End of first is start of second
        let end2 = symbols.len(); // End of second is end of expression

        // Compare the symbol slices
        if end1 - start1 == end2 - start2 {
            return symbols[start1..end1] == symbols[start2..end2];
        }
    }

    false
}

/// Check if a symbol is a constant (no x)
fn is_constant(sym: Symbol) -> bool {
    matches!(sym.seft(), Seft::A) && sym != Symbol::X
}

/// Generate expressions in parallel using Rayon
#[cfg(feature = "parallel")]
pub fn generate_all_parallel(config: &GenConfig, target: f64) -> GeneratedExprs {
    generate_all_parallel_with_context(
        config,
        target,
        &EvalContext::from_slices(&config.user_constants, &config.user_functions),
    )
}

/// Generate expressions in parallel using Rayon with an explicit evaluation context.
#[cfg(feature = "parallel")]
pub fn generate_all_parallel_with_context(
    config: &GenConfig,
    target: f64,
    eval_context: &EvalContext<'_>,
) -> GeneratedExprs {
    use rayon::prelude::*;

    // Parallel path currently assumes shared LHS/RHS symbol sets.
    if has_rhs_symbol_overrides(config) {
        return generate_all_with_context(config, target, eval_context);
    }

    // Generate valid prefixes of length 1 and 2 to create smaller,
    // more evenly distributed tasks for Rayon to schedule.
    let mut prefixes: Vec<(Expression, usize)> = Vec::new();
    let mut immediate_results_lhs = Vec::new();
    let mut immediate_results_rhs = Vec::new();

    let first_symbols: Vec<Symbol> = config
        .constants
        .iter()
        .copied()
        .chain(
            if config.generate_lhs && !config.constants.contains(&Symbol::X) {
                Some(Symbol::X)
            } else {
                None
            },
        )
        .filter(|&sym| {
            config
                .symbol_max_counts
                .get(&sym)
                .is_none_or(|&max| max > 0)
        })
        .collect();

    for sym1 in first_symbols {
        let mut expr1 = Expression::new();
        expr1.push_with_table(sym1, &config.symbol_table);

        let max_complexity = if expr1.contains_x() {
            config.max_lhs_complexity
        } else {
            std::cmp::max(config.max_lhs_complexity, config.max_rhs_complexity)
        };

        if expr1.complexity() > max_complexity {
            continue;
        }

        // 1. Evaluate length-1 prefix (simulate top of generate_recursive)
        if let Ok(result) = evaluate_fast_with_context(&expr1, target, eval_context) {
            if result.value.is_finite()
                && result.value.abs() <= MAX_GENERATED_VALUE
                && result.num_type >= config.min_num_type
            {
                let eval_expr = EvaluatedExpr::new(
                    expr1.clone(),
                    result.value,
                    result.derivative,
                    result.num_type,
                );

                if expr1.contains_x() {
                    if config.generate_lhs && expr1.complexity() <= config.max_lhs_complexity {
                        immediate_results_lhs.push(eval_expr);
                    }
                } else if config.generate_rhs && expr1.complexity() <= config.max_rhs_complexity {
                    immediate_results_rhs.push(eval_expr);
                }
            }
        }

        if expr1.len() >= config.max_length {
            continue;
        }

        // 2. Add next symbols (simulate bottom of generate_recursive)

        // Constants (+1 stack)
        let mut next_constants = config.constants.clone();
        if config.generate_lhs && !next_constants.contains(&Symbol::X) {
            next_constants.push(Symbol::X);
        }

        for &sym2 in &next_constants {
            let sym2_weight = config.symbol_table.weight(sym2);
            let next_max = if expr1.contains_x() || sym2 == Symbol::X {
                config.max_lhs_complexity
            } else {
                std::cmp::max(config.max_lhs_complexity, config.max_rhs_complexity)
            };

            if expr1.complexity() + sym2_weight <= next_max
                && !exceeds_symbol_limit(config, &expr1, sym2)
            {
                let mut expr2 = expr1.clone();
                expr2.push_with_table(sym2, &config.symbol_table);
                // Min complexity check: for stack depth 2, we need at least 1 binary op
                let min_remaining = min_complexity_to_complete(2, config);
                if expr2.complexity() + min_remaining <= next_max {
                    prefixes.push((expr2, 2));
                }
            }
        }

        // Unary ops (+0 stack)
        for &sym2 in &config.unary_ops {
            let sym2_weight = config.symbol_table.weight(sym2);
            if expr1.complexity() + sym2_weight <= max_complexity
                && !exceeds_symbol_limit(config, &expr1, sym2)
                && !should_prune_unary(&expr1, sym2)
            {
                let mut expr2 = expr1.clone();
                expr2.push_with_table(sym2, &config.symbol_table);
                let min_remaining = min_complexity_to_complete(1, config);
                if expr2.complexity() + min_remaining <= max_complexity {
                    prefixes.push((expr2, 1));
                }
            }
        }
    }

    let results: Vec<(Vec<EvaluatedExpr>, Vec<EvaluatedExpr>)> = prefixes
        .into_par_iter()
        .map(|(mut expr, depth)| {
            let mut lhs = Vec::new();
            let mut rhs = Vec::new();
            generate_recursive(
                config,
                target,
                *eval_context,
                &mut expr,
                depth,
                &mut lhs,
                &mut rhs,
            );
            (lhs, rhs)
        })
        .collect();

    // Merge results
    let mut lhs_raw = immediate_results_lhs;
    let mut rhs_raw = immediate_results_rhs;
    for (lhs, rhs) in results {
        lhs_raw.extend(lhs);
        rhs_raw.extend(rhs);
    }

    // Deduplicate RHS by value, keeping simplest expression for each value
    let mut rhs_map: HashMap<i64, EvaluatedExpr> = HashMap::new();
    for expr in rhs_raw {
        let key = quantize_value(expr.value);
        rhs_map
            .entry(key)
            .and_modify(|existing| {
                if expr.expr.complexity() < existing.expr.complexity() {
                    *existing = expr.clone();
                }
            })
            .or_insert(expr);
    }

    // Deduplicate LHS by (value, derivative), keeping simplest expression
    let mut lhs_map: HashMap<LhsKey, EvaluatedExpr> = HashMap::new();
    for expr in lhs_raw {
        let key = (quantize_value(expr.value), quantize_value(expr.derivative));
        lhs_map
            .entry(key)
            .and_modify(|existing| {
                if expr.expr.complexity() < existing.expr.complexity() {
                    *existing = expr.clone();
                }
            })
            .or_insert(expr);
    }

    GeneratedExprs {
        lhs: lhs_map.into_values().collect(),
        rhs: rhs_map.into_values().collect(),
    }
}

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

    /// Create a fast test config with limited complexity and operators
    fn fast_test_config() -> GenConfig {
        GenConfig {
            max_lhs_complexity: 20,
            max_rhs_complexity: 20,
            max_length: 8,
            constants: vec![
                Symbol::One,
                Symbol::Two,
                Symbol::Three,
                Symbol::Four,
                Symbol::Five,
                Symbol::Pi,
                Symbol::E,
            ],
            unary_ops: vec![Symbol::Neg, Symbol::Recip, Symbol::Square, Symbol::Sqrt],
            binary_ops: vec![Symbol::Add, Symbol::Sub, Symbol::Mul, Symbol::Div],
            rhs_constants: None,
            rhs_unary_ops: None,
            rhs_binary_ops: None,
            symbol_max_counts: HashMap::new(),
            rhs_symbol_max_counts: None,
            min_num_type: NumType::Transcendental,
            generate_lhs: true,
            generate_rhs: true,
            user_constants: Vec::new(),
            user_functions: Vec::new(),
            show_pruned_arith: false,
            symbol_table: Arc::new(SymbolTable::new()),
        }
    }

    #[test]
    fn test_generate_simple() {
        let mut config = fast_test_config();
        config.generate_lhs = false; // Only RHS for simpler test

        let result = generate_all(&config, 1.0);

        // Should have some RHS expressions
        assert!(!result.rhs.is_empty());

        // All should be valid (evaluate without error)
        for expr in &result.rhs {
            assert!(!expr.expr.contains_x());
        }
    }

    #[test]
    fn test_generate_lhs() {
        let mut config = fast_test_config();
        config.generate_rhs = false;

        let result = generate_all(&config, 2.0);

        // Should have LHS expressions containing x
        assert!(!result.lhs.is_empty());
        for expr in &result.lhs {
            assert!(expr.expr.contains_x());
        }
    }

    #[test]
    fn test_complexity_limit() {
        let config = fast_test_config();

        let result = generate_all(&config, 1.0);

        for expr in &result.rhs {
            assert!(expr.expr.complexity() <= config.max_rhs_complexity);
        }
        for expr in &result.lhs {
            assert!(expr.expr.complexity() <= config.max_lhs_complexity);
        }
    }

    #[test]
    fn test_generate_all_with_limit_aborts_when_exceeded() {
        // Config with high complexity that will generate many expressions.
        // With new calibrated weights, even moderate complexity can generate 100+ expressions.
        let mut config = fast_test_config();
        config.max_lhs_complexity = 30;
        config.max_rhs_complexity = 30;

        // First, check how many expressions would be generated without limit.
        let unlimited = generate_all(&config, 2.5);
        let total_unlimited = unlimited.lhs.len() + unlimited.rhs.len();

        // The test only makes sense if we'd generate more than a handful.
        assert!(
            total_unlimited > 10,
            "Test config should generate >10 expressions"
        );

        // Now test with a limit less than the actual count — should return None.
        let limit = total_unlimited / 2; // Set limit to half of what would be generated
        let result = generate_all_with_limit(&config, 2.5, limit);

        assert!(
            result.is_none(),
            "generate_all_with_limit should return None when limit ({}) is exceeded (actual: {})",
            limit,
            total_unlimited
        );
    }

    #[test]
    fn test_generate_all_with_limit_succeeds_when_within_limit() {
        // Same config but with a generous limit that won't be hit.
        let mut config = fast_test_config();
        config.max_lhs_complexity = 30;
        config.max_rhs_complexity = 30;

        // Set limit much higher than expected expression count.
        let result = generate_all_with_limit(&config, 2.5, 10_000);

        assert!(
            result.is_some(),
            "generate_all_with_limit should return Some when limit is not exceeded"
        );

        let generated = result.unwrap();
        // Should have generated some expressions.
        assert!(!generated.lhs.is_empty() || !generated.rhs.is_empty());
    }

    // ==================== expression_respects_constraints tests ====================

    fn expr_from_postfix(s: &str) -> Expression {
        Expression::parse(s).expect("valid expression")
    }

    #[test]
    fn test_constraints_default_allows_all() {
        let opts = ExpressionConstraintOptions::default();

        // x^pi should be allowed with default options
        let expr = expr_from_postfix("xp^"); // x^pi
        assert!(
            expression_respects_constraints(&expr, opts),
            "x^pi should be allowed with default options"
        );

        // sinpi(e) should be allowed
        let expr = expr_from_postfix("eS"); // e then sinpi (S = SinPi)
        assert!(
            expression_respects_constraints(&expr, opts),
            "sinpi(e) should be allowed with default options"
        );
    }

    #[test]
    fn test_constraints_rational_exponents_rejects_transcendental() {
        let opts = ExpressionConstraintOptions {
            rational_exponents: true,
            ..Default::default()
        };

        // x^pi should be rejected (pi is transcendental)
        let expr = expr_from_postfix("xp^");
        assert!(
            !expression_respects_constraints(&expr, opts),
            "x^pi should be rejected with rational_exponents=true"
        );

        // x^e should be rejected
        let expr = expr_from_postfix("xe^");
        assert!(
            !expression_respects_constraints(&expr, opts),
            "x^e should be rejected with rational_exponents=true"
        );
    }

    #[test]
    fn test_constraints_rational_exponents_allows_integer() {
        let opts = ExpressionConstraintOptions {
            rational_exponents: true,
            ..Default::default()
        };

        // x^2 should be allowed (2 is integer)
        let expr = expr_from_postfix("x2^");
        assert!(
            expression_respects_constraints(&expr, opts),
            "x^2 should be allowed with rational_exponents=true"
        );

        // x^1 should be allowed
        let expr = expr_from_postfix("x1^");
        assert!(
            expression_respects_constraints(&expr, opts),
            "x^1 should be allowed with rational_exponents=true"
        );
    }

    #[test]
    fn test_constraints_rational_trig_args_rejects_irrational() {
        let opts = ExpressionConstraintOptions {
            rational_trig_args: true,
            ..Default::default()
        };

        // sinpi(e) should be rejected (e is irrational/transcendental)
        let expr = expr_from_postfix("eS"); // e then sinpi (S = SinPi)
        assert!(
            !expression_respects_constraints(&expr, opts),
            "sinpi(e) should be rejected with rational_trig_args=true"
        );

        // sinpi(pi) should be rejected (pi is transcendental)
        let expr = expr_from_postfix("pS"); // pi then sinpi
        assert!(
            !expression_respects_constraints(&expr, opts),
            "sinpi(pi) should be rejected with rational_trig_args=true"
        );
    }

    #[test]
    fn test_constraints_rational_trig_args_allows_rational() {
        let opts = ExpressionConstraintOptions {
            rational_trig_args: true,
            ..Default::default()
        };

        // sinpi(1) should be allowed (1 is integer, hence rational)
        let expr = expr_from_postfix("1S"); // 1 then sinpi (S = SinPi)
        assert!(
            expression_respects_constraints(&expr, opts),
            "sinpi(1) should be allowed with rational_trig_args=true"
        );

        // sinpi(2) should be allowed
        let expr = expr_from_postfix("2S");
        assert!(
            expression_respects_constraints(&expr, opts),
            "sinpi(2) should be allowed with rational_trig_args=true"
        );
    }

    #[test]
    fn test_constraints_rational_trig_args_rejects_x() {
        let opts = ExpressionConstraintOptions {
            rational_trig_args: true,
            ..Default::default()
        };

        // sinpi(x) should be rejected (x is not a constant rational)
        let expr = expr_from_postfix("xS"); // x then sinpi (S = SinPi)
        assert!(
            !expression_respects_constraints(&expr, opts),
            "sinpi(x) should be rejected with rational_trig_args=true"
        );
    }

    #[test]
    fn test_constraints_max_trig_cycles() {
        let opts = ExpressionConstraintOptions {
            max_trig_cycles: Some(2),
            ..Default::default()
        };

        // Single trig: sinpi(x) - should pass
        let expr = expr_from_postfix("xS"); // x then sinpi (S = SinPi)
        assert!(
            expression_respects_constraints(&expr, opts),
            "1 trig op should pass with max=2"
        );

        // Double nested: sinpi(cospi(x)) - should pass
        // x C S = sinpi(cospi(x)) where C = CosPi, S = SinPi
        let expr = expr_from_postfix("xCS");
        assert!(
            expression_respects_constraints(&expr, opts),
            "2 trig ops should pass with max=2"
        );

        // Triple nested: sinpi(cospi(tanpi(x))) - should fail
        // x T C S = sinpi(cospi(tanpi(x))) where T = TanPi
        let expr = expr_from_postfix("xTCS");
        assert!(
            !expression_respects_constraints(&expr, opts),
            "3 trig ops should fail with max=2"
        );
    }

    #[test]
    fn test_constraints_max_trig_cycles_none_unlimited() {
        let opts = ExpressionConstraintOptions {
            max_trig_cycles: None, // No limit
            ..Default::default()
        };

        // Even deeply nested trig should pass
        // x T C S T C S = 6 trig ops
        let expr = expr_from_postfix("xTCSTCS");
        assert!(
            expression_respects_constraints(&expr, opts),
            "Unlimited trig should pass any depth"
        );
    }

    #[test]
    fn test_constraints_combined() {
        let opts = ExpressionConstraintOptions {
            rational_exponents: true,
            rational_trig_args: true,
            max_trig_cycles: Some(1),
            ..Default::default()
        };

        // x^2 + sinpi(1) should pass
        let expr = expr_from_postfix("x2^1S+"); // S = SinPi
        assert!(
            expression_respects_constraints(&expr, opts),
            "x^2 + sinpi(1) should pass all constraints"
        );

        // x^pi should fail (rational_exponents)
        let expr = expr_from_postfix("xp^");
        assert!(
            !expression_respects_constraints(&expr, opts),
            "x^pi should fail rational_exponents"
        );

        // sinpi(x) should fail (rational_trig_args)
        let expr = expr_from_postfix("xS"); // S = SinPi
        assert!(
            !expression_respects_constraints(&expr, opts),
            "sinpi(x) should fail rational_trig_args"
        );

        // sinpi(cospi(1)) should fail (max_trig_cycles)
        let expr = expr_from_postfix("1CS"); // C = CosPi, S = SinPi
        assert!(
            !expression_respects_constraints(&expr, opts),
            "double trig should fail max_trig_cycles=1"
        );
    }

    #[test]
    fn test_constraints_malformed_expression() {
        let opts = ExpressionConstraintOptions::default();

        // Expression that would cause stack underflow
        let expr = Expression::from_symbols(&[crate::symbol::Symbol::Add]); // Just a binary op
        assert!(
            !expression_respects_constraints(&expr, opts),
            "Malformed expression should return false"
        );

        // Incomplete expression (too many values)
        let expr =
            Expression::from_symbols(&[crate::symbol::Symbol::One, crate::symbol::Symbol::Two]);
        assert!(
            !expression_respects_constraints(&expr, opts),
            "Incomplete expression should return false"
        );
    }

    #[test]
    fn test_constraints_user_constant_types() {
        // Set user constant 0 to be Integer type
        let mut user_types = [NumType::Transcendental; 16];
        user_types[0] = NumType::Integer;

        let opts = ExpressionConstraintOptions {
            rational_exponents: true,
            user_constant_types: user_types,
            ..Default::default()
        };

        // If UserConstant0 is treated as Integer, x^UserConstant0 should be allowed
        // (We can't easily test this without actually having user constants in the expression,
        // but this verifies the options struct is properly configured)
        assert_eq!(opts.user_constant_types[0], NumType::Integer);
    }
}