axioval-cli 0.3.0

Command-line runner for normalized Axioval packages
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
#![allow(clippy::doc_markdown)]

//! The saved check result, and bounded views of it.
//!
//! A full result grows with the model: one entry per finding, and a real model
//! easily has thousands. A reader with a budget (a person at a terminal, an
//! agent paying per token) needs the shape first and the entries only on
//! request. So there are two views, both computed from the saved result
//! without re-running the check:
//!
//! - a **summary**, whose size depends on how many distinct rules and codes
//!   fired, not on how many objects they fired on;
//! - a **listing**, filtered and paged, for digging into one rule, code or
//!   object.
//!
//! Both end with the exact command for the next step.

use std::collections::{BTreeMap, BTreeSet};
use std::fmt::Write as _;

use axioval::ir::{
    Decision, DecisionStatus, EvidenceCheck, Finding, FindingDecision, Location, NotEvaluated,
    NotEvaluatedReason, ObjectId, Place, Project, Report, ReportColumn, ReportColumnKind,
    ReportRow, ReportTable, ReportValue, RuleStatus, Scope, Severity, SourceId,
};
use serde::{Deserialize, Serialize};

/// Scheme of the GlobalId alias shown next to an object.
const GLOBAL_ID: &str = axioval::bcf::IFC_GLOBAL_ID_SCHEME;
/// Longest message a summary prints before eliding the rest.
const MESSAGE_BUDGET: usize = 160;
/// Example objects a summary names per group.
const EXAMPLES: usize = 3;

/// The JSON document `check` writes.
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckOutput {
    pub report: Report,
    /// Irregularities of the model itself, separate from rule findings.
    pub integrity: Vec<IntegrityRecord>,
    /// Every object the report names, keyed by its full id, so a reader can
    /// tell what `#4711` is without the model at hand.
    #[serde(default)]
    pub objects: BTreeMap<String, ObjectInfo>,
    /// How the model's bodies were meshed, when `check --geometry` ran.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub geometry: Option<GeometryRecord>,
    /// What `compare` found, per object and facet, beside the report it
    /// projects to. Absent from a `check` result.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub comparison: Option<ComparisonRecord>,
    /// Every checked source with its discipline and where it came from.
    /// Absent from a `compare` result and from results saved before it.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub sources: Vec<SourceInfo>,
}

/// One checked source: its discipline, declared or assigned by
/// `--discipline-map`, or why the map left it without one.
#[derive(Debug, Serialize, Deserialize)]
pub struct SourceInfo {
    /// `system:document`.
    pub source: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub discipline: Option<String>,
    /// `declared` or `mapped`, with a discipline.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub discipline_origin: Option<String>,
    /// The map rule that assigned it, `field:pattern=discipline`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mapped_by: Option<String>,
    /// The value the rule matched.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mapped_value: Option<String>,
    /// Why `--discipline-map` assigned none.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unmapped: Option<String>,
}

