selen 0.15.5

Constraint Satisfaction Problem (CSP) solver
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
//! Runtime Constraint API
//!
//! This module provides a runtime-programmable constraint building API
//! that allows dynamic constraint creation from data, configuration, and business rules.
//!
//! # Phase 1: Core Expression System
//! - ExprBuilder for mathematical expression building (x.add(y).eq(z))
//! - VarIdExt trait for direct variable constraint methods
//! - ModelExt trait for posting constraints
//!
//! # Phase 2: Constraint Builder
//! - Builder struct for fluent constraint building
//! - Model::c() method for ultra-short syntax (m.c(x).eq(5))
//! - Global constraint shortcuts (alldiff, alleq, elem, count)
//!
//! # Phase 3: Boolean Logic
//! - Enhanced constraint composition with proper reification
//! - Constraint arrays and iteration support
//! - Helper functions for combining multiple constraints
//!
//! # Phase 4: Global Constraints
//! - Comprehensive global constraint support (alldiff, alleq, elem, count, betw, atmost, atleast, gcc)
//! - Optimized implementations for common constraint patterns
//! - Full integration with solver's global constraint system
//!
//! # Phase 5: Performance Optimization
//! - Optimized expression building with constant folding
//! - Efficient batch constraint posting with postall()
//! - Performance regression testing and benchmarking
//! - Best practices guide for optimal performance
//!
//! ## Performance Characteristics
//!
//! The runtime API provides flexibility at the cost of some performance overhead:
//!
//! - **Simple constraints**: ~3-4x overhead vs post! macro
//! - **Complex expressions**: ~1.4x overhead vs post! macro  
//! - **Batch operations**: Significantly reduced per-constraint overhead
//! - **Global constraints**: Minimal overhead, highly optimized
//!
//! ## When to Use Runtime API vs post! Macro
//!
//! **Use Runtime API for:**
//! - Data-driven constraint building from configs/databases
//! - Complex mathematical expressions with runtime coefficients
//! - Dynamic constraint generation based on business rules
//! - Global constraint patterns (alldiff, count, etc.)
//! - Batch constraint posting scenarios
//!
//! **Use post! macro for:**
//! - Simple, static constraints known at compile time
//! - Maximum performance for basic operations
//! - Direct translation from mathematical notation
//! - Performance-critical constraint posting loops
//!
//! ## Performance Best Practices
//!
//! 1. **Use batch posting**: `model.postall(constraints)` instead of individual posts
//! 2. **Leverage global constraints**: Use `alldiff()` instead of manual != constraints
//! 3. **Pre-allocate vectors**: Use `Vec::with_capacity()` for large constraint sets
//! 4. **Choose the right API**: Runtime API for complex/dynamic, post! for simple/static
//!
//! Key features:
//! - Pure runtime expression building (no macro syntax required)
//! - Ultra-short method names for concise code
//! - Fluent interface for natural constraint composition
//! - Full integration with existing constraint system
//! - Performance-optimized implementations

use crate::{
    model::Model,
    variables::{Val, VarId},
    constraints::props::PropId,
    lpsolver::csp_integration::{LinearConstraint, ConstraintRelation},
};

/// Debug flag - set to false to disable LP extraction debug output
const LP_DEBUG: bool = false;

/// Represents an expression that can be built at runtime
///
/// Performance optimizations:
/// - Uses Box for heap allocation to reduce stack size
/// - Implements Copy for simple variants to avoid cloning
/// - Inlined common operations for better performance
#[derive(Debug, Clone)]
#[doc(hidden)]
pub enum ExprBuilder {
    /// A variable reference
    Var(VarId),
    /// A constant value
    Val(Val),
    /// Addition of two expressions
    Add(Box<ExprBuilder>, Box<ExprBuilder>),
    /// Subtraction of two expressions  
    Sub(Box<ExprBuilder>, Box<ExprBuilder>),
    /// Multiplication of two expressions
    Mul(Box<ExprBuilder>, Box<ExprBuilder>),
    /// Division of two expressions
    Div(Box<ExprBuilder>, Box<ExprBuilder>),
    /// Modulo (remainder) of two expressions
    Modulo(Box<ExprBuilder>, Box<ExprBuilder>),
}

/// A constraint that can be posted to the model
#[derive(Clone, Debug)]
#[doc(hidden)]
pub struct Constraint {
    kind: ConstraintKind,
}

/// Phase 2: Fluent constraint builder for step-by-step constraint construction
#[doc(hidden)]
pub struct Builder<'a> {
    model: &'a mut Model,  // Safe mutable reference with lifetime
    current_expr: ExprBuilder,
}

#[derive(Clone)]
#[doc(hidden)]
#[derive(Debug)]
pub enum ConstraintKind {
    /// Simple binary constraint: left op right
    Binary {
        left: ExprBuilder,
        op: ComparisonOp,
        right: ExprBuilder,
    },
    /// Boolean combination of constraints
    And(Box<Constraint>, Box<Constraint>),
    Or(Box<Constraint>, Box<Constraint>),
    Not(Box<Constraint>),
    
    // =================== Phase 2: Extended Constraint Types ===================
    
    /// Linear constraint: coeffs[0]*vars[0] + coeffs[1]*vars[1] + ... op constant
    LinearInt {
        coeffs: Vec<i32>,
        vars: Vec<VarId>,
        op: ComparisonOp,
        constant: i32,
    },
    LinearFloat {
        coeffs: Vec<f64>,
        vars: Vec<VarId>,
        op: ComparisonOp,
        constant: f64,
    },
    
    /// Reified comparison: b <-> (left op right)
    ReifiedBinary {
        left: ExprBuilder,
        op: ComparisonOp,
        right: ExprBuilder,
        reif_var: VarId,  // Boolean variable that is true iff constraint holds
    },
    
    /// Reified linear constraint
    ReifiedLinearInt {
        coeffs: Vec<i32>,
        vars: Vec<VarId>,
        op: ComparisonOp,
        constant: i32,
        reif_var: VarId,
    },
    ReifiedLinearFloat {
        coeffs: Vec<f64>,
        vars: Vec<VarId>,
        op: ComparisonOp,
        constant: f64,
        reif_var: VarId,
    },
    
    /// Logical constraints
    BoolAnd {
        x: VarId,
        y: VarId,
        z: VarId,  // z <-> (x AND y)
    },
    BoolOr {
        x: VarId,
        y: VarId,
        z: VarId,  // z <-> (x OR y)
    },
    BoolNot {
        x: VarId,
        y: VarId,  // y <-> NOT x
    },
    BoolXor {
        x: VarId,
        y: VarId,
        z: VarId,  // z <-> (x XOR y)
    },
    BoolImplies {
        x: VarId,
        y: VarId,  // x -> y
    },
    
    /// Global constraints
    AllDifferent {
        vars: Vec<VarId>,
    },
    AllEqual {
        vars: Vec<VarId>,
    },
    Minimum {
        vars: Vec<VarId>,
        result: VarId,
    },
    Maximum {
        vars: Vec<VarId>,
        result: VarId,
    },
    Sum {
        vars: Vec<VarId>,
        result: VarId,
    },
    Element {
        index: VarId,
        array: Vec<VarId>,
        value: VarId,
    },
    
    /// Advanced global constraints (stubs for now)
    Table {
        vars: Vec<VarId>,
        tuples: Vec<Vec<i32>>,
    },
    GlobalCardinality {
        vars: Vec<VarId>,
        card_vars: Vec<VarId>,
        covers: Vec<i32>,
    },
    Cumulative {
        starts: Vec<VarId>,
        durations: Vec<VarId>,
        demands: Vec<VarId>,
        capacity: VarId,
    },
}

#[derive(Clone, Debug)]
#[doc(hidden)]
pub enum ComparisonOp {
    Eq,  // ==
    Ne,  // !=  
    Lt,  // <
    Le,  // <=
    Gt,  // >
    Ge,  // >=
}

