demystify 0.4.0

A constraint solving tool for explaining puzzles
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
/// This module contains the definitions and implementations related to JSON serialization and deserialization for the demystify library.
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};

use anyhow::Context;
use itertools::Itertools;
use serde::{Deserialize, Serialize};

use crate::problem::{
    PuzLit, VarValPair,
    parse::{EdgeSide, LtAxis, PuzzleParse, ShowRole},
    solver::PuzzleSolver,
};

/// Convert a 2D clue matrix (outer = side entry, inner = padded-with-trailing-zeros clue slots)
/// into layered border labels. Non-zero values in each row are right-aligned across layers so
/// the last clue ends up on the layer nearest the grid. Empty leading layers are trimmed.
/// Returns an empty Vec if every row is all zeros.
fn clue_matrix_to_layers(clues: &[Vec<i64>]) -> Vec<Vec<String>> {
    let max_clues = clues
        .iter()
        .map(|row| row.iter().filter(|&&v| v > 0).count())
        .max()
        .unwrap_or(0);
    if max_clues == 0 {
        return Vec::new();
    }
    let mut layers: Vec<Vec<String>> = vec![vec![String::new(); clues.len()]; max_clues];
    for (r, row) in clues.iter().enumerate() {
        let non_zero: Vec<i64> = row.iter().copied().filter(|&v| v > 0).collect();
        let offset = max_clues - non_zero.len();
        for (k, v) in non_zero.into_iter().enumerate() {
            layers[offset + k][r] = v.to_string();
        }
    }
    layers
}

/// Read a `$#SHOW` name as a 2-D `Option<i64>` matrix, falling back to
/// known PuzLits when the name is a find/aux variable rather than a given
/// parameter.  Mystify uses this path: every `puz_*` matrix is a `find`
/// var whose values arrive at render-time via injected known lits, not via
/// a `letting` block.
fn read_2d_option_i64(
    pp: &PuzzleParse,
    known: &BTreeSet<PuzLit>,
    name: &str,
) -> anyhow::Result<Vec<Vec<Option<i64>>>> {
    if pp.eprime.has_param(name) {
        return pp.eprime.param_vec_vec_option_i64(name);
    }
    if !pp.eprime.vars.contains(name) && !pp.eprime.auxvars.contains(name) {
        anyhow::bail!("$#SHOW name '{name}' is neither a parameter nor a find/aux variable");
    }
    let dims = pp
        .get_matrix_indices(name)
        .with_context(|| format!("variable '{name}' has no shape information for rendering"))?;
    if dims.len() != 2 {
        anyhow::bail!(
            "$#SHOW '{name}': expected 2-D matrix, got {} dimensions",
            dims.len()
        );
    }
    let h = dims[0].max(0) as usize;
    let w = dims[1].max(0) as usize;
    let mut grid = vec![vec![None; w]; h];
    for lit in known {
        if !lit.sign() || lit.var().name() != name {
            continue;
        }
        let lit_var = lit.var();
        let idx = lit_var.indices();
        if idx.len() != 2 {
            continue;
        }
        let r = (idx[0] - 1) as usize;
        let c = (idx[1] - 1) as usize;
        if r < h && c < w {
            grid[r][c] = Some(lit.val());
        }
    }
    Ok(grid)
}

/// Read a `$#SHOW` name as a 2-D `i64` matrix.  Same dispatch as
/// [`read_2d_option_i64`] but cells without a known lit default to 0.
fn read_2d_i64(
    pp: &PuzzleParse,
    known: &BTreeSet<PuzLit>,
    name: &str,
) -> anyhow::Result<Vec<Vec<i64>>> {
    if pp.eprime.has_param(name) {
        return pp.eprime.param_vec_vec_i64(name);
    }
    let m = read_2d_option_i64(pp, known, name)?;
    Ok(m.into_iter()
        .map(|row| row.into_iter().map(|c| c.unwrap_or(0)).collect())
        .collect())
}

/// Read a `$#SHOW` name as a 1-D `i64` vector.
fn read_1d_i64(pp: &PuzzleParse, known: &BTreeSet<PuzLit>, name: &str) -> anyhow::Result<Vec<i64>> {
    if pp.eprime.has_param(name) {
        return pp.eprime.param_vec_i64(name);
    }
    if !pp.eprime.vars.contains(name) && !pp.eprime.auxvars.contains(name) {
        anyhow::bail!("$#SHOW name '{name}' is neither a parameter nor a find/aux variable");
    }
    let dims = pp
        .get_matrix_indices(name)
        .with_context(|| format!("variable '{name}' has no shape information for rendering"))?;
    if dims.len() != 1 {
        anyhow::bail!(
            "$#SHOW '{name}': expected 1-D vector, got {} dimensions",
            dims.len()
        );
    }
    let n = dims[0].max(0) as usize;
    let mut out = vec![0; n];
    for lit in known {
        if !lit.sign() || lit.var().name() != name {
            continue;
        }
        let lit_var = lit.var();
        let idx = lit_var.indices();
        if idx.len() != 1 {
            continue;
        }
        let i = (idx[0] - 1) as usize;
        if i < n {
            out[i] = lit.val();
        }
    }
    Ok(out)
}

/// Read a `$#SHOW` name as a scalar `i64`.
fn read_scalar_i64(pp: &PuzzleParse, known: &BTreeSet<PuzLit>, name: &str) -> anyhow::Result<i64> {
    if pp.eprime.has_param(name) {
        return pp.eprime.param_i64(name);
    }
    for lit in known {
        if lit.sign() && lit.var().name() == name && lit.var().indices().is_empty() {
            return Ok(lit.val());
        }
    }
    anyhow::bail!(
        "$#SHOW name '{name}': scalar has no value (not a parameter, and no \
         known equality literal found)"
    )
}

/// Read a 2-D `String` matrix.  Used for `side_labels`-shaped params.
fn read_2d_string(
    pp: &PuzzleParse,
    known: &BTreeSet<PuzLit>,
    name: &str,
) -> anyhow::Result<Vec<Vec<String>>> {
    if pp.eprime.has_param(name) {
        return pp.eprime.param_vec_vec_string(name);
    }
    let m = read_2d_i64(pp, known, name)?;
    Ok(m.into_iter()
        .map(|row| row.into_iter().map(|c| c.to_string()).collect())
        .collect())
}

