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
mod abs;
mod add;
mod alldiff;
mod allequal;
pub mod between;
mod bool_logic;
pub mod cardinality;
pub mod conditional;
mod count;
mod div;
mod element;
mod eq;
mod leq;
mod linear;
mod max;
mod min;
mod modulo;
mod mul;
mod neq;
mod noop;
mod reification;
mod sum;
mod table;

use std::ops::{Index, IndexMut};
use std::rc::Rc;

use crate::{
    variables::VarId,
    variables::views::{Context, View, ViewExt},
};

// Type aliases for cleaner Rc-based sharing
type PropagatorBox = Box<dyn Prune>;
type SharedPropagator = Rc<PropagatorBox>;

/// Enforce a specific constraint by pruning domain of decision variables.
///
/// The `Any` supertrait allows downcasting to concrete propagator types,
/// which is used for LP solver integration (extracting linear constraints).
pub trait Prune: core::fmt::Debug + std::any::Any {
    /// Perform pruning based on variable domains and internal state.
    fn prune(&self, ctx: &mut Context) -> Option<()>;
}

/// Isolate methods that prevent propagator from being used as a trait-object.
pub trait Propagate: Prune + 'static {
    /// List variables that schedule the propagator when their domain changes.
    fn list_trigger_vars(&self) -> impl Iterator<Item = VarId>;
}

/// Store internal state for each propagators, along with dependencies for when to schedule each.
#[doc(hidden)]
#[derive(Clone, Debug, Default)]
pub struct Propagators {
    state: Vec<SharedPropagator>,
    dependencies: Vec<Vec<PropId>>,
    /// Counter for the number of propagation steps performed
    propagation_count: usize,
    /// Counter for the number of search nodes (branching points) explored
    node_count: usize,
    /// Constraint metadata registry for optimization introspection
    constraint_registry: crate::optimization::constraint_metadata::ConstraintRegistry,
}

#[doc(hidden)]
impl Propagators {
    /// Extend dependencies matrix with a row for the new decision variable.
    pub fn on_new_var(&mut self) {
        self.dependencies.push(Vec::new());
    }

    /// List ids of all registered propagators.
    pub fn get_prop_ids_iter(&self) -> impl Iterator<Item = PropId> {
        (0..self.state.len()).map(PropId)
    }

    /// Acquire immutable reference to propagator state (for constraint analysis).
    pub fn get_state(&self, p: PropId) -> &SharedPropagator {
        &self.state[p.0]
    }