/// Extract a linear constraint from a ConstraintKind AST node for LP solving
/// 
/// This function analyzes the AST BEFORE materialization to preserve the
/// constraint structure. It handles patterns like:
/// - Add(x, y).eq(z) → x + y = z
/// - x.le(y) → x ≤ y  
/// - x.eq(Val(c)) → x = c
/// - Add(x, y).le(Val(c)) → x + y ≤ c
/// - Sub(x, y).eq(z) → x - y = z
/// 
/// Returns None if the constraint is non-linear or not suitable for LP.
fn extract_lp_constraint(kind: &ConstraintKind) -> Option<LinearConstraint> {
    match kind {
        ConstraintKind::Binary { left, op, right } => {
            // Try to extract linear expression from both sides
            let left_linear = extract_linear_expr(left)?;
            let right_linear = extract_linear_expr(right)?;
            
            // Combine into a single constraint: left_expr op right_expr
            // Rewrite as: left_expr - right_expr op 0
            let mut coeffs = Vec::new();
            let mut vars = Vec::new();
            
            // Add left side with positive coefficients
            for (var, coeff) in left_linear.terms {
                vars.push(var);
                coeffs.push(coeff);
            }
            
            // Add right side with negative coefficients  
            for (var, coeff) in right_linear.terms {
                if let Some(idx) = vars.iter().position(|&v| v == var) {
                    // Variable already exists, combine coefficients
                    coeffs[idx] -= coeff;
                } else {
                    vars.push(var);
                    coeffs.push(-coeff);
                }
            }
            
            // RHS is: right_constant - left_constant
            let rhs = right_linear.constant - left_linear.constant;
            
            // Convert comparison operator to constraint relation
            let relation = match op {
                ComparisonOp::Eq => ConstraintRelation::Equality,
                ComparisonOp::Le => ConstraintRelation::LessOrEqual,
                ComparisonOp::Ge => ConstraintRelation::GreaterOrEqual,
                ComparisonOp::Lt | ComparisonOp::Gt | ComparisonOp::Ne => {
                    // Strict inequalities and != are not handled by LP
                    return None;
                }
            };
            
            Some(LinearConstraint::new(coeffs, vars, relation, rhs))
        }
        
        // Handle LinearInt constraints (already converted from expressions)
        ConstraintKind::LinearInt { coeffs, vars, op, constant } => {
            let relation = match op {
                ComparisonOp::Eq => ConstraintRelation::Equality,
                ComparisonOp::Le => ConstraintRelation::LessOrEqual,
                ComparisonOp::Ge => ConstraintRelation::GreaterOrEqual,
                ComparisonOp::Lt | ComparisonOp::Gt | ComparisonOp::Ne => {
                    return None;  // Strict inequalities not supported by LP
                }
            };
            
            // Convert i32 coefficients to f64
            let f_coeffs: Vec<f64> = coeffs.iter().map(|&c| c as f64).collect();
            Some(LinearConstraint::new(f_coeffs, vars.clone(), relation, *constant as f64))
        }
        
        // Handle LinearFloat constraints (already converted from expressions)
        ConstraintKind::LinearFloat { coeffs, vars, op, constant } => {
            let relation = match op {
                ComparisonOp::Eq => ConstraintRelation::Equality,
                ComparisonOp::Le => ConstraintRelation::LessOrEqual,
                ComparisonOp::Ge => ConstraintRelation::GreaterOrEqual,
                ComparisonOp::Lt | ComparisonOp::Gt | ComparisonOp::Ne => {
                    return None;  // Strict inequalities not supported by LP
                }
            };
            
            Some(LinearConstraint::new(coeffs.clone(), vars.clone(), relation, *constant))
        }
        
        // Handle Sum constraint: sum(vars) = result
        // This can be rewritten as: sum(vars) - result = 0
        ConstraintKind::Sum { vars, result } => {
            let mut coeffs = vec![1.0; vars.len()];
            let mut all_vars = vars.clone();
            
            // Add result variable with coefficient -1
            all_vars.push(*result);
            coeffs.push(-1.0);
            
            Some(LinearConstraint::new(
                coeffs,
                all_vars,
                ConstraintRelation::Equality,
                0.0
            ))
        }
        
        // Minimum: result = min(vars)
        // This could be modeled as: result <= vars[i] for all i, and at least one result == vars[i]
        // But this requires auxiliary constraints or disjunctions, which LP doesn't handle well
        // Better to leave it to the CSP propagator
        ConstraintKind::Minimum { .. } => None,
        
        // Maximum: result = max(vars)  
        // Similar to Minimum, needs disjunctions
        ConstraintKind::Maximum { .. } => None,
        
        // Reified constraints involve boolean variables and would need big-M formulations
        // which require variable bounds. Skip for now.
        ConstraintKind::ReifiedBinary { .. } => None,
        ConstraintKind::ReifiedLinearInt { .. } => None,
        ConstraintKind::ReifiedLinearFloat { .. } => None,
        
        // Boolean logic operations
        ConstraintKind::BoolAnd { .. } => None,
        ConstraintKind::BoolOr { .. } => None,
        ConstraintKind::BoolNot { .. } => None,
        ConstraintKind::BoolXor { .. } => None,
        ConstraintKind::BoolImplies { .. } => None,
        
        // Global constraints - not suitable for LP
        ConstraintKind::AllDifferent { .. } => None,
        ConstraintKind::AllEqual { .. } => None,
        ConstraintKind::Element { .. } => None,
        ConstraintKind::Table { .. } => None,
        ConstraintKind::GlobalCardinality { .. } => None,
        ConstraintKind::Cumulative { .. } => None,
        
        // Boolean combinations
        ConstraintKind::And(..) => None,
        ConstraintKind::Or(..) => None,
        ConstraintKind::Not(..) => None,
    }
}

/// Represents a linear expression: sum of (coeff * var) + constant
struct LinearExpr {
    terms: Vec<(VarId, f64)>,  // (variable, coefficient) pairs
    constant: f64,
}

/// Extract a linear expression from an ExprBuilder AST node
/// Returns None if the expression is non-linear (contains Mul or Div with variables)
fn extract_linear_expr(expr: &ExprBuilder) -> Option<LinearExpr> {
    match expr {
        ExprBuilder::Var(var) => {
            // Single variable: 1.0 * var + 0.0
            Some(LinearExpr {
                terms: vec![(*var, 1.0)],
                constant: 0.0,
            })
        }
        ExprBuilder::Val(val) => {
            // Constant: 0 * x + constant
            let constant = match val {
                Val::ValI(i) => *i as f64,
                Val::ValF(f) => *f,
            };
            Some(LinearExpr {
                terms: vec![],
                constant,
            })
        }
        ExprBuilder::Add(left, right) => {
            // Addition: (left_expr) + (right_expr)
            let left_linear = extract_linear_expr(left)?;
            let right_linear = extract_linear_expr(right)?;
            
            let mut terms = left_linear.terms;
            
            // Add right terms, combining coefficients for same variables
            for (var, coeff) in right_linear.terms {
                if let Some(idx) = terms.iter().position(|(v, _)| *v == var) {
                    terms[idx].1 += coeff;
                } else {
                    terms.push((var, coeff));
                }
            }
            
            Some(LinearExpr {
                terms,
                constant: left_linear.constant + right_linear.constant,
            })
        }
        ExprBuilder::Sub(left, right) => {
            // Subtraction: (left_expr) - (right_expr)
            let left_linear = extract_linear_expr(left)?;
            let right_linear = extract_linear_expr(right)?;
            
            let mut terms = left_linear.terms;
            
            // Subtract right terms, combining coefficients for same variables
            for (var, coeff) in right_linear.terms {
                if let Some(idx) = terms.iter().position(|(v, _)| *v == var) {
                    terms[idx].1 -= coeff;
                } else {
                    terms.push((var, -coeff));
                }
            }
            
            Some(LinearExpr {
                terms,
                constant: left_linear.constant - right_linear.constant,
            })
        }
        ExprBuilder::Mul(left, right) => {
            // Multiplication is only linear if one side is constant
            let left_linear = extract_linear_expr(left)?;
            let right_linear = extract_linear_expr(right)?;
            
            // Check if left is constant (no variable terms)
            if left_linear.terms.is_empty() {
                let scalar = left_linear.constant;
                let terms = right_linear.terms
                    .into_iter()
                    .map(|(var, coeff)| (var, coeff * scalar))
                    .collect();
                return Some(LinearExpr {
                    terms,
                    constant: right_linear.constant * scalar,
                });
            }
            
            // Check if right is constant (no variable terms)
            if right_linear.terms.is_empty() {
                let scalar = right_linear.constant;
                let terms = left_linear.terms
                    .into_iter()
                    .map(|(var, coeff)| (var, coeff * scalar))
                    .collect();
                return Some(LinearExpr {
                    terms,
                    constant: left_linear.constant * scalar,
                });
            }
            
            // Both sides have variables - non-linear!
            None
        }
        ExprBuilder::Div(left, right) => {
            // Division is only linear if right side is constant
            let left_linear = extract_linear_expr(left)?;
            let right_linear = extract_linear_expr(right)?;
            
            // Right must be constant (no variable terms)
            if !right_linear.terms.is_empty() {
                return None;  // Division by variable - non-linear!
            }
            
            let divisor = right_linear.constant;
            if divisor.abs() < 1e-10 {
                return None;  // Division by zero or near-zero
            }
            
            let terms = left_linear.terms
                .into_iter()
                .map(|(var, coeff)| (var, coeff / divisor))
                .collect();
            Some(LinearExpr {
                terms,
                constant: left_linear.constant / divisor,
            })
        }
        ExprBuilder::Modulo(_, _) => {
            // Modulo is non-linear in general
            None
        }
    }
}

#[doc(hidden)]
impl ExprBuilder {
    /// Create a new expression builder from a variable
    #[inline]
    pub fn from_var(var_id: VarId) -> Self {
        ExprBuilder::Var(var_id)
    }

    /// Create a new expression builder from a constant value
    #[inline]
    pub fn from_val(value: Val) -> Self {
        ExprBuilder::Val(value)
    }

    /// Add another expression or value
    /// Optimized for common cases where rhs is a constant
    #[inline]
    pub fn add(self, other: impl Into<ExprBuilder>) -> ExprBuilder {
        let other = other.into();
        
        // Optimization: combine constants at build time
        if let (ExprBuilder::Val(a), ExprBuilder::Val(b)) = (&self, &other) {
            return ExprBuilder::Val(*a + *b);
        }
        
        ExprBuilder::Add(Box::new(self), Box::new(other))
    }