/// Read an edge-labels parameter, returning the layered-labels representation
/// the renderer expects.  Accepts two shapes:
///
/// - a 1-D vector: produces a single layer of stringified entries.
/// - a 2-D matrix (e.g. nonogram clue runs with trailing-zero padding):
///   produces multiple layers via [`clue_matrix_to_layers`].
///
/// Returns `None` if the param is the zero-only matrix shape (all rows empty),
/// matching the legacy "no labels to render" behaviour.
fn read_edge_labels(
    pp: &PuzzleParse,
    known: &BTreeSet<PuzLit>,
    name: &str,
) -> anyhow::Result<Option<Vec<Vec<String>>>> {
    // Try matrix shape first (numeric clue grids).
    let dims = if pp.eprime.has_param(name) {
        // Probe the param shape: vec_vec_i64 errors out for 1-D params.
        pp.eprime.param_vec_vec_i64(name).ok().map(|_| 2)
    } else {
        pp.get_matrix_indices(name).map(|d| d.len())
    };
    if let Some(2) = dims {
        let m = read_2d_i64(pp, known, name)?;
        let layers = clue_matrix_to_layers(&m);
        return Ok(if layers.is_empty() {
            None
        } else {
            Some(layers)
        });
    }
    // 1-D fallback: vec_string for params (preserves any string entries),
    // stringified i64 for find vars.  By convention, an integer value of
    // `-1` means "no clue here" — hide the label by mapping it to "".
    let blank_if_neg_one = |s: String| -> String { if s == "-1" { String::new() } else { s } };
    if pp.eprime.has_param(name) {
        let labels = pp.eprime.param_vec_string(name)?;
        return Ok(Some(vec![
            labels.into_iter().map(blank_if_neg_one).collect(),
        ]));
    }
    let v = read_1d_i64(pp, known, name)?;
    Ok(Some(vec![
        v.iter().map(|x| blank_if_neg_one(x.to_string())).collect(),
    ]))
}

/// Build the list of `ConstraintShape`s for the constraints in `constraint_num`.
/// Cells are extracted from each constraint's scope, filtered to the main `$#SHOW`
/// var (so non-grid auxiliaries don't leak in), kind detected, and stagger
/// assigned per row/col group.
fn build_constraint_shapes(
    solver: &PuzzleSolver,
    constraint_num: &HashMap<String, usize>,
    allowed_names: &HashSet<String>,
) -> Vec<ConstraintShape> {
    let mut shapes: Vec<ConstraintShape> = Vec::with_capacity(constraint_num.len());
    for (name, &idx) in constraint_num.iter() {
        let scope = solver.puzzleparse().constraint_scope(name);
        let cells: BTreeSet<[i64; 2]> = scope
            .iter()
            .filter(|p| allowed_names.contains(p.var().name()))
            .filter_map(|p| {
                let i = p.var().indices();
                if i.len() == 2 && i[0] >= 1 && i[1] >= 1 {
                    Some([i[0] - 1, i[1] - 1])
                } else {
                    None
                }
            })
            .collect();
        if cells.is_empty() {
            continue;
        }
        let cells: Vec<[i64; 2]> = cells.into_iter().collect();
        let kind = detect_constraint_shape_kind(&cells);
        shapes.push(ConstraintShape {
            idx,
            kind,
            cells,
            stagger: 0,
        });
    }
    shapes.sort_by_key(|s| s.idx);

    // Stagger assignment: group Row constraints by row index, Col by column,
    // assign 0, +1, -1, +2, -2, ... in shape-idx order.  Pair and Region get 0.
    let mut row_groups: BTreeMap<i64, Vec<usize>> = BTreeMap::new();
    let mut col_groups: BTreeMap<i64, Vec<usize>> = BTreeMap::new();
    for (vec_pos, shape) in shapes.iter().enumerate() {
        match shape.kind {
            ConstraintShapeKind::Row => {
                row_groups
                    .entry(shape.cells[0][0])
                    .or_default()
                    .push(vec_pos);
            }
            ConstraintShapeKind::Col => {
                col_groups
                    .entry(shape.cells[0][1])
                    .or_default()
                    .push(vec_pos);
            }
            _ => {}
        }
    }
    for indices in row_groups.values().chain(col_groups.values()) {
        for (slot, &vec_pos) in indices.iter().enumerate() {
            shapes[vec_pos].stagger = stagger_slot(slot);
        }
    }
    shapes
}

/// 0, +1, -1, +2, -2, ...
fn stagger_slot(n: usize) -> i32 {
    let half = (n as i32 + 1) / 2;
    if n.is_multiple_of(2) { half } else { -half }
}

fn detect_constraint_shape_kind(cells: &[[i64; 2]]) -> ConstraintShapeKind {
    if cells.is_empty() {
        return ConstraintShapeKind::Region;
    }
    let same_row = cells.iter().all(|c| c[0] == cells[0][0]);
    if same_row {
        return ConstraintShapeKind::Row;
    }
    let same_col = cells.iter().all(|c| c[1] == cells[0][1]);
    if same_col {
        return ConstraintShapeKind::Col;
    }
    if cells.len() == 2 {
        return ConstraintShapeKind::Pair;
    }
    ConstraintShapeKind::Region
}

/// One instantiated constraint from a `$#CON` class, with the grid cells it covers.
#[derive(Clone, PartialOrd, Ord, Hash, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct ConstraintInstance {
    /// Rendered human-readable description of this constraint instance.
    pub description: String,
    /// Grid cells (0-indexed [row, col]) that this constraint's scope covers.
    pub cells: Vec<[i64; 2]>,
}

#[derive(Clone, PartialOrd, Ord, Hash, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct Puzzle {
    pub kind: String,
    pub width: i64,
    pub height: i64,
    pub start_grid: Option<Vec<Vec<Option<i64>>>>,
    pub solution_grid: Option<Vec<Vec<Option<i64>>>>,
    pub cages: Option<Vec<Vec<Option<i64>>>>,
    /// Per-cell colour-region IDs (`Some(k)` with `k >= 1`; `None` = uncoloured).
    /// Rendered as a per-colour cell tint with no borders. See `ShowRole::RegionTint`.
    #[serde(default)]
    pub region_tint: Option<Vec<Vec<Option<i64>>>>,
    /// Border labels on each side. Outer vec is layer depth (0 = furthest from grid for
    /// top/left, 0 = nearest grid for bottom/right). Inner vec runs along the side
    /// (row index for top/bottom_labels, col index for left/right_labels). Depth-1 layer
    /// vectors cover the single-number case (Kakurasu, Skyscrapers). Multi-layer is used
    /// for Nonogram clue lists.
    pub top_labels: Option<Vec<Vec<String>>>,
    pub bottom_labels: Option<Vec<Vec<String>>>,
    pub left_labels: Option<Vec<Vec<String>>>,
    pub right_labels: Option<Vec<Vec<String>>>,
    /// Thermometer paths: each thermometer is an ordered list of [row, col] (0-indexed), bulb first.
    pub thermometers: Option<Vec<Vec<[i64; 2]>>>,
    /// Less-than constraints: each entry is [r1, c1, r2, c2] (0-indexed), meaning cell (r1,c1) < cell (r2,c2).
    pub less_than: Option<Vec<[i64; 4]>>,
    /// Cage sums indexed by cage ID (1-indexed): cage_sums[cage_id - 1] = target sum.
    pub cage_sums: Option<Vec<i64>>,
    /// Lines from `$#INFO` directives in the .eprime file.
    pub info: Option<Vec<String>>,
    /// All instantiated constraints grouped by their `$#CON` class name.
    /// Built once at puzzle-load time; templates rendered in parse.rs, not here.
    pub constraint_classes: Option<BTreeMap<String, Vec<ConstraintInstance>>>,
    /// SVG decoration flags from `$#DEC` directives (e.g. "sudoku_grid", "blank_input_val=2").
    #[serde(default)]
    pub decorations: Vec<String>,
}

