mathdoku 0.1.0

Generate and solve Mathdoku puzzles: grid representation, constraint propagation, solver, and generator
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
//! [`Puzzle`]: the top-level constraint-solving interface.
use crate::Error::MissingCell;
use crate::cage::Cage;
pub use crate::cage::CageOperator;
#[cfg(feature = "without-solution")]
use crate::cage::collinear_groups;
use crate::csp::{Constraint, generalized_arc_consistency};
use crate::fill::Fill;
use crate::grid::{AllDifferent, Grid as InternalGrid};
#[cfg(feature = "without-solution")]
use crate::mdd::CageDp;
#[cfg(feature = "without-solution")]
use crate::memo::Memo;
#[cfg(feature = "without-solution")]
use crate::operator::{CommutativeOperator, NonCommutativeOperator};
use crate::polyomino::{Cell, Polyomino};
#[cfg(feature = "without-solution")]
use crate::table::Table;
use crate::{Error, N, T};
use serde::de::Error as DeError;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::sync::Arc;

/// A Mathdoku puzzle: an n×n grid partitioned into cages, each with an arithmetic constraint.
#[derive(Clone, Debug)]
pub struct Puzzle {
    grid: InternalGrid,
    // INVARIANT: all k cells of a k-cell cage map to the same Arc<Cage> — one object, k aliases.
    // Never call Arc::make_mut on values in this map: when refcount > 1 it silently clones,
    // breaking the aliasing and producing k independent copies that diverge under propagation.
    // Propagation must follow replace-never-mutate: build a new Cage, then re-insert all k cells.
    cages: HashMap<Cell, Arc<Cage>>,
}

/// A constraint that applies to a [`Puzzle`]'s grid: either a cage or an all-different.
#[derive(Clone)]
enum PuzzleConstraint {
    Cage(Arc<Cage>),
    AllDifferent(AllDifferent),
}

impl std::fmt::Display for PuzzleConstraint {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Cage(cage) => write!(f, "{cage}"),
            Self::AllDifferent(ad) => write!(f, "{ad}"),
        }
    }
}

impl Constraint<InternalGrid, Cell, Fill, Error> for PuzzleConstraint {
    fn propagate(&self, state: &InternalGrid) -> Result<(InternalGrid, Vec<Cell>), Error> {
        match self {
            Self::Cage(cage) => cage.propagate(state),
            Self::AllDifferent(ad) => ad.propagate(state),
        }
    }

    fn in_scope(&self, variable: Cell) -> bool {
        match self {
            Self::Cage(cage) => cage.in_scope(variable),
            Self::AllDifferent(ad) => ad.in_scope(variable),
        }
    }
}

impl Puzzle {
    /// Creates an empty `n×n` puzzle with no cages.
    ///
    /// # Errors
    /// Returns [`Error::InvalidGridSize`] if `n` is not in `1..=9`.
    pub fn new(n: usize) -> Result<Self, Error> {
        Ok(Self {
            grid: InternalGrid::new(n)?,
            cages: HashMap::new(),
        })
    }

    /// Returns the grid size `n` (puzzle is `n×n`).
    #[must_use]
    pub const fn n(&self) -> usize {
        self.grid.size()
    }

    /// Returns `true` if every cell of the grid is covered by a cage.
    ///
    /// Cages are disjoint, so the cell-to-cage map covers the grid exactly
    /// when it has one entry per cell.
    #[must_use]
    pub fn is_fully_covered(&self) -> bool {
        self.cages.len() == self.n() * self.n()
    }

    /// Returns an iterator over the unique cages in this puzzle, sorted by anchor cell.
    pub fn cages(&self) -> impl Iterator<Item = &Cage> {
        let mut seen: HashSet<*const Cage> = HashSet::new();
        let mut cages: Vec<&Arc<Cage>> = self
            .cages
            .values()
            .filter(move |arc| seen.insert(Arc::as_ptr(arc)))
            .collect();
        cages.sort_by_key(|arc| arc.polyomino.iter().copied().min());
        cages.into_iter().map(Arc::as_ref)
    }