    /// Subtract another expression or value
    /// Optimized for common cases where rhs is a constant
    #[inline]
    pub fn sub(self, other: impl Into<ExprBuilder>) -> ExprBuilder {
        let other = other.into();
        
        // Optimization: combine constants at build time
        if let (ExprBuilder::Val(a), ExprBuilder::Val(b)) = (&self, &other) {
            return ExprBuilder::Val(*a - *b);
        }
        
        ExprBuilder::Sub(Box::new(self), Box::new(other))
    }

    /// Multiply by another expression or value
    /// Optimized for common cases where rhs is a constant
    #[inline]
    pub fn mul(self, other: impl Into<ExprBuilder>) -> ExprBuilder {
        let other = other.into();
        
        // Optimization: combine constants at build time
        if let (ExprBuilder::Val(a), ExprBuilder::Val(b)) = (&self, &other) {
            return ExprBuilder::Val(*a * *b);
        }
        
        // Optimization: multiplication by 1 is identity
        if let ExprBuilder::Val(val) = &other {
            if let Some(1) = val.as_int() {
                return self;
            }
        }
        if let ExprBuilder::Val(val) = &self {
            if let Some(1) = val.as_int() {
                return other;
            }
        }
        
        ExprBuilder::Mul(Box::new(self), Box::new(other))
    }

    /// Divide by another expression or value
    /// Optimized for common cases where rhs is a constant
    #[inline]
    pub fn div(self, other: impl Into<ExprBuilder>) -> ExprBuilder {
        let other = other.into();
        
        // Optimization: combine constants at build time
        if let (ExprBuilder::Val(a), ExprBuilder::Val(b)) = (&self, &other) {
            return ExprBuilder::Val(*a / *b);
        }
        
        // Optimization: division by 1 is identity
        if let ExprBuilder::Val(val) = &other {
            if let Some(1) = val.as_int() {
                return self;
            }
        }
        
        ExprBuilder::Div(Box::new(self), Box::new(other))
    }

    /// Modulo (remainder) operation with another expression or value
    #[inline]
    pub fn modulo(self, other: impl Into<ExprBuilder>) -> ExprBuilder {
        ExprBuilder::Modulo(Box::new(self), Box::new(other.into()))
    }

    /// Create an equality constraint
    #[inline]
    pub fn eq(self, other: impl Into<ExprBuilder>) -> Constraint {
        Constraint {
            kind: ConstraintKind::Binary {
                left: self,
                op: ComparisonOp::Eq,
                right: other.into(),
            },
        }
    }

    /// Create a less-than-or-equal constraint
    #[inline]
    pub fn le(self, other: impl Into<ExprBuilder>) -> Constraint {
        Constraint {
            kind: ConstraintKind::Binary {
                left: self,
                op: ComparisonOp::Le,
                right: other.into(),
            },
        }
    }

    /// Create a greater-than constraint
    #[inline]
    pub fn gt(self, other: impl Into<ExprBuilder>) -> Constraint {
        Constraint {
            kind: ConstraintKind::Binary {
                left: self,
                op: ComparisonOp::Gt,
                right: other.into(),
            },
        }
    }

    /// Create a less-than constraint
    pub fn lt(self, other: impl Into<ExprBuilder>) -> Constraint {
        Constraint {
            kind: ConstraintKind::Binary {
                left: self,
                op: ComparisonOp::Lt,
                right: other.into(),
            },
        }
    }

    /// Create a greater-than-or-equal constraint
    pub fn ge(self, other: impl Into<ExprBuilder>) -> Constraint {
        Constraint {
            kind: ConstraintKind::Binary {
                left: self,
                op: ComparisonOp::Ge,
                right: other.into(),
            },
        }
    }

    /// Create a not-equal constraint
    pub fn ne(self, other: impl Into<ExprBuilder>) -> Constraint {
        Constraint {
            kind: ConstraintKind::Binary {
                left: self,
                op: ComparisonOp::Ne,
                right: other.into(),
            },
        }
    }
}

#[doc(hidden)]
impl Constraint {
    /// Combine this constraint with another using AND logic
    pub fn and(self, other: Constraint) -> Constraint {
        Constraint {
            kind: ConstraintKind::And(Box::new(self), Box::new(other)),
        }
    }

    /// Combine this constraint with another using OR logic
    pub fn or(self, other: Constraint) -> Constraint {
        Constraint {
            kind: ConstraintKind::Or(Box::new(self), Box::new(other)),
        }
    }

    /// Negate this constraint
    pub fn not(self) -> Constraint {
        Constraint {
            kind: ConstraintKind::Not(Box::new(self)),
        }
    }
}

// =================== PHASE 3: BOOLEAN LOGIC ===================

#[doc(hidden)]
impl Constraint {
    /// Combine multiple constraints with AND logic
    pub fn and_all(constraints: Vec<Constraint>) -> Option<Constraint> {
        if constraints.is_empty() {
            return None;
        }
        
        // Use reduce which returns Option, then map to handle the None case explicitly
        constraints.into_iter().reduce(|acc, c| acc.and(c))
    }
    
    /// Combine multiple constraints with OR logic
    pub fn or_all(constraints: Vec<Constraint>) -> Option<Constraint> {
        if constraints.is_empty() {
            return None;
        }
        
        // Use reduce which returns Option, then map to handle the None case explicitly
        constraints.into_iter().reduce(|acc, c| acc.or(c))
    }
}

/// Helper functions for constraint arrays and iteration
pub fn and_all(constraints: Vec<Constraint>) -> Option<Constraint> {
    Constraint::and_all(constraints)
}

pub fn or_all(constraints: Vec<Constraint>) -> Option<Constraint> {
    Constraint::or_all(constraints)
}

/// Create a constraint that all given constraints must be satisfied
pub fn all_of(constraints: Vec<Constraint>) -> Option<Constraint> {
    and_all(constraints)
}

/// Create a constraint that at least one of the given constraints must be satisfied
pub fn any_of(constraints: Vec<Constraint>) -> Option<Constraint> {
    or_all(constraints)
}

/// Extension trait for `Vec<Constraint>` to enable fluent constraint array operations
#[doc(hidden)]
pub trait ConstraintVecExt {
    /// Combine all constraints with AND logic
    fn and_all(self) -> Option<Constraint>;
    
    /// Combine all constraints with OR logic  
    fn or_all(self) -> Option<Constraint>;
    
    /// Post all constraints to the model (AND semantics - all must be satisfied)
    fn postall(self, model: &mut Model) -> Vec<PropId>;
}

impl ConstraintVecExt for Vec<Constraint> {
    fn and_all(self) -> Option<Constraint> {
        Constraint::and_all(self)
    }
    
    fn or_all(self) -> Option<Constraint> {
        Constraint::or_all(self)
    }
    
    fn postall(self, m: &mut Model) -> Vec<PropId> {
        self.into_iter()
            .map(|constraint| m.new(constraint))
            .collect()
    }
}

#[doc(hidden)]
impl<'a> Builder<'a> {
    /// Create a new constraint builder from a variable
    pub fn new(model: &'a mut Model, var: VarId) -> Self {
        Builder {
            model,
            current_expr: ExprBuilder::from_var(var),
        }
    }

    /// Add to the current expression
    pub fn add(mut self, other: impl Into<ExprBuilder>) -> Self {
        self.current_expr = self.current_expr.add(other);
        self
    }

    /// Subtract from the current expression
    pub fn sub(mut self, other: impl Into<ExprBuilder>) -> Self {
        self.current_expr = self.current_expr.sub(other);
        self
    }

    /// Multiply the current expression
    pub fn mul(mut self, other: impl Into<ExprBuilder>) -> Self {
        self.current_expr = self.current_expr.mul(other);
        self
    }

    /// Divide the current expression
    pub fn div(mut self, other: impl Into<ExprBuilder>) -> Self {
        self.current_expr = self.current_expr.div(other);
        self
    }

    /// Create and post an equality constraint
    pub fn eq(self, other: impl Into<ExprBuilder>) -> PropId {
        let constraint = self.current_expr.eq(other);
        self.model.new(constraint)
    }

    /// Create and post a not-equal constraint
    pub fn ne(self, other: impl Into<ExprBuilder>) -> PropId {
        let constraint = self.current_expr.ne(other);
        self.model.new(constraint)
    }

    /// Create and post a less-than constraint
    pub fn lt(self, other: impl Into<ExprBuilder>) -> PropId {
        let constraint = self.current_expr.lt(other);
        self.model.new(constraint)
    }

    /// Create and post a less-than-or-equal constraint
    pub fn le(self, other: impl Into<ExprBuilder>) -> PropId {
        let constraint = self.current_expr.le(other);
        self.model.new(constraint)
    }

    /// Create and post a greater-than constraint
    pub fn gt(self, other: impl Into<ExprBuilder>) -> PropId {
        let constraint = self.current_expr.gt(other);
        self.model.new(constraint)
    }

    /// Create and post a greater-than-or-equal constraint
    pub fn ge(self, other: impl Into<ExprBuilder>) -> PropId {
        let constraint = self.current_expr.ge(other);
        self.model.new(constraint)
    }
}

// Helper function to create a result variable for complex expressions
fn create_result_var(model: &mut Model, expr: &ExprBuilder) -> VarId {
    // For now, create a variable with a wide range
    // In a full implementation, we'd compute bounds based on the expression
    match expr {
        ExprBuilder::Var(var_id) => *var_id,
        ExprBuilder::Val(_) => {
            // For constants, we still need a variable to use in constraints
            model.int(-1000, 1000) // Placeholder bounds
        }
        _ => model.int(-1000, 1000), // Placeholder bounds for complex expressions
    }
}