impl Puzzle {
    /// Build a [`Puzzle`] from a parsed model with no known literals.  Use
    /// this when you don't have a [`PuzzleSolver`] handy (mostly tests and
    /// unit tests).  All `$#SHOW` directives whose name resolves to a
    /// `find` variable will produce empty matrices, since there's no known
    /// state to read values from.
    pub fn new_from_puzzle(problem: &PuzzleParse) -> anyhow::Result<Puzzle> {
        Self::new_from_puzzle_and_known(problem, &BTreeSet::new())
    }

    /// Build a [`Puzzle`] from a parsed model plus a set of known PuzLits.
    /// `known` is consulted whenever a `$#SHOW` directive names a `find`
    /// or `aux` variable rather than a `given` parameter — this is the
    /// path mystify uses to render `puz_*` clue values that are injected
    /// at runtime via [`PuzzleSolver::add_not_provable_known_lit`].
    pub fn new_from_puzzle_and_known(
        problem: &PuzzleParse,
        known: &BTreeSet<PuzLit>,
    ) -> anyhow::Result<Puzzle> {
        let kind = problem.eprime.kind.clone().unwrap_or("Unknown".to_string());

        // The renderer treats `cells[i][j]` as `cells[row][col]`, so
        // `puzzle.height = dims[0]` and `puzzle.width = dims[1]` of the
        // main `$#SHOW` var's matrix.  Param-named `width` / `height` are
        // model-internal — kakuro puts `width` on index[0], opposite the
        // usual convention — so only the main var's shape is authoritative.
        let main_show = problem
            .eprime
            .show
            .iter()
            .find(|d| d.role == ShowRole::Main)
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "model has no `$#SHOW <var> main` directive — required for rendering"
                )
            })?;
        let dims = problem
            .get_matrix_indices(&main_show.var)
            .with_context(|| format!("main var '{}' has no shape information", main_show.var))?;
        anyhow::ensure!(
            dims.len() == 2,
            "main var '{}' must be a 2-D matrix for rendering, got {} dimensions",
            main_show.var,
            dims.len()
        );
        let height = dims[0];
        let width = dims[1];

        let mut start_grid = None;
        let mut cages = None;
        let mut region_tint = None;

        let mut top_labels = None;
        let mut bottom_labels = None;
        let mut left_labels = None;
        let mut right_labels = None;

        // Renderer roles are driven entirely by `$#SHOW` directives now;
        // there are no longer any magic-name fallbacks (`fixed`, `cages`,
        // `start_grid`, etc.).  See `ShowRole` in parse.rs.
        let show = &problem.eprime.show;
        let find_role = |pred: &dyn Fn(&ShowRole) -> bool| -> Option<&str> {
            show.iter().find(|d| pred(&d.role)).map(|d| d.var.as_str())
        };

        // Edge labels: vector of strings (or a 2-D clue matrix) per side.
        let edge_param = |side: EdgeSide| -> Option<String> {
            find_role(&|r| matches!(r, ShowRole::Edge { side: s } if *s == side))
                .map(str::to_string)
        };
        if let Some(p) = edge_param(EdgeSide::Top) {
            top_labels = read_edge_labels(problem, known, &p)?;
        }
        if let Some(p) = edge_param(EdgeSide::Left) {
            left_labels = read_edge_labels(problem, known, &p)?;
        }
        if let Some(p) = edge_param(EdgeSide::Bottom) {
            bottom_labels = read_edge_labels(problem, known, &p)?;
        }
        if let Some(p) = edge_param(EdgeSide::Right) {
            right_labels = read_edge_labels(problem, known, &p)?;
        }

        // Combined four-side labels: a [side, slot] matrix in left/top/right/
        // bottom order.  Overrides individual edge directives if present.
        if let Some(p) = find_role(&|r| matches!(r, ShowRole::SideLabels)) {
            let side_labels = read_2d_string(problem, known, p)?;
            left_labels = Some(vec![side_labels[0].clone()]);
            top_labels = Some(vec![side_labels[1].clone()]);
            right_labels = Some(vec![side_labels[2].clone()]);
            bottom_labels = Some(vec![side_labels[3].clone()]);
        }

        // Givens (pre-filled values shown as immutable in cells).
        if let Some(p) = find_role(&|r| matches!(r, ShowRole::Givens)) {
            start_grid = Some(read_2d_option_i64(problem, known, p)?);
        }

        // Cages (matrix of cage ids per cell).
        if let Some(p) = find_role(&|r| matches!(r, ShowRole::Cages)) {
            cages = Some(read_2d_option_i64(problem, known, p)?);
        }

        // Colour regions (matrix of colour ids; 0/absent = uncoloured -> no tint).
        if let Some(p) = find_role(&|r| matches!(r, ShowRole::RegionTint)) {
            let raw = read_2d_option_i64(problem, known, p)?;
            region_tint = Some(
                raw.into_iter()
                    .map(|row| {
                        row.into_iter()
                            .map(|cell| match cell {
                                Some(k) if k >= 1 => Some(k),
                                _ => None,
                            })
                            .collect()
                    })
                    .collect(),
            );
        }

        let mut thermometers = None;
        let mut less_than = None;
        let mut cage_sums = None;

        // Thermometer paths.  Decoder: therms_raw[col][row] = therm_id * step
        // + position.  The directive carries both the therms matrix name
        // and the name of the scalar `step` integer.
        if let Some(d) = show
            .iter()
            .find(|d| matches!(d.role, ShowRole::Thermometers { .. }))
        {
            let ShowRole::Thermometers { step: step_name } = &d.role else {
                unreachable!()
            };
            let step = read_scalar_i64(problem, known, step_name)?;
            let therms_raw = read_2d_i64(problem, known, &d.var)?;
            // therms_raw[col_0][row_0] (0-indexed), outer index = col, inner index = row.
            let mut therm_paths: BTreeMap<i64, BTreeMap<i64, [i64; 2]>> = BTreeMap::new();
            for (col_0, col_data) in therms_raw.iter().enumerate() {
                for (row_0, &val) in col_data.iter().enumerate() {
                    if val == 0 {
                        continue;
                    }
                    let therm_id = val / step;
                    let pos = val % step;
                    therm_paths
                        .entry(therm_id)
                        .or_default()
                        .insert(pos, [row_0 as i64, col_0 as i64]);
                }
            }
            let paths: Vec<Vec<[i64; 2]>> = therm_paths
                .into_values()
                .map(|path| path.into_values().collect())
                .collect();
            if !paths.is_empty() {
                thermometers = Some(paths);
            }
        }

        // Less-than relations: vector of [r1, c1, r2, c2] 1-indexed cell pairs.
        // Collect from both the tuple-list role (`less_than`) and the per-axis
        // sign-matrix role (`less_than_grid horizontal|vertical`).  Cells are
        // emitted as 0-indexed [r1, c1, r2, c2] where (r1,c1) is the smaller.
        let mut pairs: Vec<[i64; 4]> = Vec::new();
        if let Some(p) = find_role(&|r| matches!(r, ShowRole::LessThan)) {
            let lt_raw = read_2d_i64(problem, known, p)?;
            pairs.extend(
                lt_raw
                    .iter()
                    .map(|v| [v[0] - 1, v[1] - 1, v[2] - 1, v[3] - 1]),
            );
        }
        for d in show.iter() {
            let axis = match d.role {
                ShowRole::LessThanGrid { axis } => axis,
                _ => continue,
            };
            let m = read_2d_i64(problem, known, &d.var)?;
            for (r, row) in m.iter().enumerate() {
                for (c, &v) in row.iter().enumerate() {
                    let (r, c) = (r as i64, c as i64);
                    let pair = match (axis, v) {
                        (LtAxis::Horizontal, 1) => [r, c, r, c + 1],
                        (LtAxis::Horizontal, 2) => [r, c + 1, r, c],
                        (LtAxis::Vertical, 1) => [r, c, r + 1, c],
                        (LtAxis::Vertical, 2) => [r + 1, c, r, c],
                        (_, 0) => continue,
                        (_, other) => anyhow::bail!(
                            "$#SHOW {} less_than_grid {axis:?}: cell [{r},{c}] \
                             has unexpected value {other} (expected 0, 1, or 2)",
                            d.var
                        ),
                    };
                    pairs.push(pair);
                }
            }
        }
        if !pairs.is_empty() {
            less_than = Some(pairs);
        }

        // Cage sums: vector of integers indexed by cage id.
        if let Some(p) = find_role(&|r| matches!(r, ShowRole::CageSums)) {
            cage_sums = Some(read_1d_i64(problem, known, p)?);
        }

        // $#INFO lines
        let info = if problem.eprime.info.is_empty() {
            None
        } else {
            Some(problem.eprime.info.clone())
        };

        // Build constraint_classes: group all instantiated constraint descriptions by $#CON class.
        // Templates were already rendered in parse.rs (conset); we just reorganise here.
        // Only keep instances whose scope includes at least one 2D grid cell (vacuous instances
        // — where Essence' guard failed — have no SAT connections and are not useful to show).
        // Cap each class at MAX_INSTANCES_PER_CLASS to keep the HTML payload manageable.
        const MAX_INSTANCES_PER_CLASS: usize = 50;
        let constraint_classes = if problem.constraints.is_empty() {
            None
        } else {
            let mut classes: BTreeMap<String, Vec<ConstraintInstance>> = BTreeMap::new();
            for (lit, description) in problem.constraints.iter() {
                if let Some(puzlits) = problem.direct.invlitmap.get(lit)
                    && let Some(puzlit) = puzlits.iter().find(|p| p.val() == 1)
                {
                    let class = puzlit.var().name().clone();
                    // Skip if this class is already at the cap.
                    let entries = classes.entry(class.clone()).or_default();
                    if entries.len() >= MAX_INSTANCES_PER_CLASS {
                        continue;
                    }
                    // Collect the unique grid cells this constraint covers (0-indexed).
                    let scope = problem.constraint_scope(description);
                    let cells: Vec<[i64; 2]> = scope
                        .iter()
                        .filter(|vvp| vvp.var().indices().len() == 2)
                        .map(|vvp| {
                            let idx = vvp.var().indices();
                            [idx[0] - 1, idx[1] - 1]
                        })
                        .collect::<BTreeSet<_>>()
                        .into_iter()
                        .collect();
                    // Skip vacuous instances (guard failed → no SAT connections → no cells).
                    if cells.is_empty() {
                        continue;
                    }
                    entries.push(ConstraintInstance {
                        description: description.clone(),
                        cells,
                    });
                }
            }
            if classes.is_empty() {
                None
            } else {
                Some(classes)
            }
        };

        Ok(Puzzle {
            kind,
            width,
            height,
            start_grid,
            solution_grid: None,
            cages,
            region_tint,
            top_labels,
            bottom_labels,
            left_labels,
            right_labels,
            thermometers,
            less_than,
            cage_sums,
            info,
            constraint_classes,
            decorations: problem.eprime.decs.clone(),
        })
    }
}