/// The structured result of `compare`: every identity that is not unchanged,
/// with its differences per facet, and everything that could not be matched.
#[derive(Debug, Serialize, Deserialize)]
pub struct ComparisonRecord {
    /// The base source, `system:document`.
    pub base: String,
    /// The revised source.
    pub revised: String,
    /// The identity scheme objects were matched by.
    pub scheme: String,
    /// The facets compared, in order.
    pub facets: Vec<String>,
    pub tolerance: ToleranceRecord,
    pub counts: ComparisonCounts,
    /// Added, removed, changed and incomplete identities, by identity.
    /// Unchanged identities are only counted.
    pub objects: Vec<ComparedRecord>,
    /// Objects without an identity in the scheme.
    pub unidentified: Vec<SideObject>,
    /// Identities claimed by several objects of one side.
    pub ambiguous: Vec<AmbiguousRecord>,
    /// Coordinate systems, per pair of sources.
    pub coordinate_systems: Vec<SourceRecord>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ToleranceRecord {
    pub length_metres: f64,
    pub angle_degrees: f64,
}

#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
pub struct ComparisonCounts {
    pub added: usize,
    pub removed: usize,
    pub changed: usize,
    pub unchanged: usize,
    /// Matched without a difference, but with a facet not compared or a
    /// measure undetermined.
    pub incomplete: usize,
    pub unidentified: usize,
    pub ambiguous: usize,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ComparedRecord {
    pub identity: String,
    /// `added`, `removed`, `changed` or `incomplete`.
    pub state: String,
    /// The object's kind, from the revised side when it has one.
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base: Option<ObjectId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revised: Option<ObjectId>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub changes: Vec<ChangeRecord>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unresolved: Vec<GapRecord>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub undetermined: Vec<ChangeRecord>,
}

/// One difference, or one undetermined measure.
#[derive(Debug, Serialize, Deserialize)]
pub struct ChangeRecord {
    pub facet: String,
    pub detail: String,
    /// The measure, for a measured difference.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub measure: Option<String>,
    /// The difference lies in `[lower, upper]`, in `unit`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub lower: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub upper: Option<f64>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tolerance: Option<f64>,
    /// `m`, `rad`, or empty for a ratio.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub unit: Option<String>,
}

/// A facet that could not be compared.
#[derive(Debug, Serialize, Deserialize)]
pub struct GapRecord {
    pub facet: String,
    pub detail: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SideObject {
    pub side: String,
    pub object: ObjectId,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AmbiguousRecord {
    pub side: String,
    pub identity: String,
    pub objects: Vec<ObjectId>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct SourceRecord {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub base: Option<SourceId>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub revised: Option<SourceId>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub changes: Vec<ChangeRecord>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub unresolved: Vec<GapRecord>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub undetermined: Vec<ChangeRecord>,
}

/// Outcome of meshing, so a reader can tell "no finding" from "not measured".
#[derive(Debug, Serialize, Deserialize)]
pub struct GeometryRecord {
    /// Meshed with every face planar: the mesh is the shape.
    pub exact: usize,
    /// Meshed from curved faces, within the compiler's chord budget.
    pub tessellated: usize,
    /// Occupying no material, e.g. storeys, zones, openings.
    pub no_body: usize,
    /// Physical objects that could not be meshed. Geometric measurements
    /// they could affect are not evaluated.
    pub unmeasured: Vec<Unmeasured>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Unmeasured {
    pub object: ObjectId,
    pub reason: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct IntegrityRecord {
    pub code: String,
    pub severity: String,
    pub message: String,
    pub locator: String,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ObjectInfo {
    pub kind: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub global_id: Option<String>,
}

impl CheckOutput {
    pub fn new(
        report: Report,
        integrity: Vec<IntegrityRecord>,
        geometry: Option<GeometryRecord>,
        project: &Project,
    ) -> Self {
        let mut named: BTreeSet<&ObjectId> = BTreeSet::new();
        named.extend(
            geometry
                .iter()
                .flat_map(|g| g.unmeasured.iter().map(|u| &u.object)),
        );
        for finding in report.findings() {
            named.extend(finding.object_id());
            named.extend(&finding.related);
            named.extend(places(finding.location.as_ref()));
        }
        for outcome in report.not_evaluated() {
            named.extend(places(outcome.location.as_ref()));
        }
        named.extend(
            report
                .not_evaluated()
                .iter()
                .filter_map(NotEvaluated::object_id),
        );
        named.extend(table_objects(&report));
        let objects = named
            .into_iter()
            .filter_map(|id| {
                // A resource object the report names is labelled from the
                // report, which carries it.
                let object = report.object(project, id)?;
                Some((
                    id.to_string(),
                    ObjectInfo {
                        kind: object.kind().to_owned(),
                        global_id: object.external_id(GLOBAL_ID).map(ToOwned::to_owned),
                    },
                ))
            })
            .collect();
        Self {
            report,
            integrity,
            objects,
            geometry,
            comparison: None,
            sources: Vec::new(),
        }
    }

    /// The same result listing its sources.
    #[must_use]
    pub fn with_sources(mut self, sources: Vec<SourceInfo>) -> Self {
        self.sources = sources;
        self
    }

    /// The same result carrying what `compare` found.
    #[must_use]
    pub fn with_comparison(mut self, comparison: ComparisonRecord) -> Self {
        self.comparison = Some(comparison);
        self
    }

    /// Whether the report spans more than one source document, in which case
    /// a bare local id like `#2` is ambiguous and is qualified.
    fn several_documents(&self) -> bool {
        let scoped = self
            .report
            .findings()
            .iter()
            .map(|f| &f.scope)
            .chain(self.report.not_evaluated().iter().map(|n| &n.scope))
            .chain(
                self.report
                    .tables()
                    .iter()
                    .flat_map(|table| table.rows().iter().map(ReportRow::scope)),
            )
            .filter_map(|scope| match scope {
                Scope::Source(source) => Some(source),
                Scope::Project | Scope::Object(_) => None,
            });
        let mut documents = self.referenced().map(|id| &id.source).chain(scoped);
        let first = documents.next();
        documents.any(|other| Some(other) != first)
    }

    fn referenced(&self) -> impl Iterator<Item = &ObjectId> {
        self.report
            .findings()
            .iter()
            .flat_map(|f| f.object_id().into_iter().chain(&f.related))
            .chain(
                self.report
                    .not_evaluated()
                    .iter()
                    .filter_map(NotEvaluated::object_id),
            )
            .chain(
                self.geometry
                    .iter()
                    .flat_map(|g| g.unmeasured.iter().map(|u| &u.object)),
            )
            .chain(table_objects(&self.report))
    }

    /// `#2 IFCWALL 2O2Fr$t4X7Zf8NOew3FLOH`: local id, kind, GlobalId when known.
    fn describe(&self, id: &ObjectId, qualify: bool) -> String {
        let mut text = if qualify {
            format!("{}/{}", id.source.document, id.local_id)
        } else {
            id.local_id.clone()
        };
        if let Some(info) = self.objects.get(&id.to_string()) {
            let _ = write!(text, " {}", info.kind);
            if let Some(global_id) = &info.global_id {
                let _ = write!(text, " {global_id}");
            }
        }
        text
    }

    /// What an entry is about: the object as [`Self::describe`] names it, or
    /// `source <document>` or `project` for an entry about no single object.
    fn subject(&self, scope: &Scope, qualify: bool) -> String {
        match scope {
            Scope::Object(id) => self.describe(id, qualify),
            Scope::Source(source) => format!("source {}", source.document),
            Scope::Project => "project".to_owned(),
        }
    }

    /// Whether `location` may lie in the storey or space `query` names (by
    /// name or as [`Self::names`] reads an id): an unresolved location
    /// might, an absent one does not.
    fn located(&self, location: Option<&Location>, query: &str) -> bool {
        location.is_some_and(|location| {
            location.unresolved.is_some()
                || location.places().any(|place| {
                    place.name.as_deref() == Some(query) || self.names(&place.id, query)
                })
        })
    }

    /// Whether `query` names `id`: its full id, its local id, its local id
    /// qualified by its document (`model.ifc/#2`, as a summary over several
    /// documents prints it), or its GlobalId.
    fn names(&self, id: &ObjectId, query: &str) -> bool {
        let full = id.to_string();
        full == query
            || id.local_id == query
            || query.split_once('/').is_some_and(|(document, local)| {
                document == id.source.document && local == id.local_id
            })
            || self
                .objects
                .get(&full)
                .and_then(|info| info.global_id.as_deref())
                == Some(query)
    }
}

/// Which part of the result an entry comes from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum Section {
    Findings,
    NotEvaluated,
    Integrity,
    /// Objects `check --geometry` could not mesh.
    Geometry,
    /// Rows of the tables of measured values rules report.
    Tables,
    /// Decisions `check --decisions` found no finding for.
    StaleDecisions,
}

impl Section {
    fn label(self) -> &'static str {
        match self {
            Self::Findings => "finding",
            Self::NotEvaluated => "not-evaluated",
            Self::Integrity => "integrity",
            Self::Geometry => "geometry",
            Self::Tables => "table",
            Self::StaleDecisions => "stale-decision",
        }
    }
}

/// A location as a reader reads it: `storey Level 1 (#10); space 101
/// (#20)`, and why it may be incomplete.
fn location_text(location: &Location, qualify: bool) -> String {
    let place = |kind: &str, place: &Place| {
        let id = if qualify {
            format!("{}/{}", place.id.source.document, place.id.local_id)
        } else {
            place.id.local_id.clone()
        };
        match &place.name {
            Some(name) => format!("{kind} {name} ({id})"),
            None => format!("{kind} {id}"),
        }
    };
    let mut parts: Vec<String> = location
        .storeys
        .iter()
        .map(|storey| place("storey", storey))
        .chain(location.spaces.iter().map(|space| place("space", space)))
        .collect();
    if parts.is_empty() {
        parts.push("no storey or space".to_owned());
    }
    if let Some(why) = &location.unresolved {
        parts.push(format!("unresolved: {why}"));
    }
    parts.join("; ")
}

/// The storeys and spaces of a location.
fn places(location: Option<&Location>) -> impl Iterator<Item = &ObjectId> {
    location
        .into_iter()
        .flat_map(|location| location.places().map(|place| &place.id))
}

/// The objects the rows of the report's tables are about.
fn table_objects(report: &Report) -> impl Iterator<Item = &ObjectId> {
    report
        .tables()
        .iter()
        .flat_map(|table| table.rows().iter().filter_map(|row| row.scope().object()))
}

/// A column as a summary names it: `height (m)`.
fn column_text(column: &ReportColumn) -> String {
    match column.kind.unit_symbol() {
        Some(unit) => format!("{} ({unit})", column.id),
        None => column.id.clone(),
    }
}

/// A table's columns, as the message of its summary group; a grouped
/// table's group columns first.
fn columns_text(table: &ReportTable) -> String {
    let columns: Vec<String> = table.columns().iter().map(column_text).collect();
    let columns = format!("columns: {}", columns.join(", "));
    if table.group_by().is_empty() {
        columns
    } else {
        format!("grouped by {}; {columns}", table.group_by().join(", "))
    }
}

/// A grouped row's group values as headings, `[A] [Level 1] `; nothing
/// for a row of an ungrouped table.
fn group_text(row: &ReportRow) -> String {
    row.group().iter().fold(String::new(), |mut text, value| {
        let _ = write!(text, "[{value}] ");
        text
    })
}

/// `table` as CSV (RFC 4180, `\n` line ends): a header, then one line per
/// row in table order.
///
/// The columns are `scope` (as a listing names it: `project`, `source …`
/// or an object id), the group columns, and per value column its text or,
/// for a number or quantity, `<id>_lower` and `<id>_upper` with the unit in
/// brackets: an exact value fills both, an unknown one neither.
pub fn table_csv(table: &ReportTable) -> String {
    let mut header = vec!["scope".to_owned()];
    header.extend(table.group_by().iter().cloned());
    for column in table.columns() {
        if column.kind == ReportColumnKind::Text {
            header.push(column.id.clone());
        } else {
            let unit = column
                .kind
                .unit_symbol()
                .map(|unit| format!(" [{unit}]"))
                .unwrap_or_default();
            header.push(format!("{}_lower{unit}", column.id));
            header.push(format!("{}_upper{unit}", column.id));
        }
    }
    let mut text = csv_line(&header);
    for row in table.rows() {
        let mut cells = vec![row.scope().to_string()];
        cells.extend(row.group().iter().cloned());
        for (column, value) in table.columns().iter().zip(row.values()) {
            let text = column.kind == ReportColumnKind::Text;
            match value {
                ReportValue::Text { value } => cells.push(value.clone()),
                ReportValue::Exact { value } => {
                    cells.extend([value.to_string(), value.to_string()]);
                }
                ReportValue::Interval { lower, upper } => {
                    cells.extend([lower.to_string(), upper.to_string()]);
                }
                ReportValue::Unknown if text => cells.push(String::new()),
                ReportValue::Unknown => cells.extend([String::new(), String::new()]),
            }
        }
        text.push_str(&csv_line(&cells));
    }
    text
}

/// One CSV line: fields quoted when they hold a comma, quote or line break.
fn csv_line(fields: &[String]) -> String {
    let quoted: Vec<String> = fields
        .iter()
        .map(|field| {
            if field.contains([',', '"', '\n', '\r']) {
                format!("\"{}\"", field.replace('"', "\"\""))
            } else {
                field.clone()
            }
        })
        .collect();
    quoted.join(",") + "\n"
}

/// A number as a reader reads it: at most six decimals.
fn decimal(value: f64) -> String {
    format!("{}", (value * 1e6).round() / 1e6)
}

/// One row's values, `elevation 3 m · height 3.49..3.51 m`.
fn row_text(table: &ReportTable, values: &[ReportValue]) -> String {
    table
        .columns()
        .iter()
        .zip(values)
        .map(|(column, value)| {
            let unit = column
                .kind
                .unit_symbol()
                .map(|unit| format!(" {unit}"))
                .unwrap_or_default();
            let text = match value {
                ReportValue::Unknown => "unknown".to_owned(),
                ReportValue::Exact { value } => format!("{}{unit}", decimal(*value)),
                ReportValue::Interval { lower, upper } => {
                    format!("{}..{}{unit}", decimal(*lower), decimal(*upper))
                }
                ReportValue::Text { value } => value.clone(),
            };
            format!("{} {text}", column.id)
        })
        .collect::<Vec<_>>()
        .join(" · ")
}

/// Entries sharing a rule (or integrity code) and a severity (or reason).
#[derive(Debug, Serialize)]
pub struct Group {
    pub section: Section,
    /// Rule id, or integrity code.
    pub key: String,
    /// Severity, or not-evaluated reason.
    pub level: String,
    pub count: usize,
    pub distinct_messages: usize,
    /// The most frequent message, elided past a fixed budget.
    pub message: String,
    /// Up to three objects the group fired on.
    pub examples: Vec<String>,
}

#[derive(Debug, Serialize)]
pub struct GeometryCounts {
    pub exact: usize,
    pub tessellated: usize,
    pub no_body: usize,
    pub unmeasured: usize,
}

/// A bounded digest of a result.
#[derive(Debug, Serialize)]
pub struct Summary {
    pub status: &'static str,
    pub findings: usize,
    pub not_evaluated: usize,
    pub integrity: usize,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub geometry: Option<GeometryCounts>,
    /// What `compare` found, when the result is a comparison.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub comparison: Option<ComparisonDigest>,
    /// Each rule's status, when `check --rule-status` recorded it.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub rules: Option<RulesDigest>,
    /// Findings by decision, when `check --decisions` carried any over.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decisions: Option<DecisionCounts>,
    pub groups: Vec<Group>,
    /// Groups left out by the `top` limit, per section.
    pub omitted_groups: BTreeMap<&'static str, usize>,
    pub next: Vec<String>,
}

/// Findings by decision, and decisions whose finding is gone.
#[derive(Debug, Default, Serialize)]
pub struct DecisionCounts {
    pub accepted: usize,
    pub rejected: usize,
    pub open: usize,
    pub undecided: usize,
    /// Decided findings that changed since the decision.
    pub changed: usize,
    pub stale: usize,
}

impl DecisionCounts {
    /// `decisions: 1 accepted · … · 0 stale`, one line.
    fn line(&self) -> String {
        format!(
            "decisions: {} accepted · {} rejected · {} open · {} undecided · {} changed · {} stale\n",
            self.accepted, self.rejected, self.open, self.undecided, self.changed, self.stale
        )
    }
}

/// The decision counts of `report`; `None` when no decision was applied
/// to it.
fn decision_counts(report: &Report) -> Option<DecisionCounts> {
    let decided = report.findings().iter().any(|f| f.decision.is_some());
    if !decided && report.stale_decisions().is_empty() {
        return None;
    }
    let mut counts = DecisionCounts {
        stale: report.stale_decisions().len(),
        ..DecisionCounts::default()
    };
    for finding in report.findings() {
        match &finding.decision {
            None => counts.undecided += 1,
            Some(decision) => {
                match decision.status {
                    DecisionStatus::Accepted => counts.accepted += 1,
                    DecisionStatus::Rejected => counts.rejected += 1,
                    DecisionStatus::Open => counts.open += 1,
                }
                if decision.evidence == EvidenceCheck::Changed {
                    counts.changed += 1;
                }
            }
        }
    }
    Some(counts)
}

/// A stale decision's rule and message, from its basis; `-` and the
/// finding's identity without one.
fn stale_subject(decision: &Decision) -> (String, String) {
    match &decision.basis {
        Some(basis) => (basis.rule_id.to_string(), basis.message.clone()),
        None => ("-".to_owned(), format!("finding {}", decision.finding)),
    }
}

/// `accepted by A. Reviewer on 2026-09-27T08:00:00Z: comment`, then what
/// changed since, if anything.
fn decision_text(
    status: DecisionStatus,
    author: &str,
    date: &axioval::ir::DateTime,
    comment: &str,
) -> String {
    let mut text = format!("{} by {author} on {date}", status.as_str());
    if !comment.trim().is_empty() {
        let _ = write!(text, ": {}", comment.trim());
    }
    text
}

fn carried_text(decision: &FindingDecision) -> String {
    let mut text = decision_text(
        decision.status,
        &decision.author,
        &decision.date,
        &decision.comment,
    );
    match decision.evidence {
        EvidenceCheck::Unchanged => {}
        EvidenceCheck::Unknown => text.push_str(" (changes unknown: no basis recorded)"),
        EvidenceCheck::Changed => {
            let changes: Vec<String> = decision
                .changes
                .iter()
                .map(|c| format!("{} {} -> {}", c.facet.as_str(), c.decided, c.now))
                .collect();
            let _ = write!(text, " (changed since: {})", changes.join("; "));
        }
    }
    text
}

/// Rules by status: how many of each, and the rules themselves, those that
/// did not pass first, at most `top`.
#[derive(Debug, Serialize)]
pub struct RulesDigest {
    pub counts: BTreeMap<&'static str, usize>,
    pub rules: Vec<RuleLine>,
    /// Rules left out by the `top` limit.
    pub omitted: usize,
}

/// One rule's counts.
#[derive(Debug, Serialize)]
pub struct RuleLine {
    pub rule: String,
    pub status: &'static str,
    pub checked: usize,
    pub failed: usize,
    pub not_evaluated: usize,
}

fn rule_status(status: RuleStatus) -> &'static str {
    match status {
        RuleStatus::Failed => "failed",
        RuleStatus::NotEvaluated => "not evaluated",
        RuleStatus::NothingSelected => "nothing selected",
        RuleStatus::Passed => "passed",
        RuleStatus::Skipped => "skipped",
    }
}

/// The rules digest of `report`; `None` when it records no rule status.
fn rules_digest(report: &Report, top: usize) -> Option<RulesDigest> {
    if report.rules().is_empty() {
        return None;
    }
    let rank = |status: RuleStatus| match status {
        RuleStatus::Failed => 0,
        RuleStatus::NotEvaluated => 1,
        RuleStatus::NothingSelected => 2,
        RuleStatus::Passed => 3,
        RuleStatus::Skipped => 4,
    };
    let mut ordered: Vec<_> = report.rules().iter().collect();
    ordered.sort_by(|a, b| {
        rank(a.status)
            .cmp(&rank(b.status))
            .then_with(|| a.rule_id.cmp(&b.rule_id))
    });
    let mut counts = BTreeMap::new();
    for summary in &ordered {
        *counts.entry(rule_status(summary.status)).or_default() += 1;
    }
    let rules: Vec<RuleLine> = ordered
        .iter()
        .take(top)
        .map(|summary| RuleLine {
            rule: summary.rule_id.to_string(),
            status: rule_status(summary.status),
            checked: summary.checked,
            failed: summary.failed,
            not_evaluated: summary.not_evaluated,
        })
        .collect();
    Some(RulesDigest {
        counts,
        omitted: ordered.len() - rules.len(),
        rules,
    })
}

/// The head of a comparison's summary.
#[derive(Debug, Serialize)]
pub struct ComparisonDigest {
    pub base: String,
    pub revised: String,
    pub facets: Vec<String>,
    pub counts: ComparisonCounts,
}

pub fn status(report: &Report) -> &'static str {
    if !report.findings().is_empty() {
        "findings"
    } else if !report.not_evaluated().is_empty() {
        "incomplete"
    } else {
        "passed"
    }
}

fn severity(severity: &Severity) -> &'static str {
    match severity {
        Severity::Error => "error",
        Severity::Warning => "warning",
        Severity::Info => "info",
    }
}

fn reason(reason: &NotEvaluatedReason) -> &'static str {
    match reason {
        NotEvaluatedReason::MissingService => "missing-service",
        NotEvaluatedReason::BackendUnavailable => "backend-unavailable",
        NotEvaluatedReason::IncompleteEvidence => "incomplete-evidence",
        NotEvaluatedReason::InvalidEvidence => "invalid-evidence",
        NotEvaluatedReason::InvalidDeclaration => "invalid-declaration",
        NotEvaluatedReason::UnboundConcept => "unbound-concept",
        NotEvaluatedReason::NotRecorded => "not-recorded",
        NotEvaluatedReason::ResourceLimit => "resource-limit",
    }
}

fn elide(message: &str, budget: usize) -> String {
    let message = message.trim();
    match message.char_indices().nth(budget) {
        Some((cut, _)) => format!("{}…", &message[..cut]),
        None => message.to_owned(),
    }
}

/// `message` with every `#<digits>` instance reference replaced by `#…`.
///
/// Messages that differ only in which instance they name say the same thing;
/// counting them as distinct would report 95 kinds of one problem.
fn shape(message: &str) -> String {
    let mut out = String::with_capacity(message.len());
    let mut chars = message.chars().peekable();
    while let Some(c) = chars.next() {
        out.push(c);
        if c == '#' && chars.peek().is_some_and(char::is_ascii_digit) {
            while chars.peek().is_some_and(char::is_ascii_digit) {
                chars.next();
            }
            out.push('…');
        }
    }
    out
}

/// Accumulates one group while scanning.
#[derive(Default)]
struct Tally {
    count: usize,
    /// Message shape -> (occurrences, first message of that shape).
    messages: BTreeMap<String, (usize, String)>,
    examples: Vec<String>,
}

impl Tally {
    fn add(&mut self, message: &str, example: Option<String>) {
        self.count += 1;
        let message = message.trim();
        self.messages
            .entry(shape(message))
            .or_insert_with(|| (0, message.to_owned()))
            .0 += 1;
        if let Some(example) = example
            && self.examples.len() < EXAMPLES
        {
            self.examples.push(example);
        }
    }