// Helper function to post an expression constraint to the model
fn post_expression_constraint(model: &mut Model, expr: &ExprBuilder, result: VarId) -> PropId {
    match expr {
        ExprBuilder::Var(var_id) => {
            // Simple variable assignment: result = var_id
            model.props.equals(*var_id, result)
        }
        ExprBuilder::Val(val) => {
            // Constant assignment: result = val
            model.props.equals(*val, result)
        }
        ExprBuilder::Add(left, right) => {
            let left_var = create_result_var(model, left);
            let right_var = create_result_var(model, right);
            
            // Post constraints for sub-expressions if needed
            if !matches!(**left, ExprBuilder::Var(_)) {
                post_expression_constraint(model, left, left_var);
            }
            if !matches!(**right, ExprBuilder::Var(_)) {
                post_expression_constraint(model, right, right_var);
            }
            
            // Post addition constraint: left_var + right_var = result
            model.props.add(left_var, right_var, result)
        }
        ExprBuilder::Sub(left, right) => {
            let left_var = create_result_var(model, left);
            let right_var = create_result_var(model, right);
            
            // Post constraints for sub-expressions if needed
            if !matches!(**left, ExprBuilder::Var(_)) {
                post_expression_constraint(model, left, left_var);
            }
            if !matches!(**right, ExprBuilder::Var(_)) {
                post_expression_constraint(model, right, right_var);
            }
            
            // Post subtraction constraint: left_var - right_var = result
            model.props.sub(left_var, right_var, result)
        }
        ExprBuilder::Mul(left, right) => {
            let left_var = create_result_var(model, left);
            let right_var = create_result_var(model, right);
            
            // Post constraints for sub-expressions if needed
            if !matches!(**left, ExprBuilder::Var(_)) {
                post_expression_constraint(model, left, left_var);
            }
            if !matches!(**right, ExprBuilder::Var(_)) {
                post_expression_constraint(model, right, right_var);
            }
            
            // Post multiplication constraint: left_var * right_var = result
            model.props.mul(left_var, right_var, result)
        }
        ExprBuilder::Div(left, right) => {
            let left_var = create_result_var(model, left);
            let right_var = create_result_var(model, right);
            
            // Post constraints for sub-expressions if needed
            if !matches!(**left, ExprBuilder::Var(_)) {
                post_expression_constraint(model, left, left_var);
            }
            if !matches!(**right, ExprBuilder::Var(_)) {
                post_expression_constraint(model, right, right_var);
            }
            
            // Post division constraint: left_var / right_var = result
            model.props.div(left_var, right_var, result)
        }
        ExprBuilder::Modulo(left, right) => {
            let left_var = create_result_var(model, left);
            let right_var = create_result_var(model, right);
            
            // Post constraints for sub-expressions if needed
            if !matches!(**left, ExprBuilder::Var(_)) {
                post_expression_constraint(model, left, left_var);
            }
            if !matches!(**right, ExprBuilder::Var(_)) {
                post_expression_constraint(model, right, right_var);
            }
            
            // Post modulo constraint: left_var % right_var = result
            model.props.modulo(left_var, right_var, result)
        }
    }
}

// Helper function to get a variable representing an expression
fn get_expr_var(model: &mut Model, expr: &ExprBuilder) -> VarId {
    match expr {
        ExprBuilder::Var(var_id) => *var_id,
        ExprBuilder::Val(val) => {
            // Create a singleton variable for the constant
            match val {
                Val::ValI(i) => model.int(*i, *i),
                Val::ValF(f) => model.float(*f, *f),
            }
        }
        _ => {
            // For complex expressions, create a result variable and post constraints
            let result_var = create_result_var(model, expr);
            post_expression_constraint(model, expr, result_var);
            result_var
        }
    }
}

/// Try to convert expression-based constraints to linear constraint AST
/// 
/// Analyzes Binary constraints with Add/Mul expressions like:
/// - add(mul(x, int(5)), mul(y, int(4))).eq(int(3))  →  LinearInt: 5*x + 4*y == 3
/// - add(x, y).le(int(10))                             →  LinearInt: x + y <= 10
/// - sub(mul(x, int(2)), y).eq(int(0))                →  LinearInt: 2*x - y == 0
///
/// Returns the original constraint if it's not linear.
fn try_convert_to_linear_ast(kind: &ConstraintKind) -> ConstraintKind {
    match kind {
        ConstraintKind::Binary { left, op, right } => {
            // Try to extract linear form from both sides
            if let (Some((left_coeffs, left_vars, left_const)), Some((right_coeffs, right_vars, right_const))) = 
                (try_extract_linear_form(left), try_extract_linear_form(right)) {
                
                // Combine into single linear constraint: left - right op 0
                // left_expr op right_expr  =>  left_expr - right_expr op 0
                let mut coeffs = Vec::new();
                let mut vars = Vec::new();
                let mut all_ints = true;
                
                // Add left side coefficients
                for (var, coeff) in left_vars.iter().zip(left_coeffs.iter()) {
                    vars.push(*var);
                    coeffs.push(*coeff);
                    if !matches!(coeff, LinearCoefficient::Int(_)) {
                        all_ints = false;
                    }
                }
                
                // Subtract right side coefficients
                for (var, coeff) in right_vars.iter().zip(right_coeffs.iter()) {
                    if let Some(idx) = vars.iter().position(|v| v == var) {
                        // Variable exists, combine coefficients
                        coeffs[idx] = subtract_coefficients(&coeffs[idx], coeff);
                    } else {
                        // New variable, add with negative coefficient
                        vars.push(*var);
                        coeffs.push(negate_coefficient(coeff));
                    }
                    if !matches!(coeff, LinearCoefficient::Int(_)) {
                        all_ints = false;
                    }
                }
                
                // Constant: left_const - right_const, then move to right side
                let constant = subtract_coefficients(&left_const, &right_const);
                let constant = negate_coefficient(&constant); // Move to RHS
                
                // Check if constant is also an integer
                if !matches!(constant, LinearCoefficient::Int(_)) {
                    all_ints = false;
                }
                
                // Convert to LinearInt or LinearFloat
                if all_ints {
                    let int_coeffs: Vec<i32> = coeffs.iter().map(|c| match c {
                        LinearCoefficient::Int(i) => *i,
                        _ => 0,
                    }).collect();
                    let int_const = match constant {
                        LinearCoefficient::Int(i) => i,
                        _ => 0,
                    };
                    
                    return ConstraintKind::LinearInt {
                        coeffs: int_coeffs,
                        vars,
                        op: op.clone(),
                        constant: int_const,
                    };
                } else {
                    let float_coeffs: Vec<f64> = coeffs.iter().map(|c| match c {
                        LinearCoefficient::Int(i) => *i as f64,
                        LinearCoefficient::Float(f) => *f,
                    }).collect();
                    let float_const = match constant {
                        LinearCoefficient::Int(i) => i as f64,
                        LinearCoefficient::Float(f) => f,
                    };
                    
                    return ConstraintKind::LinearFloat {
                        coeffs: float_coeffs,
                        vars,
                        op: op.clone(),
                        constant: float_const,
                    };
                }
            }
            
            // Not linear, return original
            kind.clone()
        }
        // Other constraint types: return as-is
        _ => kind.clone(),
    }
}

#[derive(Clone, Copy, Debug)]
enum LinearCoefficient {
    Int(i32),
    Float(f64),
}

fn negate_coefficient(coeff: &LinearCoefficient) -> LinearCoefficient {
    match coeff {
        LinearCoefficient::Int(i) => LinearCoefficient::Int(-i),
        LinearCoefficient::Float(f) => LinearCoefficient::Float(-f),
    }
}

fn subtract_coefficients(a: &LinearCoefficient, b: &LinearCoefficient) -> LinearCoefficient {
    match (a, b) {
        (LinearCoefficient::Int(ia), LinearCoefficient::Int(ib)) => LinearCoefficient::Int(ia - ib),
        (LinearCoefficient::Float(fa), LinearCoefficient::Float(fb)) => LinearCoefficient::Float(fa - fb),
        (LinearCoefficient::Int(ia), LinearCoefficient::Float(fb)) => LinearCoefficient::Float(*ia as f64 - fb),
        (LinearCoefficient::Float(fa), LinearCoefficient::Int(ib)) => LinearCoefficient::Float(fa - *ib as f64),
    }
}