#[derive(Clone, PartialOrd, Ord, Hash, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct StateLit {
    pub val: i64,
    pub classes: Option<BTreeSet<String>>,
}

#[derive(Clone, PartialOrd, Ord, Hash, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct State {
    pub knowledge_grid: Option<Vec<Vec<Option<Vec<StateLit>>>>>,
    pub statements: Option<Vec<Statement>>,
    pub description: Option<String>,
    /// Cells (0-indexed [row, col]) that have no deducable literals at this step.
    /// Populated only in difficulty view to show non-deducable cells visually.
    #[serde(default)]
    pub blocked_cells: Option<Vec<[i64; 2]>>,
    /// One entry per MUS constraint in this step, describing how the renderer
    /// should draw the constraint's scope.  Indexed by `idx` matching the
    /// `highlight_conN` class on the cells.
    #[serde(default)]
    pub constraint_shapes: Option<Vec<ConstraintShape>>,
    /// Free-form diagnostic sections, populated when the caller has
    /// requested verbose output (CLI: `--verbose`).  Each section is a
    /// titled block of plain text that downstream renderers can display
    /// alongside the per-step view — used today to dump every `$#VAR`
    /// instance's current domain, intended to grow with timing / strategy
    /// / MUS-search internals as needs arise.  `None` (rather than
    /// `Some(vec![])`) when verbose output is off.
    #[serde(default)]
    pub verbose: Option<Vec<VerboseSection>>,
}