    /// Returns an iterator over all solutions for this puzzle.
    ///
    /// Each item is a solved [`Puzzle`] where every cell's fill is a singleton.
    pub fn solutions(&self) -> impl Iterator<Item = Result<Self, Error>> + '_ {
        crate::solutions::Solutions::new(self)
    }

    /// Returns the `(multiset, tuple)` counts of valid value assignments for
    /// the cage covering `polyomino`, given the current grid fills.
    ///
    /// A tuple assigns one value from `1..=n` to each cell in the cage in
    /// sorted cell order; it is counted when it jointly satisfies the cage's
    /// arithmetic constraint, collinear distinctness within the cage, and
    /// every cell's current candidate fill. A multiset is a tuple up to
    /// reordering. Counts are folded over the cage's memo (the exact tuple
    /// relation), so the cost is proportional to the memo, not `n^k`.
    ///
    /// # Errors
    /// Returns [`Error::MissingPolyomino`] if no cage covers `polyomino`.
    pub fn cage_viable_counts(&self, polyomino: &Polyomino) -> Result<(u64, u64), Error> {
        let cage_arc = polyomino
            .iter()
            .find_map(|cell| self.cages.get(cell))
            .filter(|arc| &arc.polyomino == polyomino)
            .ok_or_else(|| Error::MissingPolyomino(polyomino.clone()))?;
        let fills: Vec<Fill> = cage_arc
            .polyomino
            .iter()
            .map(|&cell| self.grid.get(cell))
            .collect::<Result<_, _>>()?;
        cage_arc.viable_counts(&fills)
    }

    /// Returns the cage whose polyomino exactly matches `polyomino`, or `None`.
    #[must_use]
    pub fn get_cage_at(&self, polyomino: &Polyomino) -> Option<&Cage> {
        self.cages
            .values()
            .find(|arc| &arc.polyomino == polyomino)
            .map(Arc::as_ref)
    }

    /// Returns the candidate fill for `cell`.
    ///
    /// # Errors
    ///
    /// Returns [`MissingCell`] if `cell` is not in the puzzle.
    pub fn get(&self, cell: Cell) -> Result<Fill, Error> {
        self.grid.get(cell)
    }

    /// # Errors
    ///
    /// Returns an error if `cell` is not in the puzzle or `n` is not a candidate value for it.
    #[allow(clippy::todo)]
    pub fn set(&self, cell: Cell, n: N) -> Result<Self, Error> {
        let fill = self.grid.get(cell)?;
        if !fill.contains(n) {
            return Err(Error::InvalidCellValue(cell, n));
        }
        Ok(Self {
            grid: self.grid.set(cell, Fill::from(&[n])),
            cages: self.cages.clone(),
        })
    }

    /// Returns a copy of the puzzle with a new cage added, propagated to a fixpoint.
    ///
    /// Returns `None` if the new cage makes the puzzle infeasible.
    ///
    /// # Errors
    ///
    /// Returns [`Error::MissingPolyomino`] if any cell of `polyomino` is not in the grid.
    /// Returns [`Error::CageConflict`] if `polyomino` overlaps an existing cage.
    /// Returns `Err(MissingPolyomino)` if any cell of `polyomino` is outside the grid.
    fn check_in_bounds(&self, polyomino: &Polyomino) -> Result<(), Error> {
        let n = self.grid.size();
        if polyomino
            .iter()
            .any(|&Cell(r, c)| r < 1 || r > n || c < 1 || c > n)
        {
            Err(Error::MissingPolyomino(polyomino.clone()))
        } else {
            Ok(())
        }
    }

    /// Returns a copy of the puzzle with a new cage added, propagated to a fixpoint.
    ///
    /// Returns `None` if the new cage makes the puzzle infeasible.
    ///
    /// # Errors
    ///
    /// Returns [`Error::MissingPolyomino`] if any cell of `polyomino` is not in the grid.
    /// Returns [`Error::CageConflict`] if `polyomino` overlaps an existing cage.
    pub fn insert(
        &self,
        polyomino: &Polyomino,
        operation: CageOperator,
        target: T,
    ) -> Result<Option<Self>, Error> {
        self.check_in_bounds(polyomino)?;
        let n =
            N::try_from(self.grid.size()).map_err(|_| Error::InvalidGridSize(self.grid.size()))?;

        // Check disjoint with every existing cage.
        let mut seen: HashSet<*const Cage> = HashSet::new();
        for arc in self.cages.values() {
            if seen.insert(Arc::as_ptr(arc)) && !arc.polyomino.is_disjoint(polyomino) {
                return Err(Error::CageConflict(polyomino.clone()));
            }
        }

        let cage = Cage::new(n, polyomino.clone(), operation, target)?;

        // Insert into a cloned cage map.
        let mut cages = self.cages.clone();
        let arc = Arc::new(cage);
        for &cell in polyomino.iter() {
            let _ = cages.insert(cell, Arc::clone(&arc));
        }

        Ok(Self {
            grid: self.grid.clone(),
            cages,
        }
        .fixpoint())
    }

    /// Returns a copy of the puzzle with `cage` removed.
    ///
    /// # Errors
    ///
    /// Returns an error if `cage` is not in the puzzle.
    pub fn remove(&self, cage: &Cage) -> Result<Option<Self>, Error> {
        let mut cages = self.cages.clone();
        for cell in cage.polyomino.iter() {
            let _ = cages.remove(cell).ok_or(MissingCell(*cell));
        }
        Ok(Self {
            grid: self.grid.clone(),
            cages,
        }
        .fixpoint())
    }

    /// Returns the operators that are feasible for `polyomino` given the current grid state.
    ///
    /// An operation is feasible if at least one target value exists that is consistent
    /// with the candidate fills of the polyomino's cells.
    ///
    /// # Errors
    ///
    /// Returns [`MissingCell`] if any cell of `polyomino` is not in the puzzle.
    #[cfg(feature = "without-solution")]
    pub fn possible_operations(&self, polyomino: &Polyomino) -> Result<Vec<CageOperator>, Error> {
        self.check_in_bounds(polyomino)?;
        let n =
            N::try_from(self.grid.size()).map_err(|_| Error::InvalidGridSize(self.grid.size()))?;
        let fills: Vec<Fill> = polyomino
            .iter()
            .map(|&cell| self.grid.get(cell))
            .collect::<Result<_, _>>()?;
        let k = N::try_from(fills.len()).unwrap_or(N::MAX);

        let candidates: &[CageOperator] = if k == 1 {
            &[CageOperator::Given]
        } else if k == 2 {
            &[
                CageOperator::Add,
                CageOperator::Subtract,
                CageOperator::Multiply,
                CageOperator::Divide,
            ]
        } else {
            &[CageOperator::Add, CageOperator::Multiply]
        };

        let result = candidates
            .iter()
            .copied()
            .filter(|&op| operator_is_feasible(self, polyomino, n, op, &fills))
            .collect();
        Ok(result)
    }

    /// Returns the target values that are feasible for `polyomino` under `operation`
    /// given the current grid state.
    ///
    /// A target is feasible if some assignment of values from the cells' candidate fills
    /// satisfies `operation` with that target.
    ///
    /// # Errors
    ///
    /// Returns [`MissingCell`] if any cell of `polyomino` is not in the puzzle.
    #[cfg(feature = "without-solution")]
    pub fn possible_targets(
        &self,
        polyomino: &Polyomino,
        operation: CageOperator,
    ) -> Result<Vec<T>, Error> {
        self.check_in_bounds(polyomino)?;
        let n =
            N::try_from(self.grid.size()).map_err(|_| Error::InvalidGridSize(self.grid.size()))?;
        let fills: Vec<Fill> = polyomino
            .iter()
            .map(|&cell| self.grid.get(cell))
            .collect::<Result<_, _>>()?;
        let Some(range) = target_range(operation, &fills) else {
            return Ok(vec![]);
        };
        let lines = collinear_groups(polyomino);
        let result = range
            .into_iter()
            .filter(|&target| {
                target_is_feasible(self, polyomino, n, operation, &fills, target, &lines)
            })
            .collect();
        Ok(result)
    }

    /// Propagates all cage and all-different constraints to a GAC fixpoint.
    ///
    /// Returns `None` if any cell's domain becomes empty (infeasible).
    #[must_use]
    pub fn fixpoint(&self) -> Option<Self> {
        let n = self.grid.size();
        // Deduplicate cages by pointer: each cage Arc is shared across all its cells.
        let mut seen: HashSet<*const Cage> = HashSet::new();
        let unique_cages: Vec<Arc<Cage>> = self
            .cages
            .values()
            .filter(|c| seen.insert(Arc::as_ptr(c)))
            .map(Arc::clone)
            .collect();
        let mut constraints: Vec<PuzzleConstraint> = unique_cages
            .iter()
            .map(|c| PuzzleConstraint::Cage(Arc::clone(c)))
            .collect();
        // Full-row and full-column all-different constraints.
        for i in 1..=n {
            constraints.push(PuzzleConstraint::AllDifferent(AllDifferent::row(n, i)));
            constraints.push(PuzzleConstraint::AllDifferent(AllDifferent::column(n, i)));
        }
        let grid = generalized_arc_consistency(self.grid.clone(), &constraints)?;
        Some(Self {
            grid,
            cages: self.cages.clone(),
        })
    }
}

/// Deduplicated cage keys for equality and hashing: `(polyomino, operator, target)`.
fn cage_keys(p: &Puzzle) -> Vec<(Polyomino, CageOperator, T)> {
    let mut seen = HashSet::new();
    p.cages
        .values()
        .filter(|arc| seen.insert(Arc::as_ptr(arc)))
        .map(|arc| {
            let (op, target) = arc.op_target();
            (arc.polyomino.clone(), op, target)
        })
        .collect()
}

impl PartialEq for Puzzle {
    fn eq(&self, other: &Self) -> bool {
        if self.n() != other.n() {
            return false;
        }
        let mut a = cage_keys(self);
        let mut b = cage_keys(other);
        a.sort_unstable();
        b.sort_unstable();
        a == b
    }
}

impl Eq for Puzzle {}

impl Hash for Puzzle {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.n().hash(state);
        #[allow(clippy::collection_is_never_read)]
        let mut keys = cage_keys(self);
        keys.sort_unstable();
        keys.hash(state);
    }
}

impl std::fmt::Display for Puzzle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let n = self.n();
        let count = self.cages().count();
        write!(f, "{n}×{n} puzzle, {count} cages")
    }
}

// Serde wire format: cage list keyed by operator/target/polyomino, plus optional grid state.
#[derive(Serialize, Deserialize)]
struct CageWire {
    polyomino: Vec<Cell>,
    operation: CageOperator,
    target: T,
}

#[derive(Serialize, Deserialize)]
struct PuzzleWire {
    n: usize,
    #[serde(default)]
    cages: Vec<CageWire>,
}