/// Try to extract linear form from an expression: coeffs, vars, constant
/// Returns None if the expression is not linear
/// 
/// Examples:
/// - Var(x) → ([1], [x], 0)
/// - Val(5) → ([], [], 5)  
/// - Mul(Var(x), Val(3)) → ([3], [x], 0)
/// - Add(Mul(Var(x), Val(2)), Var(y)) → ([2, 1], [x, y], 0)
/// - Add(Mul(Var(x), Val(2)), Val(5)) → ([2], [x], 5)
fn try_extract_linear_form(expr: &ExprBuilder) -> Option<(Vec<LinearCoefficient>, Vec<VarId>, LinearCoefficient)> {
    match expr {
        ExprBuilder::Var(var) => {
            // Single variable with coefficient 1
            Some((vec![LinearCoefficient::Int(1)], vec![*var], LinearCoefficient::Int(0)))
        }
        ExprBuilder::Val(val) => {
            // Just a constant
            match val {
                Val::ValI(i) => Some((vec![], vec![], LinearCoefficient::Int(*i))),
                Val::ValF(f) => Some((vec![], vec![], LinearCoefficient::Float(*f))),
            }
        }
        ExprBuilder::Mul(left, right) => {
            // Check for Var * Const or Const * Var patterns
            match (left.as_ref(), right.as_ref()) {
                (ExprBuilder::Var(var), ExprBuilder::Val(val)) => {
                    let coeff = match val {
                        Val::ValI(i) => LinearCoefficient::Int(*i),
                        Val::ValF(f) => LinearCoefficient::Float(*f),
                    };
                    Some((vec![coeff], vec![*var], LinearCoefficient::Int(0)))
                }
                (ExprBuilder::Val(val), ExprBuilder::Var(var)) => {
                    let coeff = match val {
                        Val::ValI(i) => LinearCoefficient::Int(*i),
                        Val::ValF(f) => LinearCoefficient::Float(*f),
                    };
                    Some((vec![coeff], vec![*var], LinearCoefficient::Int(0)))
                }
                _ => None, // Var * Var or other non-linear patterns
            }
        }
        ExprBuilder::Add(left, right) => {
            // Recursively extract both sides and combine
            let (mut left_coeffs, mut left_vars, left_const) = try_extract_linear_form(left)?;
            let (right_coeffs, right_vars, right_const) = try_extract_linear_form(right)?;
            
            // Combine terms
            for (var, coeff) in right_vars.iter().zip(right_coeffs.iter()) {
                if let Some(idx) = left_vars.iter().position(|v| v == var) {
                    // Variable exists, add coefficients
                    left_coeffs[idx] = add_coefficients(&left_coeffs[idx], coeff);
                } else {
                    // New variable
                    left_vars.push(*var);
                    left_coeffs.push(coeff.clone());
                }
            }
            
            let combined_const = add_coefficients(&left_const, &right_const);
            Some((left_coeffs, left_vars, combined_const))
        }
        ExprBuilder::Sub(left, right) => {
            // Similar to Add but subtract right side
            let (mut left_coeffs, mut left_vars, left_const) = try_extract_linear_form(left)?;
            let (right_coeffs, right_vars, right_const) = try_extract_linear_form(right)?;
            
            // Subtract terms
            for (var, coeff) in right_vars.iter().zip(right_coeffs.iter()) {
                if let Some(idx) = left_vars.iter().position(|v| v == var) {
                    left_coeffs[idx] = subtract_coefficients(&left_coeffs[idx], coeff);
                } else {
                    left_vars.push(*var);
                    left_coeffs.push(negate_coefficient(coeff));
                }
            }
            
            let combined_const = subtract_coefficients(&left_const, &right_const);
            Some((left_coeffs, left_vars, combined_const))
        }
        ExprBuilder::Div(_,_) => None, // Division is not linear
        ExprBuilder::Modulo(_,_) => None, // Modulo is not linear
    }
}

fn add_coefficients(a: &LinearCoefficient, b: &LinearCoefficient) -> LinearCoefficient {
    match (a, b) {
        (LinearCoefficient::Int(ia), LinearCoefficient::Int(ib)) => LinearCoefficient::Int(ia + ib),
        (LinearCoefficient::Float(fa), LinearCoefficient::Float(fb)) => LinearCoefficient::Float(fa + fb),
        (LinearCoefficient::Int(ia), LinearCoefficient::Float(fb)) => LinearCoefficient::Float(*ia as f64 + fb),
        (LinearCoefficient::Float(fa), LinearCoefficient::Int(ib)) => LinearCoefficient::Float(fa + *ib as f64),
    }
}

/// Helper function to apply intersection bounds for Var==Var equality constraints
/// This ensures modulo and other constraints see correct operand bounds immediately
fn apply_var_eq_bounds(model: &mut Model, var1: VarId, var2: VarId) {
    if var1.to_index() >= model.vars.count() || var2.to_index() >= model.vars.count() {
        return;
    }
    
    // Collect bounds from both variables
    let (var1_min, var1_max, is_var1_int) = match &model.vars[var1] {
        crate::variables::Var::VarI(ss) => (ss.min(), ss.max(), true),
        crate::variables::Var::VarF(_) => (0, 0, false),
    };
    
    let (var2_min, var2_max, is_var2_int) = match &model.vars[var2] {
        crate::variables::Var::VarI(ss) => (ss.min(), ss.max(), true),
        crate::variables::Var::VarF(_) => (0, 0, false),
    };
    
    // Only apply for integer variables
    if is_var1_int && is_var2_int {
        // Compute intersection bounds
        let intersection_min = if var1_min > var2_min { var1_min } else { var2_min };
        let intersection_max = if var1_max < var2_max { var1_max } else { var2_max };
        
        if intersection_min <= intersection_max {
            // Collect values to remove BEFORE any mutable borrows
            let var1_to_remove: Vec<i32> = if let crate::variables::Var::VarI(ss) = &model.vars[var1] {
                ss.iter()
                    .filter(|val| *val < intersection_min || *val > intersection_max)
                    .collect()
            } else {
                Vec::new()
            };
            
            let var2_to_remove: Vec<i32> = if let crate::variables::Var::VarI(ss) = &model.vars[var2] {
                ss.iter()
                    .filter(|val| *val < intersection_min || *val > intersection_max)
                    .collect()
            } else {
                Vec::new()
            };
            
            // Now remove values from var1
            if let crate::variables::Var::VarI(sparse_set) = &mut model.vars[var1] {
                for val in var1_to_remove {
                    sparse_set.remove(val);
                }
            }
            
            // Remove values from var2
            if let crate::variables::Var::VarI(sparse_set) = &mut model.vars[var2] {
                for val in var2_to_remove {
                    sparse_set.remove(val);
                }
            }
        }
    }
}

/// Post a constraint by storing its AST for later materialization
/// This allows LP extraction BEFORE creating propagators
/// 
/// **SPECIAL HANDLING:** Binary equals constraints are materialized immediately
/// to ensure they run before other constraints that depend on the variable's bounds.
/// This fixes issues where deferred constraints like `x.eq(47)` aren't propagated
/// before modulo/division constraints need to use x's bounds.
#[inline]
#[doc(hidden)]
pub fn post_constraint_kind(model: &mut Model, kind: &ConstraintKind) -> PropId {
    // **IMMEDIATE BOUNDS APPLICATION:** Handle Var==Var equality constraints
    // Apply bounds immediately to ensure modulo and other constraints see correct operand bounds
    // This must be done BEFORE storing in ASTs or materializing
    if let ConstraintKind::Binary { left, op, right } = kind {
        if matches!(op, ComparisonOp::Eq) {
            if let (ExprBuilder::Var(var1), ExprBuilder::Var(var2)) = (left, right) {
                // Apply intersection bounds immediately
                apply_var_eq_bounds(model, *var1, *var2);
            }
        }
    }
    
    // **IMMEDIATE MATERIALIZATION (BEFORE CONVERSION):** Simple binary equals constraints
    // Post these immediately so they propagate before other constraints run
    // MUST BE DONE BEFORE try_convert_to_linear_ast() since that converts Var==Val to LinearInt
    if let ConstraintKind::Binary { left, op, right } = kind {
        if matches!(op, ComparisonOp::Eq) {
            // Only immediate-materialize simple Var op Val patterns
            let is_var_eq_val = matches!(left, ExprBuilder::Var(_)) && matches!(right, ExprBuilder::Val(_));
            let is_val_eq_var = matches!(left, ExprBuilder::Val(_)) && matches!(right, ExprBuilder::Var(_));
            
            if is_var_eq_val || is_val_eq_var {
                // Materialize immediately
                let prop_id = materialize_constraint_kind(model, kind);
                return prop_id;
            }
        }
    }
    
    // STEP 0: Try to convert expression-based constraints to linear AST
    let kind = try_convert_to_linear_ast(kind);
    
    // STEP 1: Extract LP constraint from AST
    if let Some(lp_constraint) = extract_lp_constraint(&kind) {
        if LP_DEBUG {
            eprintln!("LP EXTRACTION: Extracted linear constraint from AST: {:?}", lp_constraint);
        }
        model.pending_lp_constraints.push(lp_constraint);
    }
    
    // STEP 2: Store AST for later materialization (delay propagator creation)
    model.pending_constraint_asts.push(kind.clone());
    
    // Return dummy PropId (actual PropId will be assigned during materialization)
    PropId(model.pending_constraint_asts.len() - 1)
}