    fn into_group(self, section: Section, key: String, level: String) -> Group {
        // Most frequent first; ties by text, so the choice is deterministic.
        let message = self
            .messages
            .iter()
            .max_by(|a, b| a.1.0.cmp(&b.1.0).then_with(|| b.0.cmp(a.0)))
            .map(|(_, (_, text))| elide(text, MESSAGE_BUDGET))
            .unwrap_or_default();
        Group {
            section,
            key,
            level,
            count: self.count,
            distinct_messages: self.messages.len(),
            message,
            examples: self.examples,
        }
    }
}

/// Digests `output`, keeping at most `top` groups per section.
///
/// `saved` is where the full result is, for the drill-down hints; `None` when
/// it was not written to a file and so cannot be queried.
/// Tallies every entry of `output` by section, key and level.
fn tally(output: &CheckOutput) -> BTreeMap<(Section, String, String), Tally> {
    let qualify = output.several_documents();
    let mut tallies: BTreeMap<(Section, String, String), Tally> = BTreeMap::new();
    for finding in output.report.findings() {
        tallies
            .entry((
                Section::Findings,
                finding.rule_id.to_string(),
                severity(&finding.severity).to_owned(),
            ))
            .or_default()
            .add(
                &finding.message,
                // A source or project finding names its scope in its
                // message; an example is always an object to drill into.
                finding.object_id().map(|id| output.describe(id, qualify)),
            );
    }
    for outcome in output.report.not_evaluated() {
        tallies
            .entry((
                Section::NotEvaluated,
                outcome.rule_id.to_string(),
                reason(&outcome.reason).to_owned(),
            ))
            .or_default()
            .add(
                &outcome.message,
                outcome.object_id().map(|id| output.describe(id, qualify)),
            );
    }
    for record in &output.integrity {
        tallies
            .entry((
                Section::Integrity,
                record.code.clone(),
                record.severity.clone(),
            ))
            .or_default()
            .add(&record.message, None);
    }
    for unmeasured in output.geometry.iter().flat_map(|g| &g.unmeasured) {
        // Grouped by the kind of failure, the text before any detail.
        let class = unmeasured
            .reason
            .split(':')
            .next()
            .unwrap_or(&unmeasured.reason)
            .trim()
            .to_owned();
        tallies
            .entry((Section::Geometry, class, "unmeasured".to_owned()))
            .or_default()
            .add(
                &unmeasured.reason,
                Some(output.describe(&unmeasured.object, qualify)),
            );
    }
    // Stale decisions by the rule and status they were recorded with.
    for decision in output.report.stale_decisions() {
        let (rule, message) = stale_subject(decision);
        tallies
            .entry((
                Section::StaleDecisions,
                rule,
                decision.status.as_str().to_owned(),
            ))
            .or_default()
            .add(&message, None);
    }
    // One group per table: its rows are the count, its columns the message.
    for table in output.report.tables() {
        let columns = columns_text(table);
        let tally = tallies
            .entry((
                Section::Tables,
                table.rule_id().to_string(),
                table.name().to_owned(),
            ))
            .or_default();
        for row in table.rows() {
            tally.add(
                &columns,
                row.scope().object().map(|id| output.describe(id, qualify)),
            );
        }
    }

    tallies
}

pub fn summarize(output: &CheckOutput, top: usize, saved: Option<&str>) -> Summary {
    let tallies = tally(output);
    let mut groups: Vec<Group> = tallies
        .into_iter()
        .map(|((section, key, level), tally)| tally.into_group(section, key, level))
        .collect();
    // Within a section: the most severe level first, then the largest group.
    let rank = |level: &str| match level {
        "error" => 0,
        "warning" => 1,
        _ => 2,
    };
    groups.sort_by(|a, b| {
        a.section
            .cmp(&b.section)
            .then(rank(&a.level).cmp(&rank(&b.level)))
            .then(b.count.cmp(&a.count))
            .then_with(|| a.key.cmp(&b.key))
    });
    let mut kept = Vec::new();
    let mut omitted_groups = BTreeMap::new();
    let mut shown: BTreeMap<Section, usize> = BTreeMap::new();
    for group in groups {
        let seen = shown.entry(group.section).or_default();
        if *seen < top {
            *seen += 1;
            kept.push(group);
        } else {
            *omitted_groups.entry(group.section.label()).or_default() += 1;
        }
    }

    let mut next = next_steps(&kept, &omitted_groups, top, saved);
    let missing_service = output
        .report
        .not_evaluated()
        .iter()
        .any(|n| n.reason == NotEvaluatedReason::MissingService);
    if output.geometry.is_none() && missing_service {
        let command = if output.comparison.is_some() {
            "compare"
        } else {
            "check"
        };
        next.push(format!(
            "some rules lack an evidence service; if they are geometric, rerun `axioval {command}` with --geometry"
        ));
    }
    Summary {
        status: status(&output.report),
        findings: output.report.findings().len(),
        not_evaluated: output.report.not_evaluated().len(),
        integrity: output.integrity.len(),
        geometry: output.geometry.as_ref().map(|g| GeometryCounts {
            exact: g.exact,
            tessellated: g.tessellated,
            no_body: g.no_body,
            unmeasured: g.unmeasured.len(),
        }),
        comparison: output.comparison.as_ref().map(|c| ComparisonDigest {
            base: c.base.clone(),
            revised: c.revised.clone(),
            facets: c.facets.clone(),
            counts: c.counts,
        }),
        rules: rules_digest(&output.report, top),
        decisions: decision_counts(&output.report),
        groups: kept,
        omitted_groups,
        next,
    }
}

fn next_steps(
    groups: &[Group],
    omitted: &BTreeMap<&'static str, usize>,
    top: usize,
    saved: Option<&str>,
) -> Vec<String> {
    let Some(path) = saved else {
        return if groups.is_empty() {
            vec![]
        } else {
            vec!["rerun with --report <file> to list entries with `axioval report`".into()]
        };
    };
    let quoted = shell_quote(path);
    let mut next = Vec::new();
    if let Some(group) = groups.first() {
        next.push(match group.section {
            Section::Integrity => {
                format!("axioval report {quoted} --code {}", shell_quote(&group.key))
            }
            Section::Geometry => format!("axioval report {quoted} --section geometry"),
            Section::StaleDecisions => {
                format!("axioval report {quoted} --section stale-decisions")
            }
            Section::Tables => format!(
                "axioval report {quoted} --section tables --rule {}",
                shell_quote(&group.key)
            ),
            _ => format!("axioval report {quoted} --rule {}", shell_quote(&group.key)),
        });
    }
    // Unmeasured bodies qualify every geometric answer, so they get their own
    // step even when a larger group comes first.
    if groups
        .first()
        .is_some_and(|g| g.section != Section::Geometry)
        && groups.iter().any(|g| g.section == Section::Geometry)
    {
        next.push(format!("axioval report {quoted} --section geometry"));
    }
    // A stale decision is a reviewed finding that is gone: worth a look.
    if groups
        .first()
        .is_some_and(|g| g.section != Section::StaleDecisions)
        && groups.iter().any(|g| g.section == Section::StaleDecisions)
    {
        next.push(format!("axioval report {quoted} --section stale-decisions"));
    }
    // Measured values are what a reader asks for next once issues are known.
    if groups.first().is_some_and(|g| g.section != Section::Tables)
        && groups.iter().any(|g| g.section == Section::Tables)
    {
        next.push(format!("axioval report {quoted} --section tables"));
    }
    if let Some(example) = groups.iter().flat_map(|g| &g.examples).next() {
        let id = example.split(' ').next().unwrap_or(example);
        next.push(format!(
            "axioval report {quoted} --object {} --evidence",
            shell_quote(id)
        ));
    }
    if !omitted.is_empty() {
        next.push(format!("axioval report {quoted} --top {}", top * 5));
    }
    next
}

/// `text` as one POSIX shell word. `#` and `$` are quoted: an unquoted `#`
/// starts a comment and `$` expands, and both occur in ids.
pub fn shell_quote(text: &str) -> String {
    if text
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || "-_./:".contains(c))
    {
        text.to_owned()
    } else {
        format!("'{}'", text.replace('\'', r"'\''"))
    }
}

pub fn render_summary(summary: &Summary) -> String {
    let mut out = String::new();
    // A comparison says first what was compared with what.
    if let Some(comparison) = &summary.comparison {
        let counts = comparison.counts;
        let _ = writeln!(
            out,
            "compared: {} -> {} · {}",
            comparison.base,
            comparison.revised,
            comparison.facets.join(", ")
        );
        let _ = writeln!(
            out,
            "objects: {} added · {} removed · {} changed · {} unchanged · {} incomplete · {} unidentified · {} ambiguous",
            counts.added,
            counts.removed,
            counts.changed,
            counts.unchanged,
            counts.incomplete,
            counts.unidentified,
            counts.ambiguous
        );
    }
    let _ = writeln!(
        out,
        "status: {} · {} finding(s) · {} not evaluated · {} integrity issue(s)",
        summary.status, summary.findings, summary.not_evaluated, summary.integrity
    );
    if let Some(geometry) = &summary.geometry {
        let _ = writeln!(
            out,
            "geometry: {} exact · {} tessellated · {} without body · {} unmeasured",
            geometry.exact, geometry.tessellated, geometry.no_body, geometry.unmeasured
        );
    }
    if let Some(rules) = &summary.rules {
        let counts: Vec<String> = ["failed", "not evaluated", "nothing selected", "passed"]
            .iter()
            .filter_map(|status| {
                rules
                    .counts
                    .get(status)
                    .map(|count| format!("{count} {status}"))
            })
            .collect();
        let _ = writeln!(out, "\nrules: {}", counts.join(" · "));
        for rule in &rules.rules {
            let _ = writeln!(
                out,
                "  {:<16}  {:>6} checked · {} failed · {} not evaluated  {}",
                rule.status, rule.checked, rule.failed, rule.not_evaluated, rule.rule
            );
        }
        if rules.omitted > 0 {
            let _ = writeln!(out, "  … {} more rule(s)", rules.omitted);
        }
    }
    if let Some(decisions) = &summary.decisions {
        out.push_str(&decisions.line());
    }
    let mut section = None;
    for group in &summary.groups {
        if section != Some(group.section) {
            section = Some(group.section);
            let _ = writeln!(out, "\n{}:", group.section.label());
        }
        let _ = write!(
            out,
            "  {:>6}  {:<7}  {}",
            group.count, group.level, group.key
        );
        if group.distinct_messages > 1 {
            let _ = write!(out, "  ({} distinct messages)", group.distinct_messages);
        }
        let _ = writeln!(out, "\n          {}", group.message);
        if !group.examples.is_empty() {
            let more = group.count.saturating_sub(group.examples.len());
            let _ = write!(out, "          e.g. {}", group.examples.join("; "));
            if more > 0 {
                let _ = write!(out, "; +{more} more");
            }
            out.push('\n');
        }
    }
    for (section, count) in &summary.omitted_groups {
        let _ = writeln!(out, "  … {count} more {section} group(s)");
    }
    if !summary.next.is_empty() {
        out.push_str("\nnext:\n");
        for step in &summary.next {
            let _ = writeln!(out, "  {step}");
        }
    }
    out
}

/// What a listing selects. Every present filter must match.
pub struct Filter {
    pub section: Option<Section>,
    pub rule: Option<String>,
    pub code: Option<String>,
    pub object: Option<String>,
    /// A storey or space; only located findings and outcomes match.
    pub location: Option<String>,
    /// A decision; only findings match.
    pub decision: Option<DecisionFilter>,
}

/// The `report --decision` values.
#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum)]
pub enum DecisionFilter {
    Accepted,
    Rejected,
    Open,
    /// No decision.
    Undecided,
    /// Decided, and changed since the decision.
    Changed,
}

impl DecisionFilter {
    fn matches(self, decision: Option<&FindingDecision>) -> bool {
        match (self, decision) {
            (Self::Undecided, None) => true,
            (_, None) | (Self::Undecided, Some(_)) => false,
            (Self::Accepted, Some(d)) => d.status == DecisionStatus::Accepted,
            (Self::Rejected, Some(d)) => d.status == DecisionStatus::Rejected,
            (Self::Open, Some(d)) => d.status == DecisionStatus::Open,
            (Self::Changed, Some(d)) => d.evidence == EvidenceCheck::Changed,
        }
    }
}

/// One listed entry.
#[derive(Debug, Serialize)]
pub struct Entry {
    pub section: Section,
    /// Rule id, or integrity code.
    pub key: String,
    /// Severity, or not-evaluated reason.
    pub level: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub object: Option<String>,
    /// `source <document>` or `project` for an entry about no single object.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub scope: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub related: Vec<String>,
    /// The storeys and spaces a located entry lies in.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub location: Option<String>,
    pub message: String,
    /// The finding's identity, to record a decision against.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<String>,
    /// The decision about the finding, as text.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub decision: Option<String>,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub evidence: Vec<String>,
}

#[derive(Debug, Serialize)]
pub struct Listing {
    pub total: usize,
    pub offset: usize,
    pub entries: Vec<Entry>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next: Option<String>,
}

#[allow(clippy::too_many_lines)]
/// Entries matching `filter`, paged. Evidence locators are long and rarely
/// needed, so they are included only on request.
pub fn list(
    output: &CheckOutput,
    filter: &Filter,
    offset: usize,
    limit: usize,
    evidence: bool,
    command: &str,
) -> Listing {
    let qualify = output.several_documents();
    let wants = |section: Section| filter.section.is_none_or(|wanted| wanted == section);
    let rule_ok = |rule: &str| filter.rule.as_deref().is_none_or(|wanted| wanted == rule);
    let place_ok = |location: Option<&Location>| {
        filter
            .location
            .as_deref()
            .is_none_or(|query| output.located(location, query))
    };
    // Only findings and not-evaluated outcomes are located, and only
    // findings decided.
    let unlocated = filter.location.is_none() && filter.decision.is_none();
    let decision_ok = |decision: Option<&FindingDecision>| {
        filter
            .decision
            .is_none_or(|wanted| wanted.matches(decision))
    };
    let mut matched: Vec<Entry> = Vec::new();

    // `--code` names integrity issues only; rules never match it.
    if filter.code.is_none() {
        if wants(Section::Findings) {
            let findings = output.report.findings().iter().filter(|finding| {
                rule_ok(&finding.rule_id.to_string())
                    && place_ok(finding.location.as_ref())
                    && decision_ok(finding.decision.as_ref())
                    && filter.object.as_deref().is_none_or(|query| {
                        names_source(&finding.scope, query)
                            || finding
                                .object_id()
                                .into_iter()
                                .chain(&finding.related)
                                .any(|id| output.names(id, query))
                    })
            });
            matched.extend(findings.map(|f| finding_entry(output, f, qualify, evidence)));
        }
        if wants(Section::NotEvaluated) && filter.decision.is_none() {
            let outcomes = output.report.not_evaluated().iter().filter(|outcome| {
                rule_ok(&outcome.rule_id.to_string())
                    && place_ok(outcome.location.as_ref())
                    && filter.object.as_deref().is_none_or(|query| {
                        names_source(&outcome.scope, query)
                            || outcome
                                .object_id()
                                .is_some_and(|id| output.names(id, query))
                    })
            });
            matched.extend(outcomes.map(|o| not_evaluated_entry(output, o, qualify)));
        }
    }
    if unlocated && filter.rule.is_none() && wants(Section::Integrity) {
        let records = output.integrity.iter().filter(|record| {
            filter
                .code
                .as_deref()
                .is_none_or(|code| code == record.code)
                && filter
                    .object
                    .as_deref()
                    .is_none_or(|query| mentions(&record.message, query))
        });
        matched.extend(records.map(|record| Entry {
            id: None,
            decision: None,
            section: Section::Integrity,
            key: record.code.clone(),
            level: record.severity.clone(),
            object: None,
            scope: None,
            related: vec![],
            location: None,
            message: record.message.trim().to_owned(),
            evidence: if evidence {
                vec![record.locator.clone()]
            } else {
                vec![]
            },
        }));
    }
    if unlocated && filter.rule.is_none() && filter.code.is_none() && wants(Section::Geometry) {
        let unmeasured = output
            .geometry
            .iter()
            .flat_map(|g| &g.unmeasured)
            .filter(|u| {
                filter
                    .object
                    .as_deref()
                    .is_none_or(|query| output.names(&u.object, query))
            });
        matched.extend(unmeasured.map(|u| Entry {
            id: None,
            decision: None,
            section: Section::Geometry,
            key: "unmeasured".to_owned(),
            level: "unmeasured".to_owned(),
            object: Some(output.describe(&u.object, qualify)),
            scope: None,
            related: vec![],
            location: None,
            message: u.reason.clone(),
            evidence: vec![],
        }));
    }

    if unlocated && filter.code.is_none() && wants(Section::Tables) {
        matched.extend(table_entries(output, filter, qualify));
    }

    // A stale decision names no object that is still reported.
    if unlocated
        && filter.code.is_none()
        && filter.object.is_none()
        && wants(Section::StaleDecisions)
    {
        for decision in output.report.stale_decisions() {
            let (rule, message) = stale_subject(decision);
            if !rule_ok(&rule) {
                continue;
            }
            matched.push(Entry {
                section: Section::StaleDecisions,
                key: rule,
                level: decision.status.as_str().to_owned(),
                object: None,
                scope: None,
                related: vec![],
                location: None,
                message,
                id: Some(decision.finding.to_string()),
                decision: Some(decision_text(
                    decision.status,
                    &decision.author,
                    &decision.date,
                    &decision.comment,
                )),
                evidence: vec![],
            });
        }
    }

    let total = matched.len();
    let entries: Vec<Entry> = matched.into_iter().skip(offset).take(limit).collect();
    let end = offset + entries.len();
    let next = (end < total).then(|| format!("{command} --offset {end}"));
    Listing {
        total,
        offset,
        entries,
        next,
    }
}

/// The rows of the report's tables that `filter`'s rule and object select,
/// in table order.
fn table_entries(output: &CheckOutput, filter: &Filter, qualify: bool) -> Vec<Entry> {
    let mut entries = Vec::new();
    for table in output.report.tables() {
        if filter
            .rule
            .as_deref()
            .is_some_and(|wanted| wanted != table.rule_id().to_string())
        {
            continue;
        }
        let rows = table.rows().iter().filter(|row| {
            filter.object.as_deref().is_none_or(|query| {
                names_source(row.scope(), query)
                    || row
                        .scope()
                        .object()
                        .is_some_and(|id| output.names(id, query))
            })
        });
        entries.extend(rows.map(|row| {
            let (object, scope) = subject_fields(output, row.scope(), qualify);
            Entry {
                id: None,
                decision: None,
                section: Section::Tables,
                key: table.rule_id().to_string(),
                level: table.name().to_owned(),
                object,
                scope,
                related: vec![],
                location: None,
                message: format!("{}{}", group_text(row), row_text(table, row.values())),
                evidence: vec![],
            }
        }));
    }
    entries
}

/// Whether `query` names the source a source-scoped entry is about, by its
/// full id or its document.
fn names_source(scope: &Scope, query: &str) -> bool {
    match scope {
        Scope::Source(SourceId { system, document }) => {
            query == document || query == format!("{system}:{document}")
        }
        Scope::Project | Scope::Object(_) => false,
    }
}

/// The `object` and `scope` fields of an entry about `scope`.
fn subject_fields(
    output: &CheckOutput,
    scope: &Scope,
    qualify: bool,
) -> (Option<String>, Option<String>) {
    let text = output.subject(scope, qualify);
    match scope {
        Scope::Object(_) => (Some(text), None),
        Scope::Source(_) | Scope::Project => (None, Some(text)),
    }
}

/// Whether `message` names `local` as a whole token: `#12` is not in `#123`.
fn mentions(message: &str, local: &str) -> bool {
    message.match_indices(local).any(|(at, _)| {
        let before = message[..at].chars().next_back();
        let after = message[at + local.len()..].chars().next();
        !before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric)
    })
}