/// One titled block of diagnostic text in [`State::verbose`].  Body is
/// rendered as preformatted text (preserves newlines and indentation).
#[derive(Clone, PartialOrd, Ord, Hash, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct VerboseSection {
    pub title: String,
    pub body: String,
}

/// How the renderer should draw a constraint's scope on the grid.  Detected
/// from the cell layout; a constraint whose cells share a row is `Row`, share
/// a column is `Col`, has exactly two non-aligned cells is `Pair`, otherwise
/// `Region`.
#[derive(Clone, Copy, PartialOrd, Ord, Hash, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub enum ConstraintShapeKind {
    Row,
    Col,
    Pair,
    Region,
}

/// A drawable constraint scope: which cells it covers and how to render them.
#[derive(Clone, PartialOrd, Ord, Hash, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct ConstraintShape {
    /// Matches the `highlight_conN` index used on cell tags so CSS can drive
    /// per-constraint colour from a single source.
    pub idx: usize,
    pub kind: ConstraintShapeKind,
    /// 0-indexed `[row, col]`, sorted.
    pub cells: Vec<[i64; 2]>,
    /// Perpendicular offset slot for line/pair shapes that share an axis with
    /// other constraints (`0, +1, -1, +2, -2, ...`); the renderer multiplies
    /// by a small fraction of cell width.  Always `0` for `Region`.
    pub stagger: i32,
}

#[derive(Clone, PartialOrd, Ord, Hash, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct Statement {
    pub content: String,
    pub classes: Vec<String>,
}

#[derive(Clone, PartialOrd, Ord, Hash, Debug, PartialEq, Eq, Deserialize, Serialize)]
pub struct Problem {
    pub puzzle: Puzzle,
    pub state: Option<State>,
}

pub struct DescriptionStatement {
    pub result: String,
    pub constraints: Vec<String>,
    /// Matched named-strategy display name, if any (e.g. "Row hidden single").
    pub name: Option<String>,
    /// Canonical-form `MusFingerprint` string. Always populated for MUS-derived
    /// statements; empty for non-MUS statements (e.g. initial state).
    pub fingerprint: Option<String>,
}

impl DescriptionStatement {
    pub fn new(result: String, constraints: Vec<String>) -> Self {
        Self {
            result,
            constraints,
            name: None,
            fingerprint: None,
        }
    }
}

impl Problem {
    pub fn new_from_puzzle(problem: &PuzzleParse) -> anyhow::Result<Problem> {
        let puzzle = Puzzle::new_from_puzzle(problem)?;
        Ok(Problem {
            puzzle,
            state: None,
        })
    }

    pub fn new_from_puzzle_and_state(
        solver: &PuzzleSolver,
        tosolve: &BTreeSet<VarValPair>,
        known: &BTreeSet<PuzLit>,
        deduced_lits: &BTreeSet<PuzLit>,
        comments: &str,
    ) -> anyhow::Result<Problem> {
        Self::new_from_puzzle_and_mus(solver, tosolve, known, deduced_lits, &[], comments, false)
    }