/// Materialize a constraint AST into propagators
/// This is the actual implementation that creates propagators from AST
/// Called by Model::materialize_pending_asts() to convert delayed ASTs into propagators
#[inline]
pub(crate) fn materialize_constraint_kind(model: &mut Model, kind: &ConstraintKind) -> PropId {
    // This is the original post_constraint_kind logic that actually creates propagators
    match kind {
        ConstraintKind::Binary { left, op, right } => {
            // **IMMEDIATE BOUNDS APPLICATION** for Var==Val constraints
            // This ensures that deferred equals constraints immediately constrain the variable domain
            // so that subsequent constraints (like modulo) see the correct bounds.
            // This fixes the issue where constraints posted via `x.eq(47)` weren't applied until search time.
            if matches!(op, ComparisonOp::Eq) {
                if let (ExprBuilder::Var(var), ExprBuilder::Val(val)) = (left, right) {
                    // Check bounds to avoid panic if memory limit was hit
                    if var.to_index() < model.vars.count() {
                        match &mut model.vars[*var] {
                            crate::variables::Var::VarI(sparse_set) => {
                                if let Val::ValI(i) = val {
                                    sparse_set.remove_all_but(*i);
                                }
                            }
                            crate::variables::Var::VarF(interval) => {
                                if let Val::ValF(f) = val {
                                    interval.min = *f;
                                    interval.max = *f;
                                }
                            }
                        }
                    }
                } else if let (ExprBuilder::Val(val), ExprBuilder::Var(var)) = (left, right) {
                    // Check bounds to avoid panic if memory limit was hit
                    if var.to_index() < model.vars.count() {
                        match &mut model.vars[*var] {
                            crate::variables::Var::VarI(sparse_set) => {
                                if let Val::ValI(i) = val {
                                    sparse_set.remove_all_but(*i);
                                }
                            }
                            crate::variables::Var::VarF(interval) => {
                                if let Val::ValF(f) = val {
                                    interval.min = *f;
                                    interval.max = *f;
                                }
                            }
                        }
                    }
                }
            }
            
            // Optimization: Handle simple var-constant constraints directly
            if let (ExprBuilder::Var(var), ExprBuilder::Val(val)) = (left, right) {
                return post_var_val_constraint(model, *var, op, *val);
            }
            if let (ExprBuilder::Val(val), ExprBuilder::Var(var)) = (left, right) {
                return post_val_var_constraint(model, *val, op, *var);
            }
            
            // Fall back to general case
            let left_var = get_expr_var(model, left);
            let right_var = get_expr_var(model, right);
            
            match op {
                ComparisonOp::Eq => model.props.equals(left_var, right_var),
                ComparisonOp::Ne => model.props.not_equals(left_var, right_var),
                ComparisonOp::Lt => model.props.less_than(left_var, right_var),
                ComparisonOp::Le => model.props.less_than_or_equals(left_var, right_var),
                ComparisonOp::Gt => model.props.greater_than(left_var, right_var),
                ComparisonOp::Ge => model.props.greater_than_or_equals(left_var, right_var),
            }
        }
        ConstraintKind::And(left, right) => {
            // Materialize both constraints - AND is implicit
            materialize_constraint_kind(model, &left.kind);
            materialize_constraint_kind(model, &right.kind)
        }
        ConstraintKind::Or(left, right) => {
            // Special case: multiple equality constraints on the same variable
            // e.g., x == 2 OR x == 8 becomes x ∈ {2, 8}
            if let (ConstraintKind::Binary { left: left_var, op: ComparisonOp::Eq, right: left_val }, 
                    ConstraintKind::Binary { left: right_var, op: ComparisonOp::Eq, right: right_val }) = 
                (&left.kind, &right.kind) {
                if matches!((left_var, right_var), (ExprBuilder::Var(a), ExprBuilder::Var(b)) if a == b) {
                    // Both constraints are on the same variable - create domain constraint
                    if let (ExprBuilder::Var(var_id), ExprBuilder::Val(left_const), ExprBuilder::Val(right_const)) = 
                        (left_var, left_val, right_val) {
                        if let (Val::ValI(left_int), Val::ValI(right_int)) = (left_const, right_const) {
                            // Create a new variable with domain {left_val, right_val} and unify it with the original
                            let domain_vals = vec![*left_int, *right_int];
                            let domain_var = model.intset(domain_vals);
                            return model.props.equals(*var_id, domain_var);
                        }
                    }
                }
            }
            
            // For general OR cases, we need proper reification (not yet implemented)
            // For now, fall back to posting both constraints (which may conflict for some cases)
            materialize_constraint_kind(model, &left.kind);
            materialize_constraint_kind(model, &right.kind)
        }
        ConstraintKind::Not(constraint) => {
            // For NOT, we need to use boolean variables and logic
            // This is a simplified implementation - a full implementation would use reification
            materialize_constraint_kind(model, &constraint.kind)
        }
        
        // =================== Phase 2: Extended Constraint Types ===================
        
        ConstraintKind::LinearInt { coeffs, vars, op, constant } => {
            match op {
                ComparisonOp::Eq => model.props.int_lin_eq(coeffs.clone(), vars.clone(), *constant),
                ComparisonOp::Le => model.props.int_lin_le(coeffs.clone(), vars.clone(), *constant),
                ComparisonOp::Ne => model.props.int_lin_ne(coeffs.clone(), vars.clone(), *constant),
                ComparisonOp::Ge => {
                    // a1*x1 + ... >= c  <==>  -a1*x1 - ... <= -c
                    let neg_coeffs: Vec<i32> = coeffs.iter().map(|c| -c).collect();
                    model.props.int_lin_le(neg_coeffs, vars.clone(), -constant)
                }
                ComparisonOp::Gt => {
                    // a1*x1 + ... > c  <==>  a1*x1 + ... >= c+1
                    let neg_coeffs: Vec<i32> = coeffs.iter().map(|c| -c).collect();
                    model.props.int_lin_le(neg_coeffs, vars.clone(), -constant - 1)
                }
                ComparisonOp::Lt => {
                    // a1*x1 + ... < c  <==>  a1*x1 + ... <= c-1
                    model.props.int_lin_le(coeffs.clone(), vars.clone(), constant - 1)
                }
            }
        }
        
        ConstraintKind::LinearFloat { coeffs, vars, op, constant } => {
            match op {
                ComparisonOp::Eq => model.props.float_lin_eq(coeffs.clone(), vars.clone(), *constant),
                ComparisonOp::Le => model.props.float_lin_le(coeffs.clone(), vars.clone(), *constant),
                ComparisonOp::Ne => model.props.float_lin_ne(coeffs.clone(), vars.clone(), *constant),
                ComparisonOp::Ge => {
                    let neg_coeffs: Vec<f64> = coeffs.iter().map(|c| -c).collect();
                    model.props.float_lin_le(neg_coeffs, vars.clone(), -constant)
                }
                ComparisonOp::Lt => {
                    // a1*x1 + ... < c  <==>  a1*x1 + ... <= c - epsilon
                    // Use float step size based on model precision to approximate strict inequality
                    let epsilon = crate::variables::domain::float_interval::precision_to_step_size(model.float_precision_digits);
                    model.props.float_lin_le(coeffs.clone(), vars.clone(), constant - epsilon)
                }
                ComparisonOp::Gt => {
                    // a1*x1 + ... > c  <==>  a1*x1 + ... >= c + epsilon  <==>  -(a1*x1 + ...) <= -(c + epsilon)
                    let epsilon = crate::variables::domain::float_interval::precision_to_step_size(model.float_precision_digits);
                    let neg_coeffs: Vec<f64> = coeffs.iter().map(|c| -c).collect();
                    model.props.float_lin_le(neg_coeffs, vars.clone(), -constant - epsilon)
                }
            }
        }
        
        ConstraintKind::ReifiedBinary { left, op, right, reif_var } => {
            let left_var = get_expr_var(model, left);
            let right_var = get_expr_var(model, right);
            
            match op {
                ComparisonOp::Eq => model.props.int_eq_reif(left_var, right_var, *reif_var),
                ComparisonOp::Ne => model.props.int_ne_reif(left_var, right_var, *reif_var),
                ComparisonOp::Lt => model.props.int_lt_reif(left_var, right_var, *reif_var),
                ComparisonOp::Le => model.props.int_le_reif(left_var, right_var, *reif_var),
                ComparisonOp::Gt => model.props.int_gt_reif(left_var, right_var, *reif_var),
                ComparisonOp::Ge => model.props.int_ge_reif(left_var, right_var, *reif_var),
            }
        }
        
        ConstraintKind::ReifiedLinearInt { coeffs, vars, op, constant, reif_var } => {
            match op {
                ComparisonOp::Eq => model.props.int_lin_eq_reif(coeffs.clone(), vars.clone(), *constant, *reif_var),
                ComparisonOp::Le => model.props.int_lin_le_reif(coeffs.clone(), vars.clone(), *constant, *reif_var),
                ComparisonOp::Ne => model.props.int_lin_ne_reif(coeffs.clone(), vars.clone(), *constant, *reif_var),
                _ => {
                    // Other comparison operators not yet supported for reified integer linear constraints
                    // TODO: Add proper support for all comparison operators or return Result<PropId, Error>
                    // For now, post a trivial constraint: 0 <= 1 ⇔ true (always sets reif_var to 1)
                    // This maintains PropId consistency but doesn't enforce the intended constraint
                    // Users should only use ==, <=, != for reified integer linear constraints
                    let zero_coeffs: Vec<i32> = vec![0; vars.len()];
                    model.props.int_lin_le_reif(zero_coeffs, vars.clone(), 1, *reif_var)
                }
            }
        }
        
        ConstraintKind::ReifiedLinearFloat { coeffs, vars, op, constant, reif_var } => {
            match op {
                ComparisonOp::Eq => model.props.float_lin_eq_reif(coeffs.clone(), vars.clone(), *constant, *reif_var),
                ComparisonOp::Le => model.props.float_lin_le_reif(coeffs.clone(), vars.clone(), *constant, *reif_var),
                ComparisonOp::Ne => model.props.float_lin_ne_reif(coeffs.clone(), vars.clone(), *constant, *reif_var),
                _ => {
                    // Other comparison operators not yet supported for reified float linear constraints
                    // TODO: Add proper support for all comparison operators or return Result<PropId, Error>
                    // For now, post a trivial constraint: 0.0 <= 1.0 ⇔ true (always sets reif_var to 1)
                    // This maintains PropId consistency but doesn't enforce the intended constraint
                    // Users should only use ==, <=, != for reified float linear constraints
                    let zero_coeffs: Vec<f64> = vec![0.0; vars.len()];
                    model.props.float_lin_le_reif(zero_coeffs, vars.clone(), 1.0, *reif_var)
                }
            }
        }
        
        // NOTE: The following constraints create AST but fall back to Model methods for materialization
        // They don't benefit from LP solver integration, so we just call the existing implementations
        
        ConstraintKind::BoolAnd { x, y, z } => {
            model.bool_and(&[*x, *y, *z]);
            PropId(0) // Dummy - Model methods don't return PropId
        }
        
        ConstraintKind::BoolOr { x, y, z } => {
            model.bool_or(&[*x, *y, *z]);
            PropId(0)
        }
        
        ConstraintKind::BoolNot { x, y } => {
            model.props.bool_not(*x, *y)
        }
        
        ConstraintKind::BoolXor { x, y, z } => {
            // z <-> (x XOR y) which is equivalent to:
            // z <-> ((x AND NOT y) OR (NOT x AND y))
            // We can decompose this into multiple constraints:
            // 1. Create temporary variables for NOT x and NOT y
            let not_x = model.bool();
            let not_y = model.bool();
            
            // not_x = NOT x
            model.props.bool_not(*x, not_x);
            // not_y = NOT y
            model.props.bool_not(*y, not_y);
            
            // Create temporary variables for the two AND terms
            let and1 = model.bool();  // x AND NOT y
            let and2 = model.bool();  // NOT x AND y
            
            // and1 <-> (x AND NOT y)
            model.bool_and(&[*x, not_y, and1]);
            
            // and2 <-> (NOT x AND y)
            model.bool_and(&[not_x, *y, and2]);
            
            // z <-> (and1 OR and2)
            model.bool_or(&[and1, and2, *z]);
            
            PropId(0)
        }
        
        ConstraintKind::BoolImplies { x, y } => {
            // x -> y is equivalent to NOT x OR y
            // Create a temporary variable for NOT x
            let not_x = model.bool();
            
            // not_x = NOT x
            model.props.bool_not(*x, not_x);
            
            // Create an output variable for the implication
            let result = model.bool();
            
            // result <-> (NOT x OR y) = (not_x OR y)
            model.bool_or(&[not_x, *y, result]);
            
            // Constrain the result to be true (the implication must hold)
            model.props.equals(result, Val::int(1));
            
            PropId(0)
        }
        
        ConstraintKind::AllDifferent { vars } => {
            model.alldiff(vars);
            PropId(0)
        }
        
        ConstraintKind::AllEqual { vars } => {
            model.alleq(vars);
            PropId(0)
        }
        
        ConstraintKind::Minimum { vars, result } => {
            // min() returns Result<VarId, ...>, we need to equate it with result
            let min_var = model.min(vars).unwrap();
            model.props.equals(min_var, *result)
        }
        
        ConstraintKind::Maximum { vars, result } => {
            let max_var = model.max(vars).unwrap();
            model.props.equals(max_var, *result)
        }
        
        ConstraintKind::Sum { vars, result } => {
            model.props.sum(vars.clone(), *result)
        }
        
        ConstraintKind::Element { index, array, value } => {
            // Element signature: element(array: &[VarId], index: VarId, value: VarId)
            model.element(array, *index, *value)
        }
        
        ConstraintKind::Table { vars, tuples } => {
            let val_tuples: Vec<Vec<Val>> = tuples.iter()
                .map(|tuple| tuple.iter().map(|&v| Val::ValI(v)).collect())
                .collect();
            model.table(vars, val_tuples);
            PropId(0)
        }
        
        ConstraintKind::GlobalCardinality { vars, card_vars, covers } => {
            // gcc signature: gcc(vars: &[VarId], values: &[i32], counts: &[VarId]) -> Vec<PropId>
            let prop_ids = model.gcc(vars, covers, card_vars);
            prop_ids.first().copied().unwrap_or(PropId(0))
        }
        
        ConstraintKind::Cumulative { starts, durations, demands, capacity: _ } => {
            // Cumulative constraint: at any point in time, sum of demands <= capacity
            // This is a scheduling constraint ensuring resource capacity is not exceeded
            // 
            // Implementation: For each pair of tasks (i, j), if they overlap,
            // the sum of their demands must not exceed capacity.
            // Two tasks i,j overlap if: starts[i] < starts[j] + durations[j] AND starts[j] < starts[i] + durations[i]
            // 
            // Basic approach: post disjunctive constraints for pairs of tasks
            // to ensure they don't overlap if their combined demand exceeds capacity.
            
            // Check that all array lengths are consistent
            if !(starts.len() == durations.len() && starts.len() == demands.len()) {
                return PropId(0); // Constraint mismatch, skip
            }
            
            let n = starts.len();
            
            // For each pair of tasks, add ordering constraint
            for i in 0..n {
                for j in i+1..n {
                    let start_i = starts[i];
                    let start_j = starts[j];
                    let dur_i = durations[i];
                    let dur_j = durations[j];
                    let _demand_i = demands[i];
                    let _demand_j = demands[j];
                    
                    // Create variables for end times
                    let end_i = model.add(start_i, dur_i);
                    let end_j = model.add(start_j, dur_j);
                    
                    // Check if combined demand exceeds capacity
                    // If demand_i + demand_j > capacity, tasks cannot overlap
                    // Otherwise, we need to track cumulative resource usage (more complex)
                    // For Phase 2, we use a simple approximation:
                    // Post disjunctive constraints for all pairs
                    
                    // Create boolean for first disjunct: end_i <= start_j
                    let b1 = model.bool();
                    model.props.int_le_reif(end_i, start_j, b1);
                    
                    // Create boolean for second disjunct: end_j <= start_i
                    let b2 = model.bool();
                    model.props.int_le_reif(end_j, start_i, b2);
                    
                    // At least one must be true (tasks don't overlap in terms of execution):
                    // b1 OR b2 must be true
                    let b_or = model.bool();
                    model.bool_or(&[b1, b2, b_or]);
                    
                    // For now, we assume non-overlapping (simplified version)
                    // A full implementation would check: if demand_i + demand_j > capacity then enforce disjunction
                    // But without runtime access to constant values, we post a weaker constraint
                    // This ensures at least one ordering is enforced
                    model.props.equals(b_or, Val::int(1));
                }
            }
            
            PropId(0)
        }
    }
}