impl Serialize for Puzzle {
    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
        let n = self.n();
        let mut cages: Vec<CageWire> = {
            let mut seen: HashSet<*const Cage> = HashSet::new();
            self.cages
                .values()
                .filter(|arc| seen.insert(Arc::as_ptr(arc)))
                .map(|arc| {
                    let (operation, target) = cage_op_target(arc);
                    CageWire {
                        polyomino: arc.polyomino.iter().copied().collect(),
                        operation,
                        target,
                    }
                })
                .collect()
        };
        cages.sort_by_key(|c| c.polyomino.iter().copied().min());
        PuzzleWire { n, cages }.serialize(s)
    }
}

/// Extracts the `(CageOperator, T)` from a cage's support.
fn cage_op_target(cage: &Cage) -> (CageOperator, T) {
    cage.op_target()
}

impl<'de> Deserialize<'de> for Puzzle {
    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
        let wire = PuzzleWire::deserialize(d)?;
        let mut puzzle = Self::new(wire.n).map_err(|e| DeError::custom(e.to_string()))?;
        for cage_wire in wire.cages {
            let polyomino =
                Polyomino::from(cage_wire.polyomino).map_err(|e| DeError::custom(e.to_string()))?;
            puzzle = puzzle
                .insert(&polyomino, cage_wire.operation, cage_wire.target)
                .map_err(|e| DeError::custom(e.to_string()))?
                .ok_or_else(|| DeError::custom("infeasible cage"))?;
        }
        Ok(puzzle)
    }
}

impl Puzzle {
    /// Creates a puzzle with singleton fills from a Latin square.
    ///
    /// Each cell in `square[r][c]` (0-indexed) is inserted as a `Given` cage,
    /// producing a fully-constrained puzzle where every cell's fill is a singleton.
    ///
    /// # Errors
    /// Returns an error if `n` is invalid, any cell value is out of range, or
    /// the values do not form a valid Latin square (duplicate in a row or column).
    pub fn from_latin_square(n: usize, square: &[Vec<N>]) -> Result<Self, Error> {
        let mut puzzle = Self::new(n)?;
        for (r, row) in square.iter().enumerate() {
            for (c, &v) in row.iter().enumerate() {
                let cell = Cell::new(r, c);
                let poly = Polyomino::from([cell])?;
                puzzle = puzzle
                    .insert(&poly, CageOperator::Given, T::from(v))?
                    .ok_or(Error::EmptyFills)?;
            }
        }
        Ok(puzzle)
    }

    /// Inserts a cage for `polyomino` with `op` and `target`.
    ///
    /// This is an alias for [`Puzzle::insert`] that keeps the old call convention.
    ///
    /// # Errors
    /// Returns an error if the polyomino is out of bounds or overlaps an existing cage.
    pub fn insert_cage(&self, cage: &Cage) -> Result<Option<Self>, Error> {
        let (op, target) = cage.op_target();
        self.insert(&cage.polyomino, op, target)
    }

    /// Removes the cage for `polyomino`.
    ///
    /// This is an alias for [`Puzzle::remove`] that keeps the old call convention.
    ///
    /// # Errors
    /// Returns an error if the cage is not in the puzzle.
    pub fn remove_cage(&self, cage: &Cage) -> Result<Option<Self>, Error> {
        self.remove(cage)
    }
}

/// Returns all operators valid for `polyomino`'s size (without domain-based filtering).
#[must_use]
pub fn operators_for(polyomino: &Polyomino) -> Vec<CageOperator> {
    match polyomino.len() {
        0 => vec![],
        1 => vec![CageOperator::Given],
        2 => vec![
            CageOperator::Add,
            CageOperator::Subtract,
            CageOperator::Multiply,
            CageOperator::Divide,
        ],
        _ => vec![CageOperator::Add, CageOperator::Multiply],
    }
}

/// Returns the tight target range for `op` derived from the fills' actual min/max values.
/// Returns `None` if any fill is empty or no valid target exists.
#[cfg(feature = "without-solution")]
fn target_range(op: CageOperator, fills: &[Fill]) -> Option<std::ops::RangeInclusive<T>> {
    let mins: Option<Vec<T>> = fills.iter().map(|f| f.min_value().map(T::from)).collect();
    let maxs: Option<Vec<T>> = fills.iter().map(|f| f.max_value().map(T::from)).collect();
    let mins = mins?;
    let maxs = maxs?;
    match op {
        CageOperator::Given => Some(mins[0]..=maxs[0]),
        CageOperator::Add => Some(mins.iter().sum()..=maxs.iter().sum()),
        CageOperator::Multiply => Some(mins.iter().product()..=maxs.iter().product()),
        CageOperator::Subtract => {
            let max_val = maxs[0].max(maxs[1]);
            let min_val = mins[0].min(mins[1]);
            let hi = max_val - min_val;
            if hi == 0 { None } else { Some(1..=hi) }
        }
        CageOperator::Divide => {
            let max_val = maxs[0].max(maxs[1]);
            let min_val = mins[0].min(mins[1]);
            let hi = max_val / min_val;
            if hi < 2 { None } else { Some(2..=hi) }
        }
    }
}

/// Returns true if `op` with some target is feasible for `polyomino` in `puzzle`.
///
/// For each target in the fill-derived range: checks for a tuple consistent
/// with the fills, and if one exists checks the fixpoint. The collinear lines
/// are target-independent, so they are computed once before the scan.
#[cfg(feature = "without-solution")]
fn operator_is_feasible(
    puzzle: &Puzzle,
    polyomino: &Polyomino,
    n: N,
    op: CageOperator,
    fills: &[Fill],
) -> bool {
    let Some(range) = target_range(op, fills) else {
        return false;
    };
    let lines = collinear_groups(polyomino);
    range
        .into_iter()
        .any(|target| target_is_feasible(puzzle, polyomino, n, op, fills, target, &lines))
}