    /// Get list of propagators that should be scheduled when a bound of variable `v` changes.
    pub fn on_bound_change(&self, v: VarId) -> impl Iterator<Item = PropId> + '_ {
        self.dependencies[v].iter().copied()
    }

    /// Get the number of propagation steps performed so far.
    pub fn get_propagation_count(&self) -> usize {
        self.propagation_count
    }

    /// Increment the propagation step counter.
    pub fn increment_propagation_count(&mut self) {
        self.propagation_count += 1;
    }

    /// Get the number of search nodes explored so far.
    pub fn get_node_count(&self) -> usize {
        self.node_count
    }

    /// Increment the search node counter.
    pub fn increment_node_count(&mut self) {
        self.node_count += 1;
    }

    /// Get the number of propagators in this collection.
    pub fn count(&self) -> usize {
        self.state.len()
    }

    /// Get access to the constraint metadata registry
    pub fn get_constraint_registry(
        &self,
    ) -> &crate::optimization::constraint_metadata::ConstraintRegistry {
        &self.constraint_registry
    }

    /// Get mutable access to the constraint metadata registry
    pub fn get_constraint_registry_mut(
        &mut self,
    ) -> &mut crate::optimization::constraint_metadata::ConstraintRegistry {
        &mut self.constraint_registry
    }

    /// Extract linear constraints from propagators for LP solving.
    ///
    /// Scans all propagators and extracts FloatLinEq and FloatLinLe constraints
    /// into a LinearConstraintSystem that can be passed to the LP solver.
    ///
    /// # Returns
    /// A `LinearConstraintSystem` containing all linear constraints found in the model.
    ///
    /// # Example
    /// ```ignore
    /// // After creating a model with linear constraints
    /// let linear_system = model.propagators().extract_linear_system();
    /// if linear_system.is_suitable_for_lp() {
    ///     let lp_problem = linear_system.to_lp_problem(&model.vars());
    ///     // Solve with LP solver...
    /// }
    /// ```
    pub fn extract_linear_system(&self) -> crate::lpsolver::LinearConstraintSystem {
        use crate::lpsolver::{LinearConstraint, LinearConstraintSystem};
        use crate::variables::VarId;
        use std::collections::HashMap;

        let mut system = LinearConstraintSystem::new();

        // Phase 1: Build map of derived variables to their linear expressions
        // e.g., sum = x + y  stores  sum -> ([(x, 1.0), (y, 1.0)], 0.0)
        let mut derived_vars: HashMap<VarId, (Vec<(VarId, f64)>, f64)> = HashMap::new();

        // Phase 1: Extract direct constraints and build derived variable map
        for prop_rc in &self.state {
            let prop_box: &Box<dyn Prune> = prop_rc.as_ref();
            let prop_ref: &dyn Prune = prop_box.as_ref();

            if let Some(eq) = (prop_ref as &dyn std::any::Any).downcast_ref::<linear::FloatLinEq>()
            {
                // Direct linear equality constraint
                let constraint = LinearConstraint::equality(
                    eq.coefficients().to_vec(),
                    eq.variables().to_vec(),
                    eq.constant(),
                );
                system.add_constraint(constraint);
            } else if let Some(le) =
                (prop_ref as &dyn std::any::Any).downcast_ref::<linear::FloatLinLe>()
            {
                // Direct linear inequality constraint
                let constraint = LinearConstraint::less_or_equal(
                    le.coefficients().to_vec(),
                    le.variables().to_vec(),
                    le.constant(),
                );
                system.add_constraint(constraint);
            } else if let Some(add) =
                (prop_ref as &dyn std::any::Any).downcast_ref::<add::Add<VarId, VarId>>()
            {
                // Add: x + y = s (derived variable definition)
                // Store: s -> ([(x, 1.0), (y, 1.0)], 0.0)
                let x = *add.x();
                let y = *add.y();
                let s = add.s();
                // Debug: eprintln!("LP EXTRACTION: Found Add constraint: {:?} + {:?} = {:?}", x, y, s);
                derived_vars.insert(s, (vec![(x, 1.0), (y, 1.0)], 0.0));

                // Also add as linear equality for LP: x + y - s = 0
                let constraint =
                    LinearConstraint::equality(vec![1.0, 1.0, -1.0], vec![x, y, s], 0.0);
                system.add_constraint(constraint);
            }
        }

        // Phase 2: Extract LessThanOrEquals constraints: x <= y becomes x - y <= 0
        // The LP solver will handle variable bounds from domains automatically
        for prop_rc in &self.state {
            let prop_box: &Box<dyn Prune> = prop_rc.as_ref();
            let prop_ref: &dyn Prune = prop_box.as_ref();

            if let Some(leq) = (prop_ref as &dyn std::any::Any)
                .downcast_ref::<leq::LessThanOrEquals<VarId, VarId>>()
            {
                let x_var = *leq.x();
                let y_var = *leq.y();

                // Debug: eprintln!("LP EXTRACTION: Found LessThanOrEquals constraint: {:?} <= {:?}", x_var, y_var);

                // x <= y  →  x - y <= 0  →  1.0*x + (-1.0)*y <= 0
                let constraint =
                    LinearConstraint::less_or_equal(vec![1.0, -1.0], vec![x_var, y_var], 0.0);
                system.add_constraint(constraint);
            }
        }

        system
    }

    /// Optimize the order of AllDifferent constraints using multiple universal heuristics.
    ///
    /// Uses a combination of three heuristics to determine priority:
    /// 1. Domain tightness: Constraints with smaller average domain sizes (closer to failure)
    /// 2. Variable connectivity: Constraints affecting variables with higher connectivity
    /// 3. Constraint saturation: Constraints with higher ratio of fixed variables
    ///
    /// This approach is universal and works for any constraint satisfaction problem.
    pub fn optimize_alldiff_order(&mut self, vars: &crate::variables::Vars) {
        use crate::optimization::constraint_metadata::ConstraintType;

        // Get all AllDifferent constraints from the registry
        let alldiff_constraint_ids = self
            .constraint_registry
            .get_constraints_by_type(&ConstraintType::AllDifferent);

        if alldiff_constraint_ids.len() <= 1 {
            return; // Nothing to optimize with 0 or 1 AllDifferent constraints
        }

        // Pre-calculate variable connectivity map
        let variable_connectivity = self.calculate_variable_connectivity_map();

        // Create a vector of (prop_id, priority_scores) for AllDifferent constraints only
        let mut alldiff_priorities: Vec<(usize, (f64, f64, f64))> = Vec::new();

        for constraint_id in alldiff_constraint_ids {
            if let Some(metadata) = self.constraint_registry.get_constraint(constraint_id) {
                // Extract variables from this AllDifferent constraint
                let constraint_vars = match &metadata.data {
                    crate::optimization::constraint_metadata::ConstraintData::NAry { operands } => {
                        operands
                            .iter()
                            .filter_map(|op| match op {
                                crate::optimization::constraint_metadata::ViewInfo::Variable {
                                    var_id,
                                } => Some(*var_id),
                                _ => None,
                            })
                            .collect::<Vec<_>>()
                    }
                    _ => continue, // Skip non-NAry constraints
                };

                // Calculate domain tightness score (smaller average domain = higher priority)
                let tightness_score = self.calculate_domain_tightness(&constraint_vars, vars);

                // Calculate variable connectivity score (higher connectivity = higher priority)
                let connectivity_score =
                    self.calculate_variable_connectivity(&constraint_vars, &variable_connectivity);

                // Calculate constraint saturation score (higher fixed ratio = higher priority)
                let saturation_score = self.calculate_constraint_saturation(&constraint_vars, vars);

                // Map constraint_id to propagator index
                let prop_index = constraint_id.0;
                if prop_index < self.state.len() {
                    alldiff_priorities.push((
                        prop_index,
                        (tightness_score, connectivity_score, saturation_score),
                    ));
                }
            }
        }

        if alldiff_priorities.is_empty() {
            return; // No AllDifferent constraints found
        }

        // Sort AllDifferent constraints by priority (lexicographic ordering):
        // Primary: domain tightness (ascending - smaller domains = higher priority)
        // Secondary: constraint saturation (descending - higher fixed ratio = higher priority)
        // Tertiary: variable connectivity (descending - higher connectivity = higher priority)
        alldiff_priorities.sort_by(|a, b| {
            // First compare by domain tightness (ascending)
            let tightness_cmp =
                a.1.0
                    .partial_cmp(&b.1.0)
                    .unwrap_or(std::cmp::Ordering::Equal);
            if tightness_cmp != std::cmp::Ordering::Equal {
                return tightness_cmp;
            }
            // Then by constraint saturation (descending)
            let saturation_cmp =
                b.1.2
                    .partial_cmp(&a.1.2)
                    .unwrap_or(std::cmp::Ordering::Equal);
            if saturation_cmp != std::cmp::Ordering::Equal {
                return saturation_cmp;
            }
            // Finally by variable connectivity (descending)
            b.1.1
                .partial_cmp(&a.1.1)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        // Check if reordering would actually change anything
        let mut needs_reordering = false;
        for (i, &(prop_idx, _)) in alldiff_priorities.iter().enumerate() {
            if i < alldiff_priorities.len() - 1 {
                let next_prop_idx = alldiff_priorities[i + 1].0;
                if prop_idx > next_prop_idx {
                    needs_reordering = true;
                    break;
                }
            }
        }

        if !needs_reordering {
            return; // Already in optimal order
        }

        // Create new ordered vectors for reordering
        let original_state = self.state.clone();
        let original_dependencies = self.dependencies.clone();

        // Extract AllDifferent constraint indices for reordering
        let alldiff_indices: std::collections::HashSet<usize> =
            alldiff_priorities.iter().map(|&(idx, _)| idx).collect();

        // Build the new state with AllDifferent constraints in optimized order
        self.state.clear();
        let mut index_mapping = vec![0; original_state.len()];
        let mut new_idx = 0;

        // First, add AllDifferent constraints in priority order
        for &(old_idx, _) in &alldiff_priorities {
            if old_idx < original_state.len() {
                self.state.push(original_state[old_idx].clone());
                index_mapping[old_idx] = new_idx;
                new_idx += 1;
            }
        }

        // Then, add all non-AllDifferent constraints in their original order
        for (old_idx, constraint) in original_state.iter().enumerate() {
            if !alldiff_indices.contains(&old_idx) {
                self.state.push(constraint.clone());
                index_mapping[old_idx] = new_idx;
                new_idx += 1;
            }
        }

        // Update dependency mapping with new indices
        self.dependencies = vec![Vec::new(); original_dependencies.len()];
        for (var_id, deps) in original_dependencies.into_iter().enumerate() {
            for old_prop_id in deps {
                if old_prop_id.0 < index_mapping.len() {
                    let new_prop_id = PropId(index_mapping[old_prop_id.0]);
                    self.dependencies[var_id].push(new_prop_id);
                }
            }
        }
    }


    /// Calculate domain tightness score for a constraint.
    /// Lower scores indicate tighter constraints (smaller domains) which should be prioritized.
    fn calculate_domain_tightness(
        &self,
        constraint_vars: &[VarId],
        vars: &crate::variables::Vars,
    ) -> f64 {
        if constraint_vars.is_empty() {
            return f64::INFINITY; // Invalid constraint, lowest priority
        }

        let total_domain_size: f64 = constraint_vars
            .iter()
            .map(|&var_id| self.calculate_variable_domain_size(var_id, vars))
            .sum();

        // Return average domain size (smaller = tighter = higher priority)
        total_domain_size / (constraint_vars.len() as f64)
    }

    /// Calculate the effective domain size for a variable.
    /// For integer variables, this is the actual domain size.
    /// For float variables, this estimates discrete steps within the interval.
    fn calculate_variable_domain_size(&self, var_id: VarId, vars: &crate::variables::Vars) -> f64 {
        match &vars[var_id] {
            crate::variables::Var::VarI(sparse_set) => sparse_set.size() as f64,
            crate::variables::Var::VarF(interval) => {
                // For float variables, estimate the number of discrete steps
                let range = interval.max - interval.min;
                if range <= 0.0 {
                    return 1.0; // Single value
                }

                // Estimate discrete domain size based on step size
                let estimated_steps = (range / interval.step).ceil();
                estimated_steps.max(1.0) // At least 1 step
            }
        }
    }

    /// Calculate variable connectivity map - how many constraints each variable participates in.
    /// This builds a connectivity graph to understand variable importance in the constraint network.
    fn calculate_variable_connectivity_map(&self) -> std::collections::HashMap<VarId, usize> {
        let mut connectivity_map = std::collections::HashMap::new();

        // Since we don't have direct access to all constraints, we'll iterate through
        // all constraint types and collect their constraint IDs
        use crate::optimization::constraint_metadata::ConstraintType;

        let constraint_types = [
            ConstraintType::AllDifferent,
            ConstraintType::Addition,
            ConstraintType::Multiplication,
            ConstraintType::Modulo,
            ConstraintType::Division,
            ConstraintType::AbsoluteValue,
            ConstraintType::Minimum,
            ConstraintType::Maximum,
            ConstraintType::Sum,
            ConstraintType::Equals,
            ConstraintType::NotEquals,
            ConstraintType::LessThanOrEquals,
            ConstraintType::LessThan,
            ConstraintType::GreaterThanOrEquals,
            ConstraintType::GreaterThan,
            ConstraintType::BooleanAnd,
            ConstraintType::BooleanOr,
            ConstraintType::BooleanNot,
        ];

        // Iterate through all constraint types to count variable participation
        for constraint_type in &constraint_types {
            for constraint_id in self
                .constraint_registry
                .get_constraints_by_type(constraint_type)
            {
                if let Some(metadata) = self.constraint_registry.get_constraint(constraint_id) {
                    // Extract variables from this constraint and increment their connectivity
                    for var_id in &metadata.variables {
                        *connectivity_map.entry(*var_id).or_insert(0) += 1;
                    }
                }
            }
        }

        connectivity_map
    }

    /// Calculate average variable connectivity for a constraint.
    /// Higher connectivity indicates variables that are more constrained and likely to propagate.
    fn calculate_variable_connectivity(
        &self,
        constraint_vars: &[VarId],
        connectivity_map: &std::collections::HashMap<VarId, usize>,
    ) -> f64 {
        if constraint_vars.is_empty() {
            return 0.0; // No variables, lowest connectivity
        }

        let total_connectivity: usize = constraint_vars
            .iter()
            .map(|var_id| connectivity_map.get(var_id).copied().unwrap_or(0))
            .sum();

        // Return average connectivity (higher = more constrained = higher priority)
        total_connectivity as f64 / constraint_vars.len() as f64
    }

    /// Calculate constraint saturation score - ratio of fixed variables to total variables.
    /// Higher saturation indicates constraints closer to completion and likely to propagate effectively.
    fn calculate_constraint_saturation(
        &self,
        constraint_vars: &[VarId],
        vars: &crate::variables::Vars,
    ) -> f64 {
        if constraint_vars.is_empty() {
            return 0.0; // No variables, lowest saturation
        }

        let fixed_variables = constraint_vars
            .iter()
            .filter(|&&var_id| {
                match &vars[var_id] {
                    crate::variables::Var::VarI(sparse_set) => sparse_set.size() == 1,
                    crate::variables::Var::VarF(interval) => {
                        // For float variables, consider fixed if the range is very small
                        let range = interval.max - interval.min;
                        range <= interval.step
                    }
                }
            })
            .count();

        // Return saturation ratio (higher = more fixed = higher priority)
        fixed_variables as f64 / constraint_vars.len() as f64
    }

    /// Declare a new propagator to enforce `x + y == s`.
    pub fn add(&mut self, x: impl View, y: impl View, s: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let x_info = self.analyze_view(&x);
        let y_info = self.analyze_view(&y);
        let s_info = ViewInfo::Variable { var_id: s };

        let variables: Vec<_> = x
            .get_underlying_var()
            .into_iter()
            .chain(y.get_underlying_var())
            .chain(std::iter::once(s))
            .collect();

        let metadata = ConstraintData::NAry {
            operands: vec![x_info, y_info, s_info],
        };

        self.push_new_prop_with_metadata(
            self::add::Add::new(x, y, s),
            ConstraintType::Addition,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce `x - y == s`.
    /// This reuses the Add propagator by transforming to `x + (-y) == s`.
    pub fn sub(&mut self, x: impl View, y: impl View, s: VarId) -> PropId {
        use crate::variables::Val;
        // x - y = s  =>  x + (-y) = s
        self.add(x, y.times_neg(Val::ValI(-1)), s)
    }

    /// Declare a new propagator to enforce `x * y == s`.
    pub fn mul(&mut self, x: impl View, y: impl View, s: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{
            ConstraintData, ConstraintType, ConstraintValue, ViewInfo,
        };

        // Special handling for TypedConstant detection
        fn analyze_view_for_constants<T: View>(view: &T) -> ViewInfo {
            if let Some(var_id) = view.get_underlying_var() {
                ViewInfo::Variable { var_id }
            } else {
                // This view has no underlying variable - it might be a constant
                // For TypedConstant, we can detect this by checking min == max
                // Since both are the constant value
                let min_val = view.min_raw(&crate::variables::Vars::default());
                let max_val = view.max_raw(&crate::variables::Vars::default());

                if min_val == max_val {
                    // This is likely a constant value
                    let const_val = match min_val {
                        crate::variables::Val::ValI(i) => ConstraintValue::Integer(i),
                        crate::variables::Val::ValF(f) => ConstraintValue::Float(f),
                    };
                    ViewInfo::Constant { value: const_val }
                } else {
                    ViewInfo::Complex
                }
            }
        }

        let x_info = analyze_view_for_constants(&x);
        let y_info = analyze_view_for_constants(&y);
        let s_info = ViewInfo::Variable { var_id: s };

        let variables: Vec<_> = x
            .get_underlying_var()
            .into_iter()
            .chain(y.get_underlying_var())
            .chain(std::iter::once(s))
            .collect();

        let metadata = ConstraintData::NAry {
            operands: vec![x_info, y_info, s_info],
        };

        self.push_new_prop_with_metadata(
            self::mul::Mul::new(x, y, s),
            ConstraintType::Multiplication,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce `x % y == s`.
    pub fn modulo(&mut self, x: impl View, y: impl View, s: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let x_info = self.analyze_view(&x);
        let y_info = self.analyze_view(&y);
        let s_info = ViewInfo::Variable { var_id: s };

        let variables: Vec<_> = x
            .get_underlying_var()
            .into_iter()
            .chain(y.get_underlying_var())
            .chain(std::iter::once(s))
            .collect();

        let metadata = ConstraintData::NAry {
            operands: vec![x_info, y_info, s_info],
        };

        self.push_new_prop_with_metadata(
            self::modulo::Modulo::new(x, y, s),
            ConstraintType::Modulo,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce `|x| == s`.
    pub fn abs(&mut self, x: impl View, s: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let x_info = self.analyze_view(&x);
        let s_info = ViewInfo::Variable { var_id: s };

        let variables: Vec<_> = x
            .get_underlying_var()
            .into_iter()
            .chain(std::iter::once(s))
            .collect();

        let metadata = ConstraintData::NAry {
            operands: vec![x_info, s_info],
        };

        self.push_new_prop_with_metadata(
            self::abs::Abs::new(x, s),
            ConstraintType::AbsoluteValue,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce `min(vars...) == result`.
    pub fn min(&mut self, vars: Vec<VarId>, result: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<ViewInfo> = vars
            .iter()
            .map(|&var| ViewInfo::Variable { var_id: var })
            .chain(std::iter::once(ViewInfo::Variable { var_id: result }))
            .collect();

        let variables: Vec<_> = vars
            .iter()
            .cloned()
            .chain(std::iter::once(result))
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::min::Min::new(vars, result),
            ConstraintType::Minimum,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce `max(vars...) == result`.
    pub fn max(&mut self, vars: Vec<VarId>, result: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<ViewInfo> = vars
            .iter()
            .map(|&var| ViewInfo::Variable { var_id: var })
            .chain(std::iter::once(ViewInfo::Variable { var_id: result }))
            .collect();

        let variables: Vec<_> = vars
            .iter()
            .cloned()
            .chain(std::iter::once(result))
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::max::Max::new(vars, result),
            ConstraintType::Maximum,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce `x / y == s`.
    pub fn div(&mut self, x: impl View, y: impl View, s: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let x_info = self.analyze_view(&x);
        let y_info = self.analyze_view(&y);
        let s_info = ViewInfo::Variable { var_id: s };

        let variables: Vec<_> = x
            .get_underlying_var()
            .into_iter()
            .chain(y.get_underlying_var())
            .chain(std::iter::once(s))
            .collect();

        let metadata = ConstraintData::NAry {
            operands: vec![x_info, y_info, s_info],
        };

        self.push_new_prop_with_metadata(
            self::div::Div::new(x, y, s),
            ConstraintType::Division,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce `sum(xs) == s`.
    pub fn sum(&mut self, xs: Vec<impl View>, s: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let mut operands = Vec::new();
        let mut variables = Vec::new();

        // Analyze all variables in the sum
        for x in &xs {
            operands.push(self.analyze_view(x));
            if let Some(var_id) = x.get_underlying_var() {
                variables.push(var_id);
            }
        }

        // Add the result variable
        operands.push(ViewInfo::Variable { var_id: s });
        variables.push(s);

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::sum::Sum::new(xs, s),
            ConstraintType::Sum,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce `x == y`.
    pub fn equals(&mut self, x: impl View, y: impl View) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType};

        let x_info = self.analyze_view(&x);
        let y_info = self.analyze_view(&y);

        let variables: Vec<_> = x
            .get_underlying_var()
            .into_iter()
            .chain(y.get_underlying_var())
            .collect();

        let metadata = ConstraintData::Binary {
            left: x_info,
            right: y_info,
        };

        self.push_new_prop_with_metadata(
            self::eq::Eq::new(x, y),
            ConstraintType::Equals,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce `x != y`.
    pub fn not_equals(&mut self, x: impl View, y: impl View) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType};

        let x_info = self.analyze_view(&x);
        let y_info = self.analyze_view(&y);

        let variables: Vec<_> = x
            .get_underlying_var()
            .into_iter()
            .chain(y.get_underlying_var())
            .collect();

        let metadata = ConstraintData::Binary {
            left: x_info,
            right: y_info,
        };

        self.push_new_prop_with_metadata(
            self::neq::NotEquals::new(x, y),
            ConstraintType::NotEquals,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce `x <= y`.
    pub fn less_than_or_equals(&mut self, x: impl View, y: impl View) -> PropId {
        // Use the metadata collection version
        self.less_than_or_equals_with_metadata(x, y)
    }

    /// Declare a type-aware propagator to enforce `x < y`.
    /// This version uses ULP-based precision by implementing x < y as x + 1 <= y for integers
    /// and appropriate ULP-based bounds for floats.
    pub fn less_than(&mut self, x: impl View, y: impl View) -> PropId {
        // Use the metadata collection version
        self.less_than_with_metadata(x, y)
    }

    /// Declare a new propagator to enforce `x >= y`.
    pub fn greater_than_or_equals(&mut self, x: impl View, y: impl View) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType};

        let x_info = self.analyze_view(&x);
        let y_info = self.analyze_view(&y);

        let variables: Vec<_> = x
            .get_underlying_var()
            .into_iter()
            .chain(y.get_underlying_var())
            .collect();

        let metadata = ConstraintData::Binary {
            left: x_info,
            right: y_info,
        };

        self.push_new_prop_with_metadata(
            self::leq::LessThanOrEquals::new(y, x), // x >= y  =>  y <= x
            ConstraintType::GreaterThanOrEquals,
            variables,
            metadata,
        )
    }

    /// Declare a type-aware propagator to enforce `x > y`.
    /// This version uses ULP-based precision by implementing x > y as x >= y + 1 for integers
    /// and appropriate ULP-based bounds for floats.
    pub fn greater_than(&mut self, x: impl View, y: impl View) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType};

        let x_info = self.analyze_view(&x);
        let y_info = self.analyze_view(&y);

        // For constraint metadata, we want to preserve the original relationship x > y
        // The metadata represents the logical constraint, not the implementation details
        let metadata = ConstraintData::Binary {
            left: x_info,
            right: y_info,
        };

        let variables: Vec<_> = x
            .get_underlying_var()
            .into_iter()
            .chain(y.get_underlying_var())
            .collect();

        self.push_new_prop_with_metadata(
            self::leq::LessThanOrEquals::new(y.next(), x), // x > y  =>  y.next() <= x
            ConstraintType::GreaterThan,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce that all variables have different values.
    /// This is more efficient than pairwise not-equals constraints.
    /// Uses the ultra-efficient AllDifferent implementation with adaptive algorithms.
    pub fn all_different(&mut self, vars: Vec<VarId>) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<_> = vars
            .iter()
            .map(|&var_id| ViewInfo::Variable { var_id })
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::alldiff::AllDiff::new(vars.clone()),
            ConstraintType::AllDifferent,
            vars,
            metadata,
        )
    }

    /// Declare a new propagator to enforce that all variables have the same value.
    /// This is the complement of AllDifferent constraint.
    /// Uses efficient domain intersection for value propagation.
    pub fn all_equal(&mut self, vars: Vec<VarId>) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<_> = vars
            .iter()
            .map(|&var_id| ViewInfo::Variable { var_id })
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::allequal::AllEqual::new(vars.clone()),
            ConstraintType::AllEqual,
            vars,
            metadata,
        )
    }

    /// Declare a new propagator to enforce that exactly count_var variables in vars equal target_var.
    /// This is the unified count constraint that works with variable targets.
    /// For constant values, create a fixed variable (e.g., m.int(3, 3)) and pass it as target_var.
    pub fn count_constraint(
        &mut self,
        vars: Vec<VarId>,
        target_var: impl crate::variables::View,
        count_var: VarId,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let target_info = self.analyze_view(&target_var);
        let count_instance = count::Count::new(vars.clone(), target_var, count_var);

        let mut operands: Vec<ViewInfo> = vars
            .iter()
            .map(|&var_id| ViewInfo::Variable { var_id })
            .collect();
        operands.push(target_info);
        operands.push(ViewInfo::Variable { var_id: count_var });

        let metadata = ConstraintData::NAry { operands };

        let mut all_vars = vars.clone();
        all_vars.extend(target_var.get_underlying_var());
        all_vars.push(count_var);

        self.push_new_prop_with_metadata(count_instance, ConstraintType::Count, all_vars, metadata)
    }

    /// Declare a new propagator to enforce that array[index] == value.
    /// This is the element constraint for array indexing operations.
    /// Supports both constant and variable indices with bidirectional propagation.
    pub fn element(&mut self, array: Vec<VarId>, index: VarId, value: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let mut operands: Vec<ViewInfo> = array
            .iter()
            .map(|&var_id| ViewInfo::Variable { var_id })
            .collect();
        operands.push(ViewInfo::Variable { var_id: index });
        operands.push(ViewInfo::Variable { var_id: value });

        let metadata = ConstraintData::NAry { operands };
        let trigger_vars = {
            let mut vars = array.clone();
            vars.push(index);
            vars.push(value);
            vars
        };

        self.push_new_prop_with_metadata(
            self::element::Element::new(array, index, value),
            ConstraintType::Element,
            trigger_vars,
            metadata,
        )
    }

    /// Declare a new propagator to enforce a between constraint: lower <= middle <= upper
    pub fn between_constraint(&mut self, lower: VarId, middle: VarId, upper: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let variables = vec![lower, middle, upper];
        let operands = vec![
            ViewInfo::Variable { var_id: lower },
            ViewInfo::Variable { var_id: middle },
            ViewInfo::Variable { var_id: upper },
        ];

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::between::BetweenConstraint::new(lower, middle, upper),
            ConstraintType::Between,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce "at least N" cardinality constraint
    pub fn at_least_constraint(
        &mut self,
        vars: Vec<VarId>,
        target_value: i32,
        count: i32,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<ViewInfo> = vars
            .iter()
            .map(|&var_id| ViewInfo::Variable { var_id })
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::cardinality::CardinalityConstraint::at_least(vars.clone(), target_value, count),
            ConstraintType::AtLeast,
            vars,
            metadata,
        )
    }

    /// Declare a new propagator to enforce "at most N" cardinality constraint
    pub fn at_most_constraint(
        &mut self,
        vars: Vec<VarId>,
        target_value: i32,
        count: i32,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<ViewInfo> = vars
            .iter()
            .map(|&var_id| ViewInfo::Variable { var_id })
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::cardinality::CardinalityConstraint::at_most(vars.clone(), target_value, count),
            ConstraintType::AtMost,
            vars,
            metadata,
        )
    }

    /// Declare a new propagator to enforce "exactly N" cardinality constraint
    pub fn exactly_constraint(
        &mut self,
        vars: Vec<VarId>,
        target_value: i32,
        count: i32,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<ViewInfo> = vars
            .iter()
            .map(|&var_id| ViewInfo::Variable { var_id })
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::cardinality::CardinalityConstraint::exactly(vars.clone(), target_value, count),
            ConstraintType::Exactly,
            vars,
            metadata,
        )
    }

    /// Declare a new propagator to enforce if-then-else constraint
    pub fn if_then_else_constraint(
        &mut self,
        condition: self::conditional::Condition,
        then_constraint: self::conditional::SimpleConstraint,
        else_constraint: Option<self::conditional::SimpleConstraint>,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let constraint = self::conditional::IfThenElseConstraint::new(
            condition,
            then_constraint,
            else_constraint,
        );
        let variables = constraint.variables();

        let operands: Vec<ViewInfo> = variables
            .iter()
            .map(|&var_id| ViewInfo::Variable { var_id })
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            constraint,
            ConstraintType::IfThenElse,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce a table constraint.
    /// Variables must take values that correspond to tuples in the allowed table.
    /// This constraint is useful for expressing complex relationships between variables
    /// by explicitly listing all valid combinations.
    pub fn table_constraint(
        &mut self,
        vars: Vec<VarId>,
        tuples: Vec<Vec<crate::variables::Val>>,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<ViewInfo> = vars
            .iter()
            .map(|&var_id| ViewInfo::Variable { var_id })
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::table::Table::new(vars.clone(), tuples),
            ConstraintType::Table,
            vars,
            metadata,
        )
    }

    /// Create a no-operation propagator for branching operations that have already applied domain filtering.
    pub fn noop(&mut self) -> PropId {
        self.push_new_prop(self::noop::NoOp::new())
    }

    /// Register propagator dependencies and store its state as a trait object.
    fn push_new_prop(&mut self, state: impl Propagate) -> PropId {
        // Create new handle to refer to propagator state and dependencies
        let p = PropId(self.state.len());

        // Register dependencies listed by trait implementor
        for v in state.list_trigger_vars() {
            // Ensure the dependencies matrix is large enough
            while self.dependencies.len() <= v.to_index() {
                self.dependencies.push(Vec::new());
            }
            self.dependencies[v].push(p);
        }

        // Store propagator state as shared trait object
        let boxed = Box::new(state);
        self.state.push(Rc::new(boxed));

        p
    }

    /// Register propagator with metadata collection
    fn push_new_prop_with_metadata(
        &mut self,
        state: impl Propagate,
        constraint_type: crate::optimization::constraint_metadata::ConstraintType,
        variables: Vec<VarId>,
        metadata: crate::optimization::constraint_metadata::ConstraintData,
    ) -> PropId {
        // Create propagator first
        let prop_id = self.push_new_prop(state);

        // Register constraint metadata
        let _constraint_id =
            self.constraint_registry
                .register_constraint(constraint_type, variables, metadata);

        prop_id
    }

    /// Get the number of constraints for analysis
    pub fn constraint_count(&self) -> usize {
        self.state.len()
    }

    // Helper functions for constraint metadata collection

    /// Analyze a view to extract constraint information
    fn analyze_view<T: View>(
        &self,
        view: &T,
    ) -> crate::optimization::constraint_metadata::ViewInfo {
        use crate::optimization::constraint_metadata::{ConstraintValue, ViewInfo};

        if let Some(var_id) = view.get_underlying_var() {
            ViewInfo::Variable { var_id }
        } else {
            // Check if this is a constant value by creating a dummy context
            // Constants will have the same min and max values
            let mut vars = crate::variables::Vars::default();
            let mut events = Vec::new();
            let ctx = crate::variables::views::Context::new(&mut vars, &mut events);

            let min_val = view.min(&ctx);
            let max_val = view.max(&ctx);

            if min_val == max_val {
                // This is a constant value
                let value = match min_val {
                    crate::variables::Val::ValI(i) => ConstraintValue::Integer(i),
                    crate::variables::Val::ValF(f) => ConstraintValue::Float(f),
                };
                ViewInfo::Constant { value }
            } else {
                // For now, mark complex views as such
                // A full implementation would detect transformations
                ViewInfo::Complex
            }
        }
    }

    // Create enhanced constraint methods with metadata collection

    /// Declare a new propagator to enforce `x <= y` with metadata collection.
    pub fn less_than_or_equals_with_metadata(&mut self, x: impl View, y: impl View) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType};

        let x_info = self.analyze_view(&x);
        let y_info = self.analyze_view(&y);
        let variables: Vec<_> = x
            .get_underlying_var()
            .into_iter()
            .chain(y.get_underlying_var())
            .collect();

        let metadata = ConstraintData::Binary {
            left: x_info,
            right: y_info,
        };

        self.push_new_prop_with_metadata(
            self::leq::LessThanOrEquals::new(x, y),
            ConstraintType::LessThanOrEquals,
            variables,
            metadata,
        )
    }

    /// Declare a type-aware propagator to enforce `x < y` with metadata collection.
    pub fn less_than_with_metadata(&mut self, x: impl View, y: impl View) -> PropId {
        use crate::optimization::constraint_metadata::{
            ConstraintData, ConstraintType, TransformationType, ViewInfo,
        };

        let x_info = self.analyze_view(&x);
        let y_info = self.analyze_view(&y);

        // For x < y implemented as x.next() <= y, we need to track the transformation
        let transformed_x_info = if let ViewInfo::Variable { var_id } = x_info {
            ViewInfo::Transformed {
                base_var: var_id,
                transformation: TransformationType::Next,
            }
        } else {
            ViewInfo::Complex
        };

        let variables: Vec<_> = x
            .get_underlying_var()
            .into_iter()
            .chain(y.get_underlying_var())
            .collect();

        let metadata = ConstraintData::Binary {
            left: transformed_x_info,
            right: y_info,
        };

        self.push_new_prop_with_metadata(
            self::leq::LessThanOrEquals::new(x.next(), y),
            ConstraintType::LessThan,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce `result = a AND b AND c AND ...`.
    /// All variables are treated as boolean: 0 = false, non-zero = true.
    pub fn bool_and(&mut self, operands: Vec<VarId>, result: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operand_infos: Vec<_> = operands
            .iter()
            .map(|&var_id| ViewInfo::Variable { var_id })
            .collect();

        let variables: Vec<_> = operands
            .iter()
            .cloned()
            .chain(std::iter::once(result))
            .collect();

        let metadata = ConstraintData::NAry {
            operands: operand_infos,
        };

        self.push_new_prop_with_metadata(
            self::bool_logic::BoolAnd::new(operands, result),
            ConstraintType::BooleanAnd,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce `result = a OR b OR c OR ...`.
    /// All variables are treated as boolean: 0 = false, non-zero = true.
    pub fn bool_or(&mut self, operands: Vec<VarId>, result: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operand_infos: Vec<_> = operands
            .iter()
            .map(|&var_id| ViewInfo::Variable { var_id })
            .collect();

        let variables: Vec<_> = operands
            .iter()
            .cloned()
            .chain(std::iter::once(result))
            .collect();

        let metadata = ConstraintData::NAry {
            operands: operand_infos,
        };

        self.push_new_prop_with_metadata(
            self::bool_logic::BoolOr::new(operands, result),
            ConstraintType::BooleanOr,
            variables,
            metadata,
        )
    }

    /// Declare a new propagator to enforce `result = NOT operand`.
    /// Variables are treated as boolean: 0 = false, non-zero = true.
    pub fn bool_not(&mut self, operand: VarId, result: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operand_info = ViewInfo::Variable { var_id: operand };
        let result_info = ViewInfo::Variable { var_id: result };

        let variables = vec![operand, result];

        let metadata = ConstraintData::Binary {
            left: operand_info,
            right: result_info,
        };

        self.push_new_prop_with_metadata(
            self::bool_logic::BoolNot::new(operand, result),
            ConstraintType::BooleanNot,
            variables,
            metadata,
        )
    }

    pub fn bool_xor(&mut self, x: VarId, y: VarId, result: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let x_info = ViewInfo::Variable { var_id: x };
        let y_info = ViewInfo::Variable { var_id: y };
        let result_info = ViewInfo::Variable { var_id: result };

        let variables = vec![x, y, result];

        let metadata = ConstraintData::NAry {
            operands: vec![x_info, y_info, result_info],
        };

        self.push_new_prop_with_metadata(
            self::bool_logic::BoolXor::new(x, y, result),
            ConstraintType::BooleanXor,
            variables,
            metadata,
        )
    }

    // ═══════════════════════════════════════════════════════════════════════
    // 🔄 Reification Constraints
    // ═══════════════════════════════════════════════════════════════════════

    /// Declare a reified equality constraint: `b ⇔ (x = y)`.
    ///
    /// The boolean variable `b` is 1 if and only if `x = y`.
    /// - If b = 1, then x must equal y
    /// - If b = 0, then x must not equal y
    /// - If x = y, then b must be 1
    /// - If x ≠ y, then b must be 0
    pub fn int_eq_reif(&mut self, x: VarId, y: VarId, b: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let x_info = ViewInfo::Variable { var_id: x };
        let y_info = ViewInfo::Variable { var_id: y };

        let variables = vec![x, y, b];

        let metadata = ConstraintData::Binary {
            left: x_info,
            right: y_info,
        };

        self.push_new_prop_with_metadata(
            self::reification::IntEqReif::new(x, y, b),
            ConstraintType::EqualityReified,
            variables,
            metadata,
        )
    }

    /// Declare a reified inequality constraint: `b ⇔ (x ≠ y)`.
    ///
    /// The boolean variable `b` is 1 if and only if `x ≠ y`.
    /// - If b = 1, then x must not equal y
    /// - If b = 0, then x must equal y
    /// - If x ≠ y, then b must be 1
    /// - If x = y, then b must be 0
    pub fn int_ne_reif(&mut self, x: VarId, y: VarId, b: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let x_info = ViewInfo::Variable { var_id: x };
        let y_info = ViewInfo::Variable { var_id: y };

        let variables = vec![x, y, b];

        let metadata = ConstraintData::Binary {
            left: x_info,
            right: y_info,
        };

        self.push_new_prop_with_metadata(
            self::reification::IntNeReif::new(x, y, b),
            ConstraintType::InequalityReified,
            variables,
            metadata,
        )
    }

    /// Declare a reified less-than constraint: `b ⇔ (x < y)`.
    ///
    /// The boolean variable `b` is 1 if and only if `x < y`.
    pub fn int_lt_reif(&mut self, x: VarId, y: VarId, b: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let x_info = ViewInfo::Variable { var_id: x };
        let y_info = ViewInfo::Variable { var_id: y };

        let variables = vec![x, y, b];

        let metadata = ConstraintData::Binary {
            left: x_info,
            right: y_info,
        };

        self.push_new_prop_with_metadata(
            self::reification::IntLtReif::new(x, y, b),
            ConstraintType::LessThanReified,
            variables,
            metadata,
        )
    }

    /// Declare a reified less-than-or-equal constraint: `b ⇔ (x ≤ y)`.
    ///
    /// The boolean variable `b` is 1 if and only if `x ≤ y`.
    pub fn int_le_reif(&mut self, x: VarId, y: VarId, b: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let x_info = ViewInfo::Variable { var_id: x };
        let y_info = ViewInfo::Variable { var_id: y };

        let variables = vec![x, y, b];

        let metadata = ConstraintData::Binary {
            left: x_info,
            right: y_info,
        };

        self.push_new_prop_with_metadata(
            self::reification::IntLeReif::new(x, y, b),
            ConstraintType::LessEqualReified,
            variables,
            metadata,
        )
    }

    /// Declare a reified greater-than constraint: `b ⇔ (x > y)`.
    ///
    /// The boolean variable `b` is 1 if and only if `x > y`.
    pub fn int_gt_reif(&mut self, x: VarId, y: VarId, b: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let x_info = ViewInfo::Variable { var_id: x };
        let y_info = ViewInfo::Variable { var_id: y };

        let variables = vec![x, y, b];

        let metadata = ConstraintData::Binary {
            left: x_info,
            right: y_info,
        };

        self.push_new_prop_with_metadata(
            self::reification::IntGtReif::new(x, y, b),
            ConstraintType::GreaterThanReified,
            variables,
            metadata,
        )
    }

    /// Declare a reified greater-than-or-equal constraint: `b ⇔ (x ≥ y)`.
    ///
    /// The boolean variable `b` is 1 if and only if `x ≥ y`.
    pub fn int_ge_reif(&mut self, x: VarId, y: VarId, b: VarId) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let x_info = ViewInfo::Variable { var_id: x };
        let y_info = ViewInfo::Variable { var_id: y };

        let variables = vec![x, y, b];

        let metadata = ConstraintData::Binary {
            left: x_info,
            right: y_info,
        };

        self.push_new_prop_with_metadata(
            self::reification::IntGeReif::new(x, y, b),
            ConstraintType::GreaterEqualReified,
            variables,
            metadata,
        )
    }

    // ═══════════════════════════════════════════════════════════════════════
    // Linear Constraint Propagators
    // ═══════════════════════════════════════════════════════════════════════

    /// Declare an integer linear equality constraint: `sum(coeffs[i] * vars[i]) = constant`.
    pub fn int_lin_eq(
        &mut self,
        coefficients: Vec<i32>,
        variables: Vec<VarId>,
        constant: i32,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<ViewInfo> = variables
            .iter()
            .map(|&v| ViewInfo::Variable { var_id: v })
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::linear::IntLinEq::new(coefficients, variables.clone(), constant),
            ConstraintType::Equals,
            variables,
            metadata,
        )
    }

    /// Declare an integer linear less-or-equal constraint: `sum(coeffs[i] * vars[i]) ≤ constant`.
    pub fn int_lin_le(
        &mut self,
        coefficients: Vec<i32>,
        variables: Vec<VarId>,
        constant: i32,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<ViewInfo> = variables
            .iter()
            .map(|&v| ViewInfo::Variable { var_id: v })
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::linear::IntLinLe::new(coefficients, variables.clone(), constant),
            ConstraintType::LessThanOrEquals,
            variables,
            metadata,
        )
    }

    /// Declare an integer linear not-equal constraint: `sum(coeffs[i] * vars[i]) ≠ constant`.
    pub fn int_lin_ne(
        &mut self,
        coefficients: Vec<i32>,
        variables: Vec<VarId>,
        constant: i32,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<ViewInfo> = variables
            .iter()
            .map(|&v| ViewInfo::Variable { var_id: v })
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::linear::IntLinNe::new(coefficients, variables.clone(), constant),
            ConstraintType::NotEquals,
            variables,
            metadata,
        )
    }

    /// Declare a reified integer linear equality constraint: `b ⟺ sum(coeffs[i] * vars[i]) = constant`.
    pub fn int_lin_eq_reif(
        &mut self,
        coefficients: Vec<i32>,
        variables: Vec<VarId>,
        constant: i32,
        reif_var: VarId,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let mut operands: Vec<ViewInfo> = variables
            .iter()
            .map(|&v| ViewInfo::Variable { var_id: v })
            .collect();
        operands.push(ViewInfo::Variable { var_id: reif_var });

        let metadata = ConstraintData::NAry { operands };

        let mut all_vars = variables.clone();
        all_vars.push(reif_var);

        self.push_new_prop_with_metadata(
            self::linear::IntLinEqReif::new(coefficients, variables, constant, reif_var),
            ConstraintType::EqualityReified,
            all_vars,
            metadata,
        )
    }

    /// Declare a reified integer linear less-or-equal constraint: `b ⟺ sum(coeffs[i] * vars[i]) ≤ constant`.
    pub fn int_lin_le_reif(
        &mut self,
        coefficients: Vec<i32>,
        variables: Vec<VarId>,
        constant: i32,
        reif_var: VarId,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let mut operands: Vec<ViewInfo> = variables
            .iter()
            .map(|&v| ViewInfo::Variable { var_id: v })
            .collect();
        operands.push(ViewInfo::Variable { var_id: reif_var });

        let metadata = ConstraintData::NAry { operands };

        let mut all_vars = variables.clone();
        all_vars.push(reif_var);

        self.push_new_prop_with_metadata(
            self::linear::IntLinLeReif::new(coefficients, variables, constant, reif_var),
            ConstraintType::InequalityReified,
            all_vars,
            metadata,
        )
    }

    /// Declare a reified integer linear not-equal constraint: `b ⟺ sum(coeffs[i] * vars[i]) ≠ constant`.
    pub fn int_lin_ne_reif(
        &mut self,
        coefficients: Vec<i32>,
        variables: Vec<VarId>,
        constant: i32,
        reif_var: VarId,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let mut operands: Vec<ViewInfo> = variables
            .iter()
            .map(|&v| ViewInfo::Variable { var_id: v })
            .collect();
        operands.push(ViewInfo::Variable { var_id: reif_var });

        let metadata = ConstraintData::NAry { operands };

        let mut all_vars = variables.clone();
        all_vars.push(reif_var);

        self.push_new_prop_with_metadata(
            self::linear::IntLinNeReif::new(coefficients, variables, constant, reif_var),
            ConstraintType::InequalityReified,
            all_vars,
            metadata,
        )
    }

    /// Declare a float linear equality constraint: `sum(coeffs[i] * vars[i]) = constant`.
    pub fn float_lin_eq(
        &mut self,
        coefficients: Vec<f64>,
        variables: Vec<VarId>,
        constant: f64,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<ViewInfo> = variables
            .iter()
            .map(|&v| ViewInfo::Variable { var_id: v })
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::linear::FloatLinEq::new(coefficients, variables.clone(), constant),
            ConstraintType::Equals,
            variables,
            metadata,
        )
    }

    /// Declare a float linear less-or-equal constraint: `sum(coeffs[i] * vars[i]) ≤ constant`.
    pub fn float_lin_le(
        &mut self,
        coefficients: Vec<f64>,
        variables: Vec<VarId>,
        constant: f64,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<ViewInfo> = variables
            .iter()
            .map(|&v| ViewInfo::Variable { var_id: v })
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::linear::FloatLinLe::new(coefficients, variables.clone(), constant),
            ConstraintType::LessThanOrEquals,
            variables,
            metadata,
        )
    }

    /// Declare a float linear not-equal constraint: `sum(coeffs[i] * vars[i]) ≠ constant`.
    pub fn float_lin_ne(
        &mut self,
        coefficients: Vec<f64>,
        variables: Vec<VarId>,
        constant: f64,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let operands: Vec<ViewInfo> = variables
            .iter()
            .map(|&v| ViewInfo::Variable { var_id: v })
            .collect();

        let metadata = ConstraintData::NAry { operands };

        self.push_new_prop_with_metadata(
            self::linear::FloatLinNe::new(coefficients, variables.clone(), constant),
            ConstraintType::NotEquals,
            variables,
            metadata,
        )
    }

    /// Declare a reified float linear equality constraint: `b ⟺ sum(coeffs[i] * vars[i]) = constant`.
    pub fn float_lin_eq_reif(
        &mut self,
        coefficients: Vec<f64>,
        variables: Vec<VarId>,
        constant: f64,
        reif_var: VarId,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let mut operands: Vec<ViewInfo> = variables
            .iter()
            .map(|&v| ViewInfo::Variable { var_id: v })
            .collect();
        operands.push(ViewInfo::Variable { var_id: reif_var });

        let metadata = ConstraintData::NAry { operands };

        let mut all_vars = variables.clone();
        all_vars.push(reif_var);

        self.push_new_prop_with_metadata(
            self::linear::FloatLinEqReif::new(coefficients, variables, constant, reif_var),
            ConstraintType::EqualityReified,
            all_vars,
            metadata,
        )
    }

    /// Declare a reified float linear less-or-equal constraint: `b ⟺ sum(coeffs[i] * vars[i]) ≤ constant`.
    pub fn float_lin_le_reif(
        &mut self,
        coefficients: Vec<f64>,
        variables: Vec<VarId>,
        constant: f64,
        reif_var: VarId,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let mut operands: Vec<ViewInfo> = variables
            .iter()
            .map(|&v| ViewInfo::Variable { var_id: v })
            .collect();
        operands.push(ViewInfo::Variable { var_id: reif_var });

        let metadata = ConstraintData::NAry { operands };

        let mut all_vars = variables.clone();
        all_vars.push(reif_var);

        self.push_new_prop_with_metadata(
            self::linear::FloatLinLeReif::new(coefficients, variables, constant, reif_var),
            ConstraintType::InequalityReified,
            all_vars,
            metadata,
        )
    }

    /// Declare a reified float linear not-equal constraint: `b ⟺ sum(coeffs[i] * vars[i]) ≠ constant`.
    pub fn float_lin_ne_reif(
        &mut self,
        coefficients: Vec<f64>,
        variables: Vec<VarId>,
        constant: f64,
        reif_var: VarId,
    ) -> PropId {
        use crate::optimization::constraint_metadata::{ConstraintData, ConstraintType, ViewInfo};

        let mut operands: Vec<ViewInfo> = variables
            .iter()
            .map(|&v| ViewInfo::Variable { var_id: v })
            .collect();
        operands.push(ViewInfo::Variable { var_id: reif_var });

        let metadata = ConstraintData::NAry { operands };

        let mut all_vars = variables.clone();
        all_vars.push(reif_var);

        self.push_new_prop_with_metadata(
            self::linear::FloatLinNeReif::new(coefficients, variables, constant, reif_var),
            ConstraintType::InequalityReified,
            all_vars,
            metadata,
        )
    }
}

/// Propagator handle that is not bound to a specific memory location.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct PropId(pub usize);

impl Index<PropId> for Vec<Box<dyn Prune>> {
    type Output = Box<dyn Prune>;

    fn index(&self, index: PropId) -> &Self::Output {
        &self[index.0]
    }
}

impl IndexMut<PropId> for Vec<Box<dyn Prune>> {
    fn index_mut(&mut self, index: PropId) -> &mut Self::Output {
        &mut self[index.0]
    }
}

// Public exports
#[doc(hidden)]
pub use alldiff::AllDiff;
#[doc(hidden)]
pub use allequal::AllEqual;
#[doc(hidden)]
pub use count::Count;