/// Optimized posting for var-constant constraints (creates singleton variable but caches it)
#[inline] 
fn post_var_val_constraint(model: &mut Model, var: VarId, op: &ComparisonOp, val: Val) -> PropId {
    let val_var = match val {
        Val::ValI(i) => model.int(i, i),
        Val::ValF(f) => model.float(f, f),
    };
    
    match op {
        ComparisonOp::Eq => model.props.equals(var, val_var),
        ComparisonOp::Ne => model.props.not_equals(var, val_var),
        ComparisonOp::Lt => model.props.less_than(var, val_var),
        ComparisonOp::Le => model.props.less_than_or_equals(var, val_var),
        ComparisonOp::Gt => model.props.greater_than(var, val_var),
        ComparisonOp::Ge => model.props.greater_than_or_equals(var, val_var),
    }
}

/// Optimized posting for constant-var constraints  
#[inline]
fn post_val_var_constraint(model: &mut Model, val: Val, op: &ComparisonOp, var: VarId) -> PropId {
    let val_var = match val {
        Val::ValI(i) => model.int(i, i),
        Val::ValF(f) => model.float(f, f),
    };
    
    match op {
        ComparisonOp::Eq => model.props.equals(val_var, var),
        ComparisonOp::Ne => model.props.not_equals(val_var, var),
        ComparisonOp::Lt => model.props.less_than(val_var, var),
        ComparisonOp::Le => model.props.less_than_or_equals(val_var, var),
        ComparisonOp::Gt => model.props.greater_than(val_var, var),
        ComparisonOp::Ge => model.props.greater_than_or_equals(val_var, var),
    }
}

// Conversion traits
impl From<VarId> for ExprBuilder {
    fn from(var_id: VarId) -> Self {
        ExprBuilder::from_var(var_id)
    }
}

impl From<i32> for ExprBuilder {
    fn from(value: i32) -> Self {
        ExprBuilder::from_val(Val::int(value))
    }
}

impl From<f64> for ExprBuilder {
    fn from(value: f64) -> Self {
        ExprBuilder::from_val(Val::float(value))
    }
}

impl From<Val> for ExprBuilder {
    fn from(value: Val) -> Self {
        ExprBuilder::from_val(value)
    }
}

// Reference implementations for convenience
impl From<&VarId> for ExprBuilder {
    fn from(value: &VarId) -> Self {
        ExprBuilder::from_var(*value)
    }
}

/// Extension trait for VarId to enable direct constraint building
#[doc(hidden)]
pub trait VarIdExt {
    /// Create an expression builder from this variable
    fn expr(self) -> ExprBuilder;
    
    /// Add another value/variable to this one
    fn add(self, other: impl Into<ExprBuilder>) -> ExprBuilder;
    