/// Returns true if `op` with `target` is feasible: some tuple consistent with
/// the fills exists and inserting the cage yields a non-empty fixpoint.
///
/// The commutative arms drive the cage DP lazily and exit at the first
/// witness; no diagram is built or narrowed. `lines` is the polyomino's
/// collinear grouping (see [`collinear_groups`]), hoisted to the caller
/// because it is the same for every target.
///
/// The closing insert-and-fixpoint check is a load-bearing postcondition, not
/// just a filter: the designer's `feasible_op_targets`
/// (`apps/designer/src/feasibility.rs`) skips its own re-insert for
/// non-coverage-completing candidates on the strength of every surviving
/// `(op, target)` having already passed it here. Weakening or removing it
/// would silently admit infeasible pairs there; the designer's
/// `mid_build_results_match_filtering_through_is_globally_feasible` test
/// guards the equivalence.
#[cfg(feature = "without-solution")]
fn target_is_feasible(
    puzzle: &Puzzle,
    polyomino: &Polyomino,
    n: N,
    op: CageOperator,
    fills: &[Fill],
    target: T,
    lines: &[Vec<usize>],
) -> bool {
    let k = N::try_from(fills.len()).unwrap_or(N::MAX);
    let has_consistent_tuple = match op {
        CageOperator::Given => N::try_from(target).is_ok_and(|v| fills[0].contains(v)),
        CageOperator::Add => CageDp::new(n, k, CommutativeOperator::Add, target, lines)
            .solutions(fills)
            .next()
            .is_some(),
        CageOperator::Multiply => CageDp::new(n, k, CommutativeOperator::Multiply, target, lines)
            .solutions(fills)
            .next()
            .is_some(),
        CageOperator::Subtract => {
            Table::non_commutative(n, NonCommutativeOperator::Subtract, target)
                .is_ok_and(|t| t.narrow(fills).is_ok())
        }
        CageOperator::Divide => Table::non_commutative(n, NonCommutativeOperator::Divide, target)
            .is_ok_and(|t| t.narrow(fills).is_ok()),
    };
    has_consistent_tuple
        && puzzle
            .insert(polyomino, op, target)
            .ok()
            .flatten()
            .is_some()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::operator::CommutativeOperator::Add;
    use crate::operator::NonCommutativeOperator::Subtract;
    use crate::polyomino::Polyomino;

    #[test]
    fn add_cage_arm_cells_exclude_values_requiring_collinear_duplicates() {
        crate::init_debug_logging();
        // L-shape in a 7×7: corner=(1,1), arm1=(1,2), arm2=(2,1), target=6.
        //
        // For arm1 (1,2) to hold 4, the remaining two cells must sum to 2,
        // which forces corner=1 and arm2=1. But corner and arm2 share column 1,
        // violating AllDifferent. Likewise for arm2 (2,1) holding 4.
        // Only the corner (1,1) can hold 4, via the tuple (4,1,1) where the
        // two 1s sit at non-collinear arm cells.
        let p = Puzzle::new(4).unwrap();
        let poly = Polyomino::from([Cell(1, 1), Cell(1, 2), Cell(2, 1)]).unwrap();
        let p = p.insert(&poly, CageOperator::Add, 6).unwrap().unwrap();
        let corner = p.get(Cell(1, 1)).unwrap();
        let arm1 = p.get(Cell(1, 2)).unwrap();
        let arm2 = p.get(Cell(2, 1)).unwrap();
        assert!(
            corner.contains(4),
            "corner (1,1) should admit 4 via tuple (4,1,1); got {corner}"
        );
        assert!(
            !arm1.contains(4),
            "arm (1,2) cannot be 4: forces two collinear 1s at (1,1) and (2,1); got {arm1}"
        );
        assert!(
            !arm2.contains(4),
            "arm (2,1) cannot be 4: forces two collinear 1s at (1,1) and (1,2); got {arm2}"
        );
    }

    // ---- cage_viable_counts ----

    #[test]
    fn cage_viable_counts_add_domino_respects_arithmetic() {
        // Regression for the brute-force enumeration that ignored the cage's
        // arithmetic: Add(5) in a 4×4 has exactly 4 tuples — (1,4),(2,3),
        // (3,2),(4,1) — and 2 multisets, not the 12 distinct pairs the fills
        // alone admit.
        let p = Puzzle::new(4).unwrap();
        let poly = domino(1, 1, 1, 2);
        let p = p.insert(&poly, CageOperator::Add, 5).unwrap().unwrap();
        assert_eq!(p.cage_viable_counts(&poly).unwrap(), (2, 4));
    }

    #[test]
    fn cage_viable_counts_l_cage_matches_mdd() {
        // The +6 L-cage in 4×4: six orderings of {1,2,3} plus (4,1,1) at the
        // corner — 7 tuples, 2 multisets (matches Mdd::tuples()).
        let p = Puzzle::new(4).unwrap();
        let poly = Polyomino::from([Cell(1, 1), Cell(1, 2), Cell(2, 1)]).unwrap();
        let p = p.insert(&poly, CageOperator::Add, 6).unwrap().unwrap();
        assert_eq!(p.cage_viable_counts(&poly).unwrap(), (2, 7));
    }

    #[test]
    fn cage_viable_counts_narrows_with_pinned_cell() {
        // Pin (1,1)=4 in an Add(5) domino: only (4,1) survives.
        let p = Puzzle::new(4).unwrap();
        let poly = domino(1, 1, 1, 2);
        let p = p.insert(&poly, CageOperator::Add, 5).unwrap().unwrap();
        let p = p.set(Cell(1, 1), 4).unwrap();
        assert_eq!(p.cage_viable_counts(&poly).unwrap(), (1, 1));
    }

    #[test]
    fn cage_viable_counts_subtract_counts_table_pairs() {
        // Subtract 1 in 4×4: (1,2),(2,1),(2,3),(3,2),(3,4),(4,3) — 6 tuples,
        // 3 multisets.
        let p = Puzzle::new(4).unwrap();
        let poly = domino(1, 1, 1, 2);
        let p = p.insert(&poly, CageOperator::Subtract, 1).unwrap().unwrap();
        assert_eq!(p.cage_viable_counts(&poly).unwrap(), (3, 6));
    }

    #[test]
    fn cage_viable_counts_given_is_single_tuple() {
        let p = Puzzle::new(4).unwrap();
        let poly = Polyomino::from([Cell(1, 1)]).unwrap();
        let p = p.insert(&poly, CageOperator::Given, 3).unwrap().unwrap();
        assert_eq!(p.cage_viable_counts(&poly).unwrap(), (1, 1));
    }

    #[test]
    fn cage_viable_counts_missing_cage_returns_error() {
        let p = Puzzle::new(4).unwrap();
        assert!(matches!(
            p.cage_viable_counts(&domino(1, 1, 1, 2)),
            Err(Error::MissingPolyomino(_))
        ));
    }

    /// Perf regression: an 8-cell (2×4) Add cage in a 9×9. The deleted brute
    /// force enumerated `9^8 ≈ 4×10^7` value combinations here (and `9^12`
    /// for a 3×4 cage — it never finished); the memo fold is proportional to
    /// the diagram.
    #[test]
    fn perf_cage_viable_counts_fat_cage_in_9x9() {
        let cells: Vec<Cell> = (1..=2)
            .flat_map(|r| (1..=4).map(move |c| Cell(r, c)))
            .collect();
        let poly = Polyomino::from(cells).unwrap();
        let p = Puzzle::new(9).unwrap();
        let p = p.insert(&poly, CageOperator::Add, 40).unwrap().unwrap();
        let (multisets, tuples) = p.cage_viable_counts(&poly).unwrap();
        assert!(multisets >= 1);
        assert!(tuples >= multisets);
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_targets_given_singleton() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = Polyomino::from([Cell(1, 1)]).unwrap();
        let targets = p.possible_targets(&poly, CageOperator::Given).unwrap();
        assert_eq!(targets, vec![1, 2, 3, 4]);
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_targets_add_domino() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = domino(1, 1, 1, 2);
        let targets = p.possible_targets(&poly, CageOperator::Add).unwrap();
        // Pairs from {1,2,3,4} with distinct values: sums 3..=7
        assert!(targets.contains(&3));
        assert!(targets.contains(&5));
        assert!(targets.contains(&7));
        assert!(!targets.contains(&1));
        assert!(!targets.contains(&2));
        assert!(!targets.contains(&8));
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_targets_subtract_excludes_zero() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = domino(1, 1, 1, 2);
        let targets = p.possible_targets(&poly, CageOperator::Subtract).unwrap();
        assert!(!targets.is_empty());
        assert!(!targets.contains(&0));
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_targets_divide_starts_at_two() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = domino(1, 1, 1, 2);
        let targets = p.possible_targets(&poly, CageOperator::Divide).unwrap();
        assert!(!targets.is_empty());
        assert!(!targets.contains(&1));
        assert!(targets.iter().all(|&t| t >= 2));
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_targets_multiply_domino() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = domino(1, 1, 1, 2);
        let targets = p.possible_targets(&poly, CageOperator::Multiply).unwrap();
        // Valid products of distinct pairs from {1,2,3,4}: 2,3,4,6,8,12
        assert!(targets.contains(&2));
        assert!(targets.contains(&6));
        assert!(targets.contains(&12));
        // 1 = 1×1 (equal values, forbidden by AllDifferent)
        assert!(!targets.contains(&1));
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_targets_narrows_with_constrained_cell() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = domino(1, 1, 1, 2);
        let all_targets = p.possible_targets(&poly, CageOperator::Add).unwrap();
        // Pin cell (1,1) to 1; Add targets must include 1 in the pair, so max sum is 1+4=5
        let p_pinned = p.set(Cell(1, 1), 1).unwrap();
        let pinned_targets = p_pinned.possible_targets(&poly, CageOperator::Add).unwrap();
        assert!(pinned_targets.len() < all_targets.len());
        assert!(!pinned_targets.contains(&7)); // 3+4=7, not reachable when cell is pinned to 1
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_targets_missing_cell_error() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        // Cell (5,1) is out of a 4×4 grid
        let poly = Polyomino::from([Cell(5, 1)]).unwrap();
        assert!(p.possible_targets(&poly, CageOperator::Given).is_err());
    }

    impl Puzzle {
        fn from_parts(grid: InternalGrid, cage_list: Vec<Cage>) -> Self {
            let mut cages: HashMap<Cell, Arc<Cage>> = HashMap::new();
            for cage in cage_list {
                let arc = Arc::new(cage);
                for &cell in arc.polyomino.iter() {
                    let _ = cages.insert(cell, Arc::clone(&arc));
                }
            }
            Self { grid, cages }
        }
    }

    fn domino(r0: usize, c0: usize, r1: usize, c1: usize) -> Polyomino {
        Polyomino::from([Cell(r0, c0), Cell(r1, c1)]).unwrap()
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_operations_size_10_returns_only_commutative() {
        // A 10-cell snake across two columns of a 9×9 grid: col 1 rows 1–5,
        // col 2 rows 5–9. No row contains more than 2 cage cells, so AllDifferent
        // is satisfiable. k > 2 so only Add and Multiply are candidates.
        let mut cells: Vec<Cell> = (1..=5).map(|r| Cell(r, 1)).collect();
        cells.extend((5..=9).map(|r| Cell(r, 2)));
        let poly = Polyomino::from(cells).unwrap();
        let p = Puzzle::from_parts(InternalGrid::new(9).unwrap(), vec![]);
        let ops = p.possible_operations(&poly).unwrap();
        assert!(ops.iter().any(|o| matches!(o, CageOperator::Add)));
        assert!(ops.iter().any(|o| matches!(o, CageOperator::Multiply)));
        assert!(!ops.iter().any(|o| matches!(o, CageOperator::Subtract)));
        assert!(!ops.iter().any(|o| matches!(o, CageOperator::Divide)));
        assert!(!ops.iter().any(|o| matches!(o, CageOperator::Given)));
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_operations_singleton_returns_only_given() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = Polyomino::from([Cell(1, 1)]).unwrap();
        let ops = p.possible_operations(&poly).unwrap();
        assert_eq!(ops.len(), 1);
        assert!(matches!(ops[0], CageOperator::Given));
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_operations_domino_includes_all_four() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = domino(1, 1, 1, 2);
        let ops = p.possible_operations(&poly).unwrap();
        assert!(ops.iter().any(|o| matches!(o, CageOperator::Add)));
        assert!(ops.iter().any(|o| matches!(o, CageOperator::Subtract)));
        assert!(ops.iter().any(|o| matches!(o, CageOperator::Multiply)));
        assert!(ops.iter().any(|o| matches!(o, CageOperator::Divide)));
    }

    #[test]
    fn possible_operations_divide_never_produces_target_one() {
        // Divide target 1 would require max(a,b)/min(a,b)=1, i.e. a==b,
        // which all-different forbids. Cage::new rejects target < 2 for Divide
        // before even building the tuple table.
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = domino(1, 1, 1, 2);
        // Insert a Divide cage with target 1 — must be an error, not Ok(Some(_)).
        assert!(
            p.insert(&poly, CageOperator::Divide, 1).is_err(),
            "Divide target 1 must be rejected as infeasible"
        );
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_operations_triomino_excludes_non_commutative() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = Polyomino::from([Cell(1, 1), Cell(1, 2), Cell(1, 3)]).unwrap();
        let ops = p.possible_operations(&poly).unwrap();
        assert!(ops.iter().any(|o| matches!(o, CageOperator::Add)));
        assert!(ops.iter().any(|o| matches!(o, CageOperator::Multiply)));
        assert!(!ops.iter().any(|o| matches!(o, CageOperator::Subtract)));
        assert!(!ops.iter().any(|o| matches!(o, CageOperator::Divide)));
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_operations_returns_error_for_out_of_grid_cell() {
        let p = Puzzle::from_parts(InternalGrid::new(2).unwrap(), vec![]);
        let poly = Polyomino::from([Cell(9, 9)]).unwrap();
        assert!(matches!(
            p.possible_operations(&poly),
            Err(Error::MissingPolyomino(_))
        ));
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_operations_given_only_returns_values_in_fill() {
        // Pin (1,1)=3; cell (1,2) loses 3 from its fill via AllDifferent.
        // Singleton poly on (1,2): Given is feasible (other values remain), but
        // specifically Given=3 is not, so possible_operations still includes Given
        // (some target exists). What matters: all returned ops are actually usable.
        let c1 = Cage::given(Cell(1, 1), 3).unwrap();
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![c1])
            .fixpoint()
            .unwrap();
        let poly = Polyomino::from([Cell(1, 2)]).unwrap();
        let ops = p.possible_operations(&poly).unwrap();
        // Given is still feasible because values other than 3 remain in the fill.
        assert!(ops.iter().any(|o| matches!(o, CageOperator::Given)));
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_operations_given_not_feasible_when_fill_empty() {
        // Force a 2×2 grid to become infeasible for a specific cell by
        // contradicting both row and column. Pin (1,1)=1 and (1,2)=2 — cell (2,1)
        // loses 1, cell (2,2) loses 2 via AllDifferent. Pin (2,1)=2 makes
        // (2,2) lose 2 again (already gone) and (1,2)'s row forces (2,2) to lose
        // 2 from column. For a clean empty-fill test: use a 2×2 and fill (1,1)
        // with empty fill directly via the grid internals, check Given is excluded.
        // Simpler: build a puzzle state where AllDifferent fully pins a cell,
        // leaving it with exactly one candidate, and check that Given returns
        // only that one value as a feasible operator.
        let c1 = Cage::given(Cell(1, 1), 1).unwrap();
        let c2 = Cage::given(Cell(1, 2), 2).unwrap();
        // In a 2×2 grid, pinning row 1 forces row 2: (2,1)={2}, (2,2)={1}.
        let p = Puzzle::from_parts(InternalGrid::new(2).unwrap(), vec![c1, c2])
            .fixpoint()
            .unwrap();
        // Cell (2,1) must be {2}; Given is feasible (target=2 is in fill).
        let poly = Polyomino::from([Cell(2, 1)]).unwrap();
        let ops = p.possible_operations(&poly).unwrap();
        assert!(ops.iter().any(|o| matches!(o, CageOperator::Given)));
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_operations_subtract_excluded_in_2x2_with_only_one_unit_pair() {
        // In a 2×2 grid the subtract target range is [1, 1]. Pin (1,3)…
        // Actually: in a 2×2 the only subtract target is 1. If we pin (1,1)=1 via a
        // given cage, AllDifferent forces (1,2)={2} and (2,1)={2}. Now the uncaged
        // domino (1,2)-(2,2): (1,2)={2} (forced by col 2 after (2,2)?). Actually (2,2)
        // is still {1,2}. The domino (1,2)-(2,2) has fills {2} and {1,2}. The only
        // subtract tuple consistent with fills is (2,1): |2-1|=1, which is in [1,1].
        // So subtract IS feasible. Verified: on a fresh 2×2 all ops on a domino work.
        // The structural rules (singleton→Given only, k>2→commutative only) are the
        // primary exclusion mechanism; fill-based exclusion requires unusual cell states.
        // Test that the result is exactly {Given} for a singleton in a constrained state:
        let c1 = Cage::given(Cell(1, 1), 1).unwrap();
        let p = Puzzle::from_parts(InternalGrid::new(2).unwrap(), vec![c1])
            .fixpoint()
            .unwrap();
        // (2,2) in a 2×2 after pinning (1,1)=1: AllDifferent forces (1,2)={2},(2,1)={2}.
        // Then (2,2) must be {1} (forced by col 2: (1,2)=2, and row 2: (2,1)=2).
        let poly = Polyomino::from([Cell(2, 2)]).unwrap();
        let ops = p.possible_operations(&poly).unwrap();
        assert_eq!(ops.len(), 1);
        assert!(matches!(ops[0], CageOperator::Given));
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_operations_fixpoint_check_excludes_infeasible_operator() {
        // In a 2×2 grid, (1,1) and (1,2) form a domino. Pin (2,1)=1 and (2,2)=2.
        // AllDifferent on col 1 removes 1 from (1,1); col 2 removes 2 from (1,2).
        // So (1,1) ∈ {2} and (1,2) ∈ {1}. An Add cage with target 3 = 2+1 is feasible.
        // An Add cage with target 4 would need 2+2 or 3+1, but (1,1)={2} and (1,2)={1},
        // so no tuple sums to 4 — but that's a Tuples check, not a fixpoint check.
        // For the fixpoint exclusion: inserting Given=3 on (1,1) which has fill {2}
        // should make the cage infeasible (3 ∉ {2}), returning None from insert.
        let c1 = Cage::given(Cell(2, 1), 1).unwrap();
        let c2 = Cage::given(Cell(2, 2), 2).unwrap();
        let p = Puzzle::from_parts(InternalGrid::new(2).unwrap(), vec![c1, c2])
            .fixpoint()
            .unwrap();
        // (1,1) is forced to {2} by col 1; (1,2) forced to {1} by col 2.
        assert_eq!(p.get(Cell(1, 1)).unwrap(), Fill::from(&[2]));
        assert_eq!(p.get(Cell(1, 2)).unwrap(), Fill::from(&[1]));
        // Singleton on (1,1): only Given=2 is feasible (Given=1 is not in fill).
        let poly = Polyomino::from([Cell(1, 1)]).unwrap();
        let ops = p.possible_operations(&poly).unwrap();
        assert_eq!(ops.len(), 1);
        assert!(matches!(ops[0], CageOperator::Given));
        // Verify Given=2 actually inserts successfully.
        assert!(p.insert(&poly, CageOperator::Given, 2).unwrap().is_some());
    }

    #[test]
    fn insert_cage_pins_cell() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = Polyomino::from([Cell(1, 1)]).unwrap();
        let fp = p.insert(&poly, CageOperator::Given, 3).unwrap().unwrap();
        assert_eq!(fp.get(Cell(1, 1)).unwrap(), Fill::from(&[3]));
    }

    #[test]
    fn insert_missing_polyomino_returns_error() {
        let p = Puzzle::from_parts(InternalGrid::new(2).unwrap(), vec![]);
        let poly = Polyomino::from([Cell(9, 9)]).unwrap();
        assert!(matches!(
            p.insert(&poly, CageOperator::Given, 1),
            Err(Error::MissingPolyomino(_))
        ));
    }

    #[test]
    fn insert_overlapping_cage_returns_error() {
        let cage = Cage::given(Cell(1, 1), 1).unwrap();
        let p = Puzzle::from_parts(InternalGrid::new(2).unwrap(), vec![cage]);
        let poly = Polyomino::from([Cell(1, 1)]).unwrap();
        assert!(matches!(
            p.insert(&poly, CageOperator::Given, 2),
            Err(Error::CageConflict(_))
        ));
    }

    #[test]
    fn insert_infeasible_cage_returns_none() {
        // pin (1,1)=1 and (1,2)=1 in a 2×2 — AllDifferent makes it infeasible
        let p = Puzzle::from_parts(InternalGrid::new(2).unwrap(), vec![]);
        let p = p
            .insert(
                &Polyomino::from([Cell(1, 1)]).unwrap(),
                CageOperator::Given,
                1,
            )
            .unwrap()
            .unwrap();
        let poly = Polyomino::from([Cell(1, 2)]).unwrap();
        assert!(p.insert(&poly, CageOperator::Given, 1).unwrap().is_none());
    }

    #[test]
    fn insert_add_cage_prunes_cells() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = domino(1, 1, 1, 2);
        let fp = p.insert(&poly, CageOperator::Add, 3).unwrap().unwrap();
        assert_eq!(fp.get(Cell(1, 1)).unwrap(), Fill::from(&[1, 2]));
        assert_eq!(fp.get(Cell(1, 2)).unwrap(), Fill::from(&[1, 2]));
    }

    #[test]
    fn insert_multiply_cage_prunes_cells() {
        // Multiply 6 in a 4×4: valid pairs are (1,6)—out of range—(2,3),(3,2). So both {2,3}.
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = domino(1, 1, 1, 2);
        let fp = p.insert(&poly, CageOperator::Multiply, 6).unwrap().unwrap();
        assert_eq!(fp.get(Cell(1, 1)).unwrap(), Fill::from(&[2, 3]));
        assert_eq!(fp.get(Cell(1, 2)).unwrap(), Fill::from(&[2, 3]));
    }

    #[test]
    fn insert_subtract_cage_prunes_cells() {
        // Subtract 3 in a 4×4: only valid pair is (4,1)/(1,4). Both cells narrow to {1,4}.
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = domino(1, 1, 1, 2);
        let fp = p.insert(&poly, CageOperator::Subtract, 3).unwrap().unwrap();
        assert_eq!(fp.get(Cell(1, 1)).unwrap(), Fill::from(&[1, 4]));
        assert_eq!(fp.get(Cell(1, 2)).unwrap(), Fill::from(&[1, 4]));
    }

    #[test]
    fn insert_divide_cage_prunes_cells() {
        // Divide 4 in a 4×4: only valid pair is (4,1)/(1,4). Both cells narrow to {1,4}.
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = domino(1, 1, 1, 2);
        let fp = p.insert(&poly, CageOperator::Divide, 4).unwrap().unwrap();
        assert_eq!(fp.get(Cell(1, 1)).unwrap(), Fill::from(&[1, 4]));
        assert_eq!(fp.get(Cell(1, 2)).unwrap(), Fill::from(&[1, 4]));
    }

    #[test]
    fn insert_does_not_affect_unrelated_cells() {
        // Adding a cage to (1,1) should leave (2,2) at its full candidate set.
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = Polyomino::from([Cell(1, 1)]).unwrap();
        let fp = p.insert(&poly, CageOperator::Given, 3).unwrap().unwrap();
        assert_eq!(fp.get(Cell(2, 2)).unwrap(), Fill::all(4));
    }

    #[test]
    fn insert_cell_at_boundary_succeeds() {
        // (n, n) is a valid cell; inserting a cage there should work.
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = Polyomino::from([Cell(4, 4)]).unwrap();
        assert!(p.insert(&poly, CageOperator::Given, 4).unwrap().is_some());
    }

    #[test]
    fn insert_cell_row_zero_returns_missing_polyomino() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = Polyomino::from([Cell(0, 1)]).unwrap();
        assert!(matches!(
            p.insert(&poly, CageOperator::Given, 1),
            Err(Error::MissingPolyomino(_))
        ));
    }

    #[test]
    fn insert_cell_col_zero_returns_missing_polyomino() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let poly = Polyomino::from([Cell(1, 0)]).unwrap();
        assert!(matches!(
            p.insert(&poly, CageOperator::Given, 1),
            Err(Error::MissingPolyomino(_))
        ));
    }

    #[test]
    fn get_returns_full_fill_for_unconstrained_cell() {
        let p = Puzzle::from_parts(InternalGrid::new(3).unwrap(), vec![]);
        assert_eq!(p.get(Cell(2, 2)).unwrap(), Fill::all(3));
    }

    #[test]
    fn get_missing_cell_returns_error() {
        let p = Puzzle::from_parts(InternalGrid::new(3).unwrap(), vec![]);
        assert!(matches!(p.get(Cell(9, 9)), Err(MissingCell(_))));
    }

    #[test]
    fn set_pins_cell_to_value() {
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![]);
        let p2 = p.set(Cell(1, 1), 3).unwrap();
        assert_eq!(p2.get(Cell(1, 1)).unwrap(), Fill::from(&[3]));
    }

    #[test]
    fn set_invalid_value_returns_error() {
        // Pin (1,1) to {2} first, then try to set it to 3.
        let cage = Cage::given(Cell(1, 1), 2).unwrap();
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![cage]);
        let p = p.fixpoint().unwrap();
        assert!(matches!(
            p.set(Cell(1, 1), 3),
            Err(Error::InvalidCellValue(_, 3))
        ));
    }

    #[test]
    fn fixpoint_no_cages_full_grid_unchanged() {
        // With no cages and a full grid, AllDifferent has nothing to prune.
        let p = Puzzle::from_parts(InternalGrid::new(2).unwrap(), vec![]);
        let fp = p.fixpoint().unwrap();
        assert_eq!(fp.get(Cell(1, 1)).unwrap(), Fill::all(2));
        assert_eq!(fp.get(Cell(1, 2)).unwrap(), Fill::all(2));
    }

    #[test]
    fn fixpoint_given_cage_pins_cell() {
        // A given cage for value 3 must narrow cell(1,1) to {3}.
        let cage = Cage::given(Cell(1, 1), 3).unwrap();
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![cage]);
        let fp = p.fixpoint().unwrap();
        assert_eq!(fp.get(Cell(1, 1)).unwrap(), Fill::from(&[3]));
    }

    #[test]
    fn fixpoint_given_cage_propagates_through_all_different() {
        // Given cage pins cell(1,1)={2}; AllDifferent for row 1 must then remove
        // 2 from every other cell in that row.
        let cage = Cage::given(Cell(1, 1), 2).unwrap();
        let p = Puzzle::from_parts(InternalGrid::new(3).unwrap(), vec![cage]);
        let fp = p.fixpoint().unwrap();
        assert_eq!(fp.get(Cell(1, 1)).unwrap(), Fill::from(&[2]));
        assert!(!fp.get(Cell(1, 2)).unwrap().contains(2));
        assert!(!fp.get(Cell(1, 3)).unwrap().contains(2));
        // Column 1 also loses 2 from all other cells.
        assert!(!fp.get(Cell(2, 1)).unwrap().contains(2));
        assert!(!fp.get(Cell(3, 1)).unwrap().contains(2));
    }

    #[test]
    fn fixpoint_add_cage_prunes_both_cells() {
        // Add 3 in a 4×4: only pairs (1,2),(2,1) satisfy it, so both cells narrow to {1,2}.
        let cage = Cage::commutative(4, domino(1, 1, 1, 2), Add, 3).unwrap();
        let p = Puzzle::from_parts(InternalGrid::new(4).unwrap(), vec![cage]);
        let fp = p.fixpoint().unwrap();
        assert_eq!(fp.get(Cell(1, 1)).unwrap(), Fill::from(&[1, 2]));
        assert_eq!(fp.get(Cell(1, 2)).unwrap(), Fill::from(&[1, 2]));
    }

    #[test]
    fn fixpoint_cage_and_all_different_chain() {
        // 2×2 grid: subtract cage on column 1 with target 1 allows (1,2),(2,1).
        // Both cells can be 1 or 2. AllDifferent on each row then pins the partner cells.
        let cage = Cage::non_commutative(2, domino(1, 1, 2, 1), Subtract, 1).unwrap();
        let p = Puzzle::from_parts(InternalGrid::new(2).unwrap(), vec![cage]);
        // Should be feasible and not panic.
        assert!(p.fixpoint().is_some());
    }

    #[test]
    fn is_fully_covered_empty_puzzle_is_false() {
        let p = Puzzle::new(2).unwrap();
        assert!(!p.is_fully_covered());
    }

    #[test]
    fn is_fully_covered_partial_coverage_is_false() {
        let p = Puzzle::new(2)
            .unwrap()
            .insert(
                &Polyomino::from([Cell(1, 1)]).unwrap(),
                CageOperator::Given,
                1,
            )
            .unwrap()
            .unwrap();
        assert!(!p.is_fully_covered());
    }

    #[test]
    fn is_fully_covered_full_coverage_is_true() {
        let square: Vec<Vec<N>> = vec![vec![1, 2], vec![2, 1]];
        let p = Puzzle::from_latin_square(2, &square).unwrap();
        assert!(p.is_fully_covered());
    }

    #[test]
    fn fixpoint_infeasible_returns_none() {
        // Two given cages both claiming value 1 in the same row: infeasible.
        let c1 = Cage::given(Cell(1, 1), 1).unwrap();
        let c2 = Cage::given(Cell(1, 2), 1).unwrap();
        let p = Puzzle::from_parts(InternalGrid::new(2).unwrap(), vec![c1, c2]);
        assert!(p.fixpoint().is_none());
    }

    /// A 4×4 with an Add domino at (1,1)-(1,2) and a Given at (2,1).
    fn two_cage_puzzle() -> (Puzzle, Polyomino, Polyomino) {
        let add = domino(1, 1, 1, 2);
        let given = Polyomino::from([Cell(2, 1)]).unwrap();
        let p = Puzzle::new(4)
            .unwrap()
            .insert(&add, CageOperator::Add, 5)
            .unwrap()
            .unwrap()
            .insert(&given, CageOperator::Given, 3)
            .unwrap()
            .unwrap();
        (p, add, given)
    }

    #[test]
    fn cages_yields_unique_cages_sorted_by_anchor() {
        let (p, add, given) = two_cage_puzzle();
        let polys: Vec<Polyomino> = p.cages().map(|c| c.polyomino.clone()).collect();
        // Each multi-cell cage appears once, ordered by minimum cell.
        assert_eq!(polys, vec![add, given]);
    }

    #[test]
    fn get_cage_at_exact_polyomino_returns_cage() {
        let (p, add, _) = two_cage_puzzle();
        let cage = p.get_cage_at(&add).unwrap();
        assert_eq!(cage.polyomino, add);
    }

    #[test]
    fn get_cage_at_unknown_polyomino_returns_none() {
        let (p, _, _) = two_cage_puzzle();
        assert!(p.get_cage_at(&domino(3, 3, 3, 4)).is_none());
    }

    #[test]
    fn remove_drops_cage_but_keeps_grid_state() {
        let (p, add, _) = two_cage_puzzle();
        let cage = p.get_cage_at(&add).unwrap().clone();
        let removed = p.remove(&cage).unwrap().unwrap();
        assert!(removed.get_cage_at(&add).is_none());
        // The grid keeps its narrowed fills: the Add cage had pruned 2 from
        // (1,2) (no pair (2,?) sums to 5 once (1,1) lost 3 to the Given's
        // column), and removal does not widen.
        assert_eq!(removed.get(Cell(1, 2)).unwrap(), p.get(Cell(1, 2)).unwrap());
    }

    #[test]
    fn remove_cage_alias_matches_remove() {
        let (p, add, _) = two_cage_puzzle();
        let cage = p.get_cage_at(&add).unwrap().clone();
        let removed = p.remove_cage(&cage).unwrap().unwrap();
        assert!(removed.get_cage_at(&add).is_none());
    }

    #[test]
    fn insert_cage_alias_matches_insert() {
        let p = Puzzle::new(4).unwrap();
        let cage = Cage::new(4, domino(1, 1, 1, 2), CageOperator::Add, 5).unwrap();
        let inserted = p.insert_cage(&cage).unwrap().unwrap();
        assert!(inserted.get_cage_at(&domino(1, 1, 1, 2)).is_some());
    }

    #[test]
    fn eq_ignores_insertion_order() {
        let add = domino(1, 1, 1, 2);
        let given = Polyomino::from([Cell(2, 1)]).unwrap();
        let a = Puzzle::new(4)
            .unwrap()
            .insert(&add, CageOperator::Add, 5)
            .unwrap()
            .unwrap()
            .insert(&given, CageOperator::Given, 3)
            .unwrap()
            .unwrap();
        let b = Puzzle::new(4)
            .unwrap()
            .insert(&given, CageOperator::Given, 3)
            .unwrap()
            .unwrap()
            .insert(&add, CageOperator::Add, 5)
            .unwrap()
            .unwrap();
        assert_eq!(a, b);
    }

    #[test]
    fn eq_distinguishes_grid_size() {
        assert_ne!(Puzzle::new(3).unwrap(), Puzzle::new(4).unwrap());
    }

    #[test]
    fn eq_distinguishes_cage_targets() {
        let poly = domino(1, 1, 1, 2);
        let a = Puzzle::new(4)
            .unwrap()
            .insert(&poly, CageOperator::Add, 5)
            .unwrap()
            .unwrap();
        let b = Puzzle::new(4)
            .unwrap()
            .insert(&poly, CageOperator::Add, 6)
            .unwrap()
            .unwrap();
        assert_ne!(a, b);
    }

    #[test]
    fn hash_equal_for_equal_puzzles() {
        use std::collections::hash_map::DefaultHasher;
        let hash = |p: &Puzzle| {
            let mut h = DefaultHasher::new();
            p.hash(&mut h);
            h.finish()
        };
        let (a, _, _) = two_cage_puzzle();
        let (b, _, _) = two_cage_puzzle();
        assert_eq!(hash(&a), hash(&b));
    }

    #[test]
    fn display_reports_size_and_cage_count() {
        let (p, _, _) = two_cage_puzzle();
        assert_eq!(p.to_string(), "4×4 puzzle, 2 cages");
    }

    #[test]
    fn serde_round_trip_preserves_puzzle() {
        let (p, _, _) = two_cage_puzzle();
        let json = serde_json::to_string(&p).unwrap();
        let back: Puzzle = serde_json::from_str(&json).unwrap();
        assert_eq!(p, back);
    }

    #[test]
    fn serialize_orders_cages_by_anchor() {
        let (p, _, _) = two_cage_puzzle();
        let v: serde_json::Value = serde_json::to_value(&p).unwrap();
        assert_eq!(v["n"], 4);
        let cages = v["cages"].as_array().unwrap();
        assert_eq!(cages.len(), 2);
        assert_eq!(cages[0]["operation"], "Add");
        assert_eq!(cages[1]["operation"], "Given");
    }

    #[test]
    fn deserialize_invalid_grid_size_errors() {
        assert!(serde_json::from_str::<Puzzle>(r#"{"n":0,"cages":[]}"#).is_err());
    }

    #[test]
    fn deserialize_disconnected_polyomino_errors() {
        let json = r#"{"n":4,"cages":[{"polyomino":[[1,1],[3,3]],"operation":"Add","target":5}]}"#;
        assert!(serde_json::from_str::<Puzzle>(json).is_err());
    }

    #[test]
    fn deserialize_overlapping_cages_errors() {
        let json = r#"{"n":4,"cages":[
            {"polyomino":[[1,1]],"operation":"Given","target":1},
            {"polyomino":[[1,1]],"operation":"Given","target":2}
        ]}"#;
        assert!(serde_json::from_str::<Puzzle>(json).is_err());
    }

    #[test]
    fn deserialize_infeasible_cage_errors() {
        // Two Givens claiming 1 in the same row: the second insert propagates
        // to an empty domain, surfaced as a custom "infeasible cage" error.
        let json = r#"{"n":2,"cages":[
            {"polyomino":[[1,1]],"operation":"Given","target":1},
            {"polyomino":[[1,2]],"operation":"Given","target":1}
        ]}"#;
        let err = serde_json::from_str::<Puzzle>(json).unwrap_err();
        assert!(err.to_string().contains("infeasible cage"));
    }

    #[test]
    fn operators_for_singleton_is_given() {
        let poly = Polyomino::from([Cell(1, 1)]).unwrap();
        assert_eq!(operators_for(&poly), vec![CageOperator::Given]);
    }

    #[test]
    fn operators_for_domino_is_all_four() {
        assert_eq!(
            operators_for(&domino(1, 1, 1, 2)),
            vec![
                CageOperator::Add,
                CageOperator::Subtract,
                CageOperator::Multiply,
                CageOperator::Divide,
            ]
        );
    }

    #[test]
    fn operators_for_triomino_is_commutative_only() {
        let poly = Polyomino::from([Cell(1, 1), Cell(1, 2), Cell(1, 3)]).unwrap();
        assert_eq!(
            operators_for(&poly),
            vec![CageOperator::Add, CageOperator::Multiply]
        );
    }

    /// A 4×4 where both cells of the (1,1)-(1,2) domino are pinned to 2 via
    /// `set` (no propagation), so subtract/divide target ranges are empty.
    #[cfg(feature = "without-solution")]
    fn equal_pinned_domino() -> (Puzzle, Polyomino) {
        let p = Puzzle::new(4)
            .unwrap()
            .set(Cell(1, 1), 2)
            .unwrap()
            .set(Cell(1, 2), 2)
            .unwrap();
        (p, domino(1, 1, 1, 2))
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_targets_subtract_empty_when_range_collapses() {
        // |2-2| = 0 is not a valid subtract target, so the range is empty.
        let (p, poly) = equal_pinned_domino();
        assert_eq!(
            p.possible_targets(&poly, CageOperator::Subtract).unwrap(),
            Vec::<T>::new()
        );
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_targets_divide_empty_when_range_collapses() {
        // 2/2 = 1 < 2, the minimum divide target, so the range is empty.
        let (p, poly) = equal_pinned_domino();
        assert_eq!(
            p.possible_targets(&poly, CageOperator::Divide).unwrap(),
            Vec::<T>::new()
        );
    }

    #[cfg(feature = "without-solution")]
    #[test]
    fn possible_operations_excludes_ops_with_empty_target_range() {
        let (p, poly) = equal_pinned_domino();
        let ops = p.possible_operations(&poly).unwrap();
        assert!(!ops.contains(&CageOperator::Subtract));
        assert!(!ops.contains(&CageOperator::Divide));
    }
}