fn finding_entry(output: &CheckOutput, finding: &Finding, qualify: bool, evidence: bool) -> Entry {
    let (object, scope) = subject_fields(output, &finding.scope, qualify);
    Entry {
        section: Section::Findings,
        key: finding.rule_id.to_string(),
        level: severity(&finding.severity).to_owned(),
        object,
        scope,
        related: finding
            .related
            .iter()
            .map(|id| output.describe(id, qualify))
            .collect(),
        location: finding
            .location
            .as_ref()
            .map(|location| location_text(location, qualify)),
        message: finding.message.trim().to_owned(),
        id: finding.id.map(|id| id.to_string()),
        decision: finding.decision.as_ref().map(carried_text),
        evidence: if evidence {
            finding
                .evidence
                .iter()
                .map(|e| {
                    let exactness = if e.exact { "exact" } else { "inexact" };
                    format!("{} ({exactness})", e.locator)
                })
                .collect()
        } else {
            vec![]
        },
    }
}

fn not_evaluated_entry(output: &CheckOutput, outcome: &NotEvaluated, qualify: bool) -> Entry {
    let (object, scope) = subject_fields(output, &outcome.scope, qualify);
    Entry {
        id: None,
        decision: None,
        section: Section::NotEvaluated,
        key: outcome.rule_id.to_string(),
        level: reason(&outcome.reason).to_owned(),
        object,
        scope,
        related: vec![],
        location: outcome
            .location
            .as_ref()
            .map(|location| location_text(location, qualify)),
        message: outcome.message.trim().to_owned(),
        evidence: vec![],
    }
}