    /// Subtract another value/variable from this one
    fn sub(self, other: impl Into<ExprBuilder>) -> ExprBuilder;
    
    /// Multiply this variable by another value/variable
    fn mul(self, other: impl Into<ExprBuilder>) -> ExprBuilder;
    
    /// Divide this variable by another value/variable
    fn div(self, other: impl Into<ExprBuilder>) -> ExprBuilder;
    
    /// Modulo (remainder) of this variable by another value/variable
    fn modulo(self, other: impl Into<ExprBuilder>) -> ExprBuilder;
    
    /// Create equality constraint: this == other
    fn eq(self, other: impl Into<ExprBuilder>) -> Constraint;
    
    /// Create inequality constraint: this != other
    fn ne(self, other: impl Into<ExprBuilder>) -> Constraint;
    
    /// Create less-than constraint: this < other
    fn lt(self, other: impl Into<ExprBuilder>) -> Constraint;
    
    /// Create less-than-or-equal constraint: this <= other
    fn le(self, other: impl Into<ExprBuilder>) -> Constraint;
    
    /// Create greater-than constraint: this > other
    fn gt(self, other: impl Into<ExprBuilder>) -> Constraint;
    
    /// Create greater-than-or-equal constraint: this >= other
    fn ge(self, other: impl Into<ExprBuilder>) -> Constraint;
}

impl VarIdExt for VarId {
    fn expr(self) -> ExprBuilder {
        ExprBuilder::from_var(self)
    }
    
    fn add(self, other: impl Into<ExprBuilder>) -> ExprBuilder {
        ExprBuilder::from_var(self).add(other)
    }
    
    fn sub(self, other: impl Into<ExprBuilder>) -> ExprBuilder {
        ExprBuilder::from_var(self).sub(other)
    }
    
    fn mul(self, other: impl Into<ExprBuilder>) -> ExprBuilder {
        ExprBuilder::from_var(self).mul(other)
    }
    
    fn div(self, other: impl Into<ExprBuilder>) -> ExprBuilder {
        ExprBuilder::from_var(self).div(other)
    }
    
    fn modulo(self, other: impl Into<ExprBuilder>) -> ExprBuilder {
        ExprBuilder::from_var(self).modulo(other)
    }
    
    fn eq(self, other: impl Into<ExprBuilder>) -> Constraint {
        ExprBuilder::from_var(self).eq(other)
    }
    
    fn ne(self, other: impl Into<ExprBuilder>) -> Constraint {
        ExprBuilder::from_var(self).ne(other)
    }
    
    fn lt(self, other: impl Into<ExprBuilder>) -> Constraint {
        ExprBuilder::from_var(self).lt(other)
    }
    
    fn le(self, other: impl Into<ExprBuilder>) -> Constraint {
        ExprBuilder::from_var(self).le(other)
    }
    
    fn gt(self, other: impl Into<ExprBuilder>) -> Constraint {
        ExprBuilder::from_var(self).gt(other)
    }
    
    fn ge(self, other: impl Into<ExprBuilder>) -> Constraint {
        ExprBuilder::from_var(self).ge(other)
    }
}

/// Extension trait for Model to support runtime constraint posting
#[doc(hidden)]
pub trait ModelExt {
    /// Post a new constraint to the model using runtime API
    fn new(&mut self, constraint: Constraint) -> PropId;
    
    /// Phase 2: Start building a constraint from a variable (ultra-short syntax)
    /// Usage: m.c(x).eq(5), m.c(x).add(y).le(10)
    fn c(&mut self, var: VarId) -> Builder<'_>;
    
    /// Global constraint: all variables must have different values
    fn alldiff(&mut self, vars: &[VarId]) -> PropId;
    
    /// Global constraint: all variables must have the same value
    fn alleq(&mut self, vars: &[VarId]) -> PropId;
    
    /// Element constraint: array\[index\] == value
    fn elem(&mut self, array: &[VarId], index: VarId, value: VarId) -> PropId;
    
    /// Count constraint: count occurrences of value in vars
    fn count(&mut self, vars: &[VarId], value: i32, result: VarId) -> PropId;
    
    /// Between constraint: min <= var <= max (cardinality constraint)
    fn betw(&mut self, var: VarId, min: i32, max: i32) -> PropId;
    
    /// At most constraint: var <= value (cardinality constraint)
    fn atmost(&mut self, var: VarId, value: i32) -> PropId;
    
    /// At least constraint: var >= value (cardinality constraint)  
    fn atleast(&mut self, var: VarId, value: i32) -> PropId;
    
    /// Global cardinality constraint: count values in vars must match cardinalities
    fn gcc(&mut self, vars: &[VarId], values: &[i32], counts: &[VarId]) -> Vec<PropId>;
    
    /// Phase 3: Post multiple constraints with AND semantics (all must be satisfied)
    fn postall(&mut self, constraints: Vec<Constraint>) -> Vec<PropId>;
    
    /// Phase 3: Post a constraint that combines multiple constraints with AND
    fn post_and(&mut self, constraints: Vec<Constraint>) -> Option<PropId>;
    
    /// Phase 3: Post a constraint that combines multiple constraints with OR
    fn post_or(&mut self, constraints: Vec<Constraint>) -> Option<PropId>;
}

impl ModelExt for Model {
    fn new(&mut self, constraint: Constraint) -> PropId {
        post_constraint_kind(self, &constraint.kind)
    }
    
    fn c(&mut self, var: VarId) -> Builder<'_> {
        Builder::new(self, var)
    }
    
    fn alldiff(&mut self, vars: &[VarId]) -> PropId {
        // Convert slice to Vec for props method
        self.props.all_different(vars.to_vec())
    }
    
    fn alleq(&mut self, vars: &[VarId]) -> PropId {
        // Use the proper all_equal constraint implementation
        self.props.all_equal(vars.to_vec())
    }
    
    fn elem(&mut self, array: &[VarId], index: VarId, value: VarId) -> PropId {
        // Convert slice to Vec for props method
        self.props.element(array.to_vec(), index, value)
    }
    
    fn count(&mut self, vars: &[VarId], value: i32, result: VarId) -> PropId {
        // Create a fixed variable for the constant value
        let target_var = self.int(value, value);
        self.props.count_constraint(vars.to_vec(), target_var, result)
    }
    
    fn betw(&mut self, var: VarId, min: i32, max: i32) -> PropId {
        // Between constraint: min <= var <= max
        // Post two constraints: var >= min AND var <= max
        self.props.greater_than_or_equals(var, Val::int(min));
        self.props.less_than_or_equals(var, Val::int(max))
    }
    
    fn atmost(&mut self, var: VarId, value: i32) -> PropId {
        // At most constraint: var <= value
        self.props.less_than_or_equals(var, Val::int(value))
    }
    
    fn atleast(&mut self, var: VarId, value: i32) -> PropId {
        // At least constraint: var >= value
        self.props.greater_than_or_equals(var, Val::int(value))
    }
    
    fn gcc(&mut self, vars: &[VarId], values: &[i32], counts: &[VarId]) -> Vec<PropId> {
        // Global cardinality constraint: count each value in vars and match cardinalities
        let mut prop_ids = Vec::with_capacity(values.len());
        
        for (&value, &count_var) in values.iter().zip(counts.iter()) {
            // For each value, create a count constraint
            // Create a fixed variable for the constant value
            let target_var = self.int(value, value);
            let prop_id = self.props.count_constraint(vars.to_vec(), target_var, count_var);
            prop_ids.push(prop_id);
        }
        
        prop_ids
    }
    
    /// Phase 3: Post multiple constraints with AND semantics (all must be satisfied)
    /// Optimized version that processes constraints in batches
    fn postall(&mut self, constraints: Vec<Constraint>) -> Vec<PropId> {
        // Pre-allocate result vector
        let mut result = Vec::with_capacity(constraints.len());
        
        // Process constraints in batches to reduce function call overhead
        for constraint in constraints {
            result.push(post_constraint_kind(self, &constraint.kind));
        }
        
        result
    }
    
    /// Phase 3: Post a constraint that combines multiple constraints with AND
    fn post_and(&mut self, constraints: Vec<Constraint>) -> Option<PropId> {
        if constraints.is_empty() {
            return None;
        }
        
        if constraints.len() == 1 {
            return Some(post_constraint_kind(self, &constraints[0].kind));
        }
        
        // Build AND constraint using the existing AND composition
        let mut result = constraints[0].clone();
        for constraint in constraints.into_iter().skip(1) {
            result = Constraint {
                kind: ConstraintKind::And(Box::new(result), Box::new(constraint))
            };
        }
        
        Some(post_constraint_kind(self, &result.kind))
    }
    
    /// Phase 3: Post a constraint that combines multiple constraints with OR
    fn post_or(&mut self, constraints: Vec<Constraint>) -> Option<PropId> {
        if constraints.is_empty() {
            return None;
        }
        
        if constraints.len() == 1 {
            return Some(post_constraint_kind(self, &constraints[0].kind));
        }
        
        // Build OR constraint using the existing OR composition
        let mut result = constraints[0].clone();
        for constraint in constraints.into_iter().skip(1) {
            result = Constraint {
                kind: ConstraintKind::Or(Box::new(result), Box::new(constraint))
            };
        }
        
        Some(post_constraint_kind(self, &result.kind))
    }
}

#[cfg(test)]
mod tests;