    /// `hide_untouched_candidates`: when true, cells that have no known
    /// literal yet (positive or negative) are left out of `knowledgegrid`,
    /// so the renderer falls back to the `blocked_cells` "?" placeholder.
    /// Used by the walkthrough renderer for tutorial output: untouched
    /// cells stay visually quiet instead of being filled with every
    /// candidate value the planner could in principle deduce.  The
    /// interactive GUI keeps the default (false) so it still has clickable
    /// candidate lits in every cell.
    pub fn new_from_puzzle_and_mus(
        solver: &PuzzleSolver,
        tosolve: &BTreeSet<VarValPair>,
        known: &BTreeSet<PuzLit>,
        deduced_lits: &BTreeSet<PuzLit>,
        deduction_list: &[DescriptionStatement],
        comments: &str,
        hide_untouched_candidates: bool,
    ) -> anyhow::Result<Problem> {
        let puzzle = Puzzle::new_from_puzzle_and_known(solver.puzzleparse(), known)?;

        let main_show = solver
            .puzzleparse()
            .eprime
            .show
            .iter()
            .find(|d| d.role == ShowRole::Main)
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "model has no `$#SHOW <var> main` directive — required for rendering"
                )
            })?;
        let allowed_names: HashSet<String> = std::iter::once(main_show.var.clone()).collect();

        let mut knowledgegrid: Vec<Vec<Option<Vec<StateLit>>>> =
            vec![
                vec![None; usize::try_from(puzzle.width).context("width is negative")?];
                usize::try_from(puzzle.height).context("height is negative")?
            ];

        // Start by getting a list of all constraints, and assigning a number to each of them.
        let mut constraint_num: HashMap<String, usize> = HashMap::new();
        // Make a list of the tags we need to attach to each varvalpair in the scope of each constraint
        let mut constraint_tags: HashMap<VarValPair, BTreeSet<String>> = HashMap::new();

        for deduction in deduction_list {
            for constraint in &deduction.constraints {
                // constraint_num makes sure we only tag each constraint once
                if !constraint_num.contains_key(constraint) {
                    let len = constraint_num.len();
                    constraint_num.insert(constraint.clone(), len);
                    let scope = solver.puzzleparse().constraint_scope(constraint);
                    for p in scope {
                        let tags = constraint_tags.entry(p).or_default();
                        tags.insert(format!("highlight_con{len}"));
                        tags.insert("js_highlighter".to_string());
                    }
                }
            }
        }

        let all_lits = solver.puzzleparse().all_var_varvals();

        // When `hide_untouched_candidates` is on, cells with no known
        // literal (= or ≠) are left out of knowledgegrid so the renderer
        // falls back to "?" (via blocked_cells) instead of showing the
        // full candidate list.
        let touched_cells: BTreeSet<(usize, usize)> = if hide_untouched_candidates {
            known
                .iter()
                .filter_map(|p| {
                    let var = p.varval().var().clone();
                    if !allowed_names.contains(var.name()) {
                        return None;
                    }
                    let idx = var.indices();
                    if idx.len() != 2 {
                        return None;
                    }
                    let i = usize::try_from(idx[0]).ok()?.checked_sub(1)?;
                    let j = usize::try_from(idx[1]).ok()?.checked_sub(1)?;
                    Some((i, j))
                })
                .collect()
        } else {
            BTreeSet::new()
        };

        for l in all_lits {
            if !(tosolve.contains(&l) || known.contains(&PuzLit::new_eq(l.clone()))) {
                continue;
            }

            if !allowed_names.contains(l.var().name()) {
                continue;
            }

            // TODO: Handle more than one variable matrix?
            let index = l.var().indices().clone();
            assert_eq!(index.len(), 2);
            let i = usize::try_from(index[0]).context("negative index 0?")?;
            let j = usize::try_from(index[1]).context("negative index 1?")?;

            if hide_untouched_candidates && !touched_cells.contains(&(i - 1, j - 1)) {
                continue;
            }

            assert!(i > 0, "Variables should be 1-indexed");
            assert!(j > 0, "Variables should be 1-indexed");

            let i = i - 1;
            let j = j - 1;

            let mut tags = BTreeSet::new();

            if let Some(val) = constraint_tags.get(&l) {
                tags.extend(val.clone());
                tags.insert("litinmus".to_string());
            }

            if deduced_lits.contains(&PuzLit::new_eq(l.clone())) {
                tags.insert("litpos".to_string());
                tags.insert("highlight_".to_string() + &l.to_css_string());
                tags.insert("js_highlighter".to_string());
            }

            if deduced_lits.contains(&PuzLit::new_neq(l.clone())) {
                tags.insert("litneg".to_string());
                tags.insert("highlight_".to_string() + &l.to_css_string());
                tags.insert("js_highlighter".to_string());
            }

            if known.contains(&PuzLit::new_eq(l.clone())) {
                tags.insert("litknown".to_string());
            }

            tags.insert(format!("var-{}", l.var().name()));

            if knowledgegrid[i][j].is_none() {
                knowledgegrid[i][j] = Some(vec![]);
            }

            knowledgegrid[i][j].as_mut().unwrap().push(StateLit {
                val: l.val(),
                classes: Some(tags),
            });
        }

        let mut statements = Vec::new();

        for deduction in deduction_list {
            // Bundle the technique name (if matched) into the same Statement
            // as the deduction text, so they form one visual block instead of
            // looking like sibling deductions in the flat statements list.
            // Fingerprint rendering is suppressed for now — the format is not
            // yet stable and the raw string confuses readers.
            let mut header = String::new();
            if let Some(name) = &deduction.name {
                header.push_str(&format!(
                    "<div class=\"technique-name\">{}</div>",
                    tera::escape_html(name)
                ));
            }
            statements.push(Statement {
                content: format!("{header}{}", deduction.result),
                classes: vec!["deduction".to_string()],
            });
            for constraint in &deduction.constraints {
                let num = constraint_num.get(constraint).unwrap();
                statements.push(Statement {
                    content: tera::escape_html(constraint),
                    classes: vec![
                        format!("highlight_con{}", num),
                        "js_highlighter".to_string(),
                    ],
                });
            }
        }

        let constraint_shapes = build_constraint_shapes(solver, &constraint_num, &allowed_names);

        // Cells with no knowledge_grid entry and no start_grid value
        // render as "?" (only meaningful when hide_untouched_candidates
        // is on; otherwise the loop above populates every cell).
        let height = usize::try_from(puzzle.height).unwrap_or(0);
        let width = usize::try_from(puzzle.width).unwrap_or(0);
        let blocked: Vec<[i64; 2]> = (0..height)
            .flat_map(|r| (0..width).map(move |c| (r, c)))
            .filter(|&(r, c)| {
                knowledgegrid[r][c].is_none()
                    && puzzle
                        .start_grid
                        .as_ref()
                        .is_none_or(|sg| sg[r][c].is_none())
            })
            .map(|(r, c)| [r as i64, c as i64])
            .collect();
        let blocked_cells = if blocked.is_empty() {
            None
        } else {
            Some(blocked)
        };

        let state = State {
            knowledge_grid: Some(knowledgegrid),
            statements: Some(statements),
            description: Some(comments.to_owned()),
            blocked_cells,
            constraint_shapes: if constraint_shapes.is_empty() {
                None
            } else {
                Some(constraint_shapes)
            },
            verbose: None,
        };

        Ok(Problem {
            puzzle,
            state: Some(state),
        })
    }

    /// `hide_untouched_candidates`: see `new_from_puzzle_and_mus`.
    pub fn new_from_puzzle_and_difficulty(
        solver: &PuzzleSolver,
        tosolve: &BTreeSet<VarValPair>,
        known: &BTreeSet<PuzLit>,
        complexity: &BTreeMap<VarValPair, usize>,
        description: &str,
        hide_untouched_candidates: bool,
    ) -> anyhow::Result<Problem> {
        let puzzle = Puzzle::new_from_puzzle_and_known(solver.puzzleparse(), known)?;

        let main_show = solver
            .puzzleparse()
            .eprime
            .show
            .iter()
            .find(|d| d.role == ShowRole::Main)
            .ok_or_else(|| {
                anyhow::anyhow!(
                    "model has no `$#SHOW <var> main` directive — required for rendering"
                )
            })?;
        let allowed_names: HashSet<String> = std::iter::once(main_show.var.clone()).collect();

        let mut knowledgegrid: Vec<Vec<Option<Vec<StateLit>>>> =
            vec![
                vec![None; usize::try_from(puzzle.width).context("width is negative")?];
                usize::try_from(puzzle.height).context("height is negative")?
            ];

        let all_lits = solver.puzzleparse().all_var_varvals();

        let complexity_vals: BTreeSet<_> = complexity.values().collect();

        let touched_cells: BTreeSet<(usize, usize)> = if hide_untouched_candidates {
            known
                .iter()
                .filter_map(|p| {
                    let var = p.varval().var().clone();
                    if !allowed_names.contains(var.name()) {
                        return None;
                    }
                    let idx = var.indices();
                    if idx.len() != 2 {
                        return None;
                    }
                    let i = usize::try_from(idx[0]).ok()?.checked_sub(1)?;
                    let j = usize::try_from(idx[1]).ok()?.checked_sub(1)?;
                    Some((i, j))
                })
                .collect()
        } else {
            BTreeSet::new()
        };

        for l in all_lits {
            if !(tosolve.contains(&l) || known.contains(&PuzLit::new_eq(l.clone()))) {
                continue;
            }

            if !allowed_names.contains(l.var().name()) {
                continue;
            }

            // TODO: Handle more than one variable matrix?
            let index = l.var().indices().clone();
            assert_eq!(index.len(), 2);
            let i = usize::try_from(index[0]).context("negative index 0?")?;
            let j = usize::try_from(index[1]).context("negative index 1?")?;

            assert!(i > 0, "Variables should be 1-indexed");
            assert!(j > 0, "Variables should be 1-indexed");

            let i = i - 1;
            let j = j - 1;

            if hide_untouched_candidates && !touched_cells.contains(&(i, j)) {
                continue;
            }

            let mut tags = BTreeSet::new();

            if let Some(val) = complexity.get(&l) {
                let i = complexity_vals.iter().position(|&v| v == val).unwrap_or(0);
                tags.insert(format!("highlight_con{i}"));
                tags.insert("js_highlighter".to_string());
            }

            if known.contains(&PuzLit::new_eq(l.clone())) {
                tags.insert("litknown".to_string());
            }

            tags.insert(format!("var-{}", l.var().name()));

            if knowledgegrid[i][j].is_none() {
                knowledgegrid[i][j] = Some(vec![]);
            }

            knowledgegrid[i][j].as_mut().unwrap().push(StateLit {
                val: l.val(),
                classes: Some(tags),
            });
        }

        let statements = complexity_vals
            .iter()
            .enumerate()
            .map(|(i, consize)| Statement {
                content: format!("MUS size {consize}"),
                classes: vec![format!("highlight_con{}", i), "js_highlighter".to_string()],
            })
            .collect_vec();

        // Collect cells that have no deducable or known literals — shown as blocked in SVG.
        let height = usize::try_from(puzzle.height).unwrap_or(0);
        let width = usize::try_from(puzzle.width).unwrap_or(0);
        let blocked: Vec<[i64; 2]> = (0..height)
            .flat_map(|r| (0..width).map(move |c| (r, c)))
            .filter(|&(r, c)| {
                knowledgegrid[r][c].is_none()
                    && puzzle
                        .start_grid
                        .as_ref()
                        .is_none_or(|sg| sg[r][c].is_none())
            })
            .map(|(r, c)| [r as i64, c as i64])
            .collect();
        let blocked_cells = if blocked.is_empty() {
            None
        } else {
            Some(blocked)
        };

        let state = State {
            knowledge_grid: Some(knowledgegrid),
            statements: Some(statements),
            description: Some(description.to_owned()),
            blocked_cells,
            constraint_shapes: None,
            verbose: None,
        };

        Ok(Problem {
            puzzle,
            state: Some(state),
        })
    }
}

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

    use crate::json::Puzzle;
    use crate::problem::util::test_utils::build_puzzleparse;

    #[test]
    fn detect_kind_classifies_layouts() {
        use super::{ConstraintShapeKind as K, detect_constraint_shape_kind};
        assert_eq!(detect_constraint_shape_kind(&[[3, 1], [3, 5]]), K::Row);
        assert_eq!(
            detect_constraint_shape_kind(&[[3, 1], [3, 2], [3, 9]]),
            K::Row
        );
        assert_eq!(detect_constraint_shape_kind(&[[1, 4], [7, 4]]), K::Col);
        assert_eq!(detect_constraint_shape_kind(&[[1, 1], [3, 5]]), K::Pair);
        assert_eq!(
            detect_constraint_shape_kind(&[[1, 1], [1, 2], [2, 1]]),
            K::Region
        );
        // Single cell — degenerate case, classified as Row (zero-length line).
        assert_eq!(detect_constraint_shape_kind(&[[2, 2]]), K::Row);
    }

    #[test]
    fn stagger_slot_pattern() {
        use super::stagger_slot;
        assert_eq!(stagger_slot(0), 0);
        assert_eq!(stagger_slot(1), -1);
        assert_eq!(stagger_slot(2), 1);
        assert_eq!(stagger_slot(3), -2);
        assert_eq!(stagger_slot(4), 2);
    }

    #[test]
    fn givens_role_reads_from_known_puzlits_for_find_var() -> anyhow::Result<()> {
        use crate::problem::PuzLit;
        use crate::problem::PuzVar;
        use crate::problem::VarValPair;
        use crate::problem::parse::{ShowDirective, ShowRole};
        use std::collections::BTreeSet;

        // Mystify-style scenario: `grid` is a `find` matrix declared in the
        // model; values arrive at render-time via known PuzLits rather than
        // a `letting` block.  Re-target the existing $#SHOW directives so
        // that `grid` plays the `givens` role, then check the renderer
        // builds `start_grid` from the supplied known lits.
        let mut puz = build_puzzleparse("./tst/binairo.eprime", "./tst/binairo-1.param");
        puz.eprime.show = vec![
            ShowDirective {
                var: "grid".to_string(),
                role: ShowRole::Main,
            },
            ShowDirective {
                var: "grid".to_string(),
                role: ShowRole::Givens,
            },
        ];

        let mut known: BTreeSet<PuzLit> = BTreeSet::new();
        // Pin a single cell so we can verify the matrix is filled from `known`.
        known.insert(PuzLit::new_eq(VarValPair::new(
            &PuzVar::new("grid", vec![1, 1]),
            1,
        )));

        let p = Puzzle::new_from_puzzle_and_known(&puz, &known)?;
        let sg = p
            .start_grid
            .expect("givens role should populate start_grid");
        assert_eq!(sg[0][0], Some(1), "known grid[1,1]=1 should appear");
        // Cells without a known lit should remain None.
        assert_eq!(sg[0][1], None);
        Ok(())
    }

    #[test]
    fn test_parse_essence_binairo() -> anyhow::Result<()> {
        let puz = build_puzzleparse("./tst/binairo.eprime", "./tst/binairo-1.param");
        let p = Puzzle::new_from_puzzle(&puz)?;
        assert_eq!(p.kind, "Binairo");
        assert_eq!(p.width, 6);
        assert_eq!(p.height, 6);
        Ok(())
    }

    #[test]
    fn test_puzzle_dimensions_match_param() -> anyhow::Result<()> {
        // binairo with n=6 should produce a 6×6 puzzle.
        let puz = build_puzzleparse("./tst/binairo.eprime", "./tst/binairo-1.param");
        let p = Puzzle::new_from_puzzle(&puz)?;
        assert_eq!(p.width, 6, "binairo n=6 should give width=6");
        assert_eq!(p.height, 6, "binairo n=6 should give height=6");
        Ok(())
    }

    #[test]
    fn test_puzzle_start_grid_present() -> anyhow::Result<()> {
        // Binairo has a start_grid with some given values.
        let puz = build_puzzleparse("./tst/binairo.eprime", "./tst/binairo-1.param");
        let p = Puzzle::new_from_puzzle(&puz)?;
        assert!(p.start_grid.is_some());
        let sg = p.start_grid.unwrap();
        assert_eq!(sg.len() as i64, p.height);
        assert_eq!(sg[0].len() as i64, p.width);
        Ok(())
    }

    #[test]
    fn test_clue_matrix_to_layers_nonogram_5x5() {
        use crate::json::clue_matrix_to_layers;
        let row_clues = vec![
            vec![5, 0, 0],
            vec![1, 3, 0],
            vec![3, 1, 0],
            vec![2, 2, 0],
            vec![1, 1, 1],
        ];
        let layers = clue_matrix_to_layers(&row_clues);
        assert_eq!(layers.len(), 3);
        assert_eq!(layers[0], vec!["", "", "", "", "1"]);
        assert_eq!(layers[1], vec!["", "1", "3", "2", "1"]);
        assert_eq!(layers[2], vec!["5", "3", "1", "2", "1"]);
    }

    #[test]
    fn test_clue_matrix_to_layers_trims_empty_depth() {
        use crate::json::clue_matrix_to_layers;
        // maxruns=4 but no row uses more than 2 clues: depth should be 2, not 4.
        let clues = vec![vec![3, 0, 0, 0], vec![1, 2, 0, 0]];
        let layers = clue_matrix_to_layers(&clues);
        assert_eq!(layers.len(), 2);
        assert_eq!(layers[0], vec!["", "1"]);
        assert_eq!(layers[1], vec!["3", "2"]);
    }

    #[test]
    fn test_clue_matrix_to_layers_all_zeros() {
        use crate::json::clue_matrix_to_layers;
        let clues = vec![vec![0, 0], vec![0, 0]];
        assert!(clue_matrix_to_layers(&clues).is_empty());
    }

    #[test]
    fn test_puzzle_minesweeper_has_no_start_grid() -> anyhow::Result<()> {
        // Minesweeper has no pre-filled grid.
        let puz = build_puzzleparse("./tst/minesweeper.eprime", "./tst/minesweeperPrinted.param");
        let p = Puzzle::new_from_puzzle(&puz)?;
        // Minesweeper start_grid is None or all-None cells
        let all_empty = p
            .start_grid
            .as_ref()
            .is_none_or(|sg| sg.iter().all(|row| row.iter().all(|c| c.is_none())));
        assert!(all_empty, "minesweeper should have no fixed start cells");
        Ok(())
    }

    /// Non-square kakuro: the model declares the main grid as
    /// `matrix indexed by [X,Y]` with X = 1..width and Y = 1..height — the
    /// row axis is bounded by the param named `width`, opposite the usual
    /// convention.  The renderer needs `puzzle.width` / `puzzle.height` to
    /// match the visible col/row counts (= `dims[1]` / `dims[0]` of the
    /// main var), not the param names.  Was a bug: pre-fix the renderer
    /// pulled `puzzle.width` from the `width` param and indexed the
    /// knowledge grid out of bounds on a non-square instance.
    #[test]
    fn test_puzzle_kakuro_non_square_dimensions() -> anyhow::Result<()> {
        let puz = build_puzzleparse("./tst/kakuro.eprime", "./tst/kakuro-non-square.param");
        let p = Puzzle::new_from_puzzle(&puz)?;
        // Param has width=2, height=3 (kakuro letting names).  Visible grid:
        // 2 rows × 3 cols, so puzzle.height=2, puzzle.width=3.
        assert_eq!(
            p.height, 2,
            "kakuro: puzzle.height must follow main var index[0] domain (2), not the `height` param (3)"
        );
        assert_eq!(
            p.width, 3,
            "kakuro: puzzle.width must follow main var index[1] domain (3), not the `width` param (2)"
        );
        Ok(())
    }

    /// Non-square minesweeper: control case for the kakuro test above.
    /// Minesweeper uses the standard convention (`matrix indexed by
    /// [int(1..height), int(1..width)]`) so the param-named width/height
    /// already match the renderer's row/col counts; a regression here
    /// would mean the fix has flipped the standard case the wrong way.
    #[test]
    fn test_puzzle_minesweeper_non_square_dimensions() -> anyhow::Result<()> {
        let puz = build_puzzleparse(
            "./tst/minesweeper.eprime",
            "./tst/minesweeper-non-square.param",
        );
        let p = Puzzle::new_from_puzzle(&puz)?;
        assert_eq!(p.width, 3, "minesweeper: width param=3 is the col count");
        assert_eq!(p.height, 2, "minesweeper: height param=2 is the row count");
        Ok(())
    }

    /// Full pipeline regression: end-to-end through `PuzzleSolver` and
    /// `Problem::new_from_puzzle_and_state`, which is where the original
    /// out-of-bounds panic fired (`json/mod.rs:823`) when the knowledge
    /// grid was sized as `[height][width]` but indexed by the var's
    /// first/second indices.
    #[test]
    fn test_problem_kakuro_non_square_no_panic() -> anyhow::Result<()> {
        use crate::problem::PuzLit;
        use crate::problem::solver::PuzzleSolver;
        use std::collections::BTreeSet;
        use std::sync::Arc;

        let pp = Arc::new(build_puzzleparse(
            "./tst/kakuro.eprime",
            "./tst/kakuro-non-square.param",
        ));
        let mut solver = PuzzleSolver::new(pp)?;

        // Build the same `tosolve` shape the planner does — varvalpairs of
        // every provable literal — so the knowledge grid is populated for
        // every cell of the main var.
        let varlits = solver.get_provable_varlits().clone();
        let tosolve: BTreeSet<_> = varlits
            .iter()
            .flat_map(|x| solver.lit_to_puzlit(x))
            .map(PuzLit::varval)
            .collect();
        let known = BTreeSet::new();
        let deduced = BTreeSet::new();

        // Pre-fix: this panicked with `index out of bounds` because the
        // knowledge grid was sized [height_param=3][width_param=2] but the
        // main var's index[1] (col) ran 1..3, exceeding the inner length 2.
        let problem =
            super::Problem::new_from_puzzle_and_state(&solver, &tosolve, &known, &deduced, "test")?;

        let kg = problem
            .state
            .as_ref()
            .and_then(|s| s.knowledge_grid.as_ref())
            .expect("state should have a knowledge grid");
        assert_eq!(kg.len(), 2, "outer (row) length must be 2");
        assert_eq!(kg[0].len(), 3, "inner (col) length must be 3");
        Ok(())
    }
}