pub fn render_listing(listing: &Listing) -> String {
    let mut out = String::new();
    for entry in &listing.entries {
        let _ = write!(
            out,
            "[{}] {} {}",
            entry.section.label(),
            entry.level,
            entry.key
        );
        if let Some(object) = &entry.object {
            let _ = write!(out, "  {object}");
        }
        if let Some(scope) = &entry.scope {
            let _ = write!(out, "  ({scope})");
        }
        let _ = writeln!(out, "\n    {}", entry.message);
        if let Some(id) = &entry.id {
            let _ = writeln!(out, "    id: {id}");
        }
        if let Some(decision) = &entry.decision {
            let _ = writeln!(out, "    decision: {decision}");
        }
        if !entry.related.is_empty() {
            let _ = writeln!(out, "    related: {}", entry.related.join("; "));
        }
        if let Some(location) = &entry.location {
            let _ = writeln!(out, "    location: {location}");
        }
        for evidence in &entry.evidence {
            let _ = writeln!(out, "    evidence: {evidence}");
        }
    }
    if listing.total == 0 {
        out.push_str("no matching entries\n");
    } else {
        let _ = writeln!(
            out,
            "showing {}–{} of {}",
            listing.offset + 1,
            listing.offset + listing.entries.len(),
            listing.total
        );
    }
    if let Some(next) = &listing.next {
        let _ = writeln!(out, "next: {next}");
    }
    out
}

#[cfg(test)]
mod tests {
    use super::{elide, mentions, shape};

    #[test]
    fn messages_differing_only_in_instances_share_a_shape() {
        assert_eq!(
            shape("#157259 has no end; see #12"),
            shape("#204035 has no end; see #9")
        );
        assert_ne!(shape("#1 has no end"), shape("#1 has no start"));
        assert_eq!(shape("C# and #x stay"), "C# and #x stay");
    }

    #[test]
    fn token_mentions_do_not_match_prefixes() {
        assert!(mentions("#12 has GlobalId 'x'", "#12"));
        assert!(mentions("claimed by #3, #12", "#12"));
        assert!(!mentions("#123 has GlobalId 'x'", "#12"));
        assert!(!mentions("#1242", "#12"));
    }

    #[test]
    fn elision_counts_characters_not_bytes() {
        assert_eq!(elide("äöü", 2), "äö…");
        assert_eq!(elide("  short  ", 10), "short");
    }
}