mahbot 0.10.2

An autonomous agentic engineering system that manages software development through role separation, subagents, and deterministic diagnostics.
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
//! PDF marks: the document's own description, its annotations and its form fields, as
//! document-text blocks.
//!
//! This is the metadata/annotation/form arm of [`crate::document`]'s PDF reading: what the
//! document says about itself (the Info dictionary), the marks beside the text — comments,
//! highlights, stamps, free text and signatures — and the AcroForm fields a user fills in.
//!
//! - **Read-only.** Nothing here writes or holds state: the walk runs off the already-parsed
//!   [`Pdf`] the caller opened.
//! - **No panics of its own**, for any file: the walk runs inside
//!   [`crate::shutdown::contain_panics`], so a panic costs the marks and nothing else.
//! - **One page never costs another.** An annotation or field that cannot be read is skipped,
//!   never an error: the marks around it keep theirs.
//! - **The walking is bounded.** The field tree has a depth cap and a visited-object set, both
//!   walks are capped by [`MAX_MARKS`]/[`MAX_FIELDS`], and a field's printed option list by
//!   [`MAX_FIELD_OPTIONS`]; a cap that truncates is named in [`Marks::notes`].
//! - **A field is listed with the state it is in.** Every field a fill can reach is listed, even
//!   with no value; one it cannot reach is listed as not fillable. No value is ever invented.
//! - **One object is one entry.** Identity is the dictionary's own bytes, so a mark listed on two
//!   pages is one mark while two dictionaries written into one array stay two.

use crate::reader_output::{Unshown, UnshownKind};
use crate::util::html::decode_html_entities;
use crate::util::one_line;
use hayro::hayro_syntax::Pdf;
use hayro::hayro_syntax::object::dict::Dict;
use hayro::hayro_syntax::object::{Array, DateTime, Name, Object, String as PdfString};
use std::collections::{HashMap, HashSet};

/// Maximum annotations reported for one document, so a file whose `/Annots` are a cycle cannot
/// make the reading unbounded.
const MAX_MARKS: usize = 1000;

/// Maximum form fields reported for one document, for the same reason.
const MAX_FIELDS: usize = 1000;

/// Maximum options printed for one form field: a list box whose `/Opt` is a cycle.
const MAX_FIELD_OPTIONS: usize = 100;

/// Maximum depth of the field tree, so a file whose `/Kids` point in a cycle terminates.
const MAX_FIELD_DEPTH: usize = 32;

/// What tells one dictionary from another within one document: the bytes it was parsed from. The
/// engine resolves a reference to the very bytes it points at and caches a decoded object stream,
/// so one object resolves to one slice — while two dictionaries written directly into one array
/// are two slices. [`Dict::obj_id`] cannot serve as an identity: it is the *enclosing* indirect
/// object's id, so every direct dictionary in one array would collapse onto the same one.
type DictId = (usize, usize);

fn dict_id(dict: &Dict<'_>) -> DictId {
    let data = dict.data();
    (data.as_ptr().addr(), data.len())
}

/// Body of the note shown when a document carries a form but no field a fill can reach.
const NO_FILLABLE_FIELDS_NOTE: &str = "the document has a form, but no field that can be filled";

/// Body of the note shown when a document's `/AcroForm` exists but cannot be read.
const FIELDS_UNREADABLE_NOTE: &str = "the document has a form, but its fields could not be read";

/// `/F` bit 2: the annotation is hidden from the reader.
const ANNOT_FLAG_HIDDEN: i32 = 2;
/// `/F` bit 5: the annotation is not shown or printed.
const ANNOT_FLAG_NO_VIEW: i32 = 32;
/// `/Ff` bit 16: a `Btn` field is a radio group.
const FIELD_FLAG_RADIO: i32 = 1 << 15;
/// `/Ff` bit 17: a `Btn` field is a pushbutton, which carries no value.
const FIELD_FLAG_PUSH_BUTTON: i32 = 1 << 16;
/// `/Ff` bit 18: a `Ch` field is a combo box (a dropdown), whose value a filler may type.
const FIELD_FLAG_COMBO: i32 = 1 << 17;

/// What a PDF says beside its page text: its own description, its annotations and its form fields.
#[derive(Debug, Default)]
pub(crate) struct Marks {
    /// The ready `Description:` section; `None` when the document has none.
    pub(crate) description: Option<String>,
    /// The ready `Annotations:` section; `None` when the document has no mark.
    pub(crate) annotations: Option<String>,
    /// The ready `Form fields:` section; `None` when no field a fill can reach exists.
    pub(crate) fields: Option<String>,
    pub(crate) notes: Vec<String>,
    /// The content the marks themselves carry and the reading does not show: the file an attachment
    /// holds, the media a sound/movie/screen annotation plays.
    pub(crate) unshown: Unshown,
}

/// Read `pdf`'s own description, its annotations and its form fields.
///
/// The walk is contained exactly like [`crate::document`]'s PDF passes: a panic in a malformed
/// object yields [`Marks::default`] rather than reaching the caller, so one bad document can
/// never cost the conversion its page text too.
#[must_use]
pub(crate) fn read(pdf: &Pdf) -> Marks {
    crate::shutdown::contain_panics(|| read_inner(pdf)).unwrap_or_default()
}

fn read_inner(pdf: &Pdf) -> Marks {
    let mut marks = Marks {
        description: read_description(pdf),
        ..Marks::default()
    };
    let walk = read_annotations(pdf);
    if !walk.lines.is_empty() {
        marks.annotations = Some(format!("Annotations:\n{}", walk.lines.join("\n")));
    }
    marks.unshown = walk.unshown;
    if walk.truncated {
        marks
            .notes
            .push(format!("only the first {MAX_MARKS} annotations were read"));
    }

    let catalog = pdf.xref().get::<Dict<'_>>(pdf.xref().root_id());
    let acroform = catalog.and_then(|catalog| catalog.get::<Dict<'_>>(b"AcroForm"));
    let mut fields_unreadable = false;
    if let Some(acroform) = &acroform {
        match read_fields(acroform, &walk.widget_pages) {
            Some(fields) => {
                if !fields.lines.is_empty() {
                    marks.fields = Some(format!(
                        "{}:\n{}",
                        crate::docgen::pdf_form_words().fields,
                        fields.lines.join("\n")
                    ));
                }
                if fields.truncated {
                    marks
                        .notes
                        .push(format!("only the first {MAX_FIELDS} form fields were read"));
                }
                if fields.options_truncated {
                    marks.notes.push(format!(
                        "only the first {MAX_FIELD_OPTIONS} options of a form field were listed"
                    ));
                }
            }
            None => fields_unreadable = true,
        }
    }
    if fields_unreadable {
        marks.notes.push(FIELDS_UNREADABLE_NOTE.to_string());
    } else if acroform.is_some() && marks.fields.is_none() {
        marks.notes.push(NO_FILLABLE_FIELDS_NOTE.to_string());
    }
    marks
}

/// The `Description:` block from the document's Info dictionary — only the entries it really
/// carries.
fn read_description(pdf: &Pdf) -> Option<String> {
    let metadata = pdf.metadata();
    let mut entries: Vec<(&str, String)> = Vec::new();
    for field in crate::docgen::pdf_metadata_fields() {
        let value = match field.key.as_str() {
            "created" => metadata.creation_date.map(format_date),
            "modified" => metadata.modification_date.map(format_date),
            "title" => metadata.title.as_deref().and_then(description_text),
            "author" => metadata.author.as_deref().and_then(description_text),
            "subject" => metadata.subject.as_deref().and_then(description_text),
            "keywords" => metadata.keywords.as_deref().and_then(description_text),
            "creator" => metadata.creator.as_deref().and_then(description_text),
            "producer" => metadata.producer.as_deref().and_then(description_text),
            _ => None,
        };
        if let Some(value) = value {
            entries.push((field.key.as_str(), value));
        }
    }
    (!entries.is_empty()).then(|| {
        let body = entries
            .into_iter()
            .map(|(label, value)| format!("{label}: {value}"))
            .collect::<Vec<_>>()
            .join("\n");
        crate::reader_output::labeled_block("Description", &body)
    })
}

/// One text entry of the description, decoded and collapsed to one line. `None` when it holds
/// nothing readable.
fn description_text(bytes: &[u8]) -> Option<String> {
    let text = one_line(decode_text_string(bytes).trim().to_string());
    (!text.is_empty()).then_some(text)
}

/// A PDF date as `YYYY-MM-DDTHH:MM:SS` with `Z` for a zero offset or an explicit one.
fn format_date(date: DateTime) -> String {
    let calendar = format!(
        "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}",
        date.year, date.month, date.day, date.hour, date.minute, date.second
    );
    if date.utc_offset_hour == 0 && date.utc_offset_minute == 0 {
        format!("{calendar}Z")
    } else {
        format!(
            "{calendar}{:+03}:{:02}",
            date.utc_offset_hour, date.utc_offset_minute
        )
    }
}

#[derive(Default)]
struct AnnotationWalk {
    /// One line per mark, in page order and then in each page's `/Annots` order.
    lines: Vec<String>,
    /// The page each `/Widget` annotation sits on, so a field can be named with it.
    widget_pages: HashMap<DictId, usize>,
    truncated: bool,
    /// The annotations that are no mark but still hold content — an attached file, media.
    unshown: Unshown,
}

/// Walk every page's `/Annots` once: the mark lines, the pages its `/Widget` annotations sit
/// on, and the content they carry.
fn read_annotations(pdf: &Pdf) -> AnnotationWalk {
    let mut walk = AnnotationWalk::default();
    let mut reported: HashSet<DictId> = HashSet::new();
    'pages: for (index, page) in pdf.pages().iter().enumerate() {
        let Some(annots) = page.raw().get::<Array<'_>>(b"Annots") else {
            continue;
        };
        let mut annots = annots.flex_iter();
        while let Some(object) = annots.next::<Object<'_>>() {
            let Some(dict) = object.into_dict() else {
                continue;
            };
            if is_widget(&dict) {
                walk.widget_pages.entry(dict_id(&dict)).or_insert(index + 1);
            }
            // One object, one finding: an annotation listed on another page (or twice on one) is
            // one mark.
            if !reported.insert(dict_id(&dict)) {
                continue;
            }
            let Some(mark) = mark_of(&dict, index + 1) else {
                // An annotation that is no mark can still carry content a reading does not show.
                if !hidden(&dict)
                    && let Some(kind) = annotation_content(&dict)
                {
                    walk.unshown.add(kind, 1);
                }
                continue;
            };
            if walk.lines.len() == MAX_MARKS {
                walk.truncated = true;
                break 'pages;
            }
            walk.lines.push(mark);
        }
    }
    walk
}

/// The one line a mark contributes — `kind (author) on page n`, with the mark's text below.
fn mark_of(dict: &Dict<'_>, page_number: usize) -> Option<String> {
    let kind = mark_kind(dict)?;
    // The document itself hides this mark from the reader; a hidden note is not content.
    if hidden(dict) {
        return None;
    }
    let mut line = match mark_author(dict) {
        Some(author) => format!("{kind} ({author}) on page {page_number}"),
        None => format!("{kind} on page {page_number}"),
    };
    if let Some(text) = mark_text(dict) {
        line.push(':');
        for text_line in text.lines() {
            line.push_str("\n  ");
            line.push_str(text_line);
        }
    }
    Some(line)
}

/// The lowercase kind word for an annotation's `/Subtype`, or `None` when it marks nothing.
fn mark_kind(dict: &Dict<'_>) -> Option<&'static str> {
    let subtype = dict.get::<Name<'_>>(b"Subtype")?;
    match subtype.as_str() {
        "Text" => Some("note"),
        "FreeText" => Some("free text"),
        "Highlight" => Some("highlight"),
        "Underline" => Some("underline"),
        "Squiggly" => Some("squiggly underline"),
        "StrikeOut" => Some("strikeout"),
        "Ink" => Some("ink"),
        "Square" => Some("square"),
        "Circle" => Some("circle"),
        "Polygon" => Some("polygon"),
        "PolyLine" => Some("polyline"),
        "Line" => Some("line"),
        "Caret" => Some("caret"),
        "Stamp" => Some("stamp"),
        "Widget" if is_signature(dict) => Some("signature"),
        _ => None,
    }
}

/// The document content an annotation carries that is not a mark in the text, or `None` when it
/// holds none: a `/FileAttachment` holds a file, a `/Sound`, `/Movie`, `/Screen`, `/RichMedia` or
/// `/3D` annotation holds media the reading never shows. A screen annotation counts only when it
/// really plays media — one whose actions only navigate holds nothing. Subtypes that mark nothing
/// and hold nothing (`/Link`, `/Popup`, `/Redact`, `/PrinterMark`) are no content a model is
/// missing, and an annotation naming a media subtype without carrying any is not counted.
fn annotation_content(dict: &Dict<'_>) -> Option<UnshownKind> {
    let (content, kind) = match dict.get::<Name<'_>>(b"Subtype")?.as_str() {
        "FileAttachment" => (b"FS".as_slice(), UnshownKind::Attachment),
        "Sound" => (b"Sound".as_slice(), UnshownKind::MediaAnnotation),
        "Movie" => (b"Movie".as_slice(), UnshownKind::MediaAnnotation),
        "RichMedia" => (b"RichMediaContent".as_slice(), UnshownKind::MediaAnnotation),
        "3D" => (b"3DD".as_slice(), UnshownKind::MediaAnnotation),
        "Screen" => return plays_media(dict).then_some(UnshownKind::MediaAnnotation),
        _ => return None,
    };
    dict.contains_key(content).then_some(kind)
}

/// Whether a screen annotation plays media rather than doing something else with its actions.
fn plays_media(dict: &Dict<'_>) -> bool {
    if dict.contains_key(b"Movie") {
        return true;
    }
    if dict
        .get::<Object<'_>>(b"A")
        .is_some_and(|action| plays_media_action(&action))
    {
        return true;
    }
    dict.get::<Dict<'_>>(b"AA").is_some_and(|actions| {
        actions.keys().any(|trigger| {
            actions
                .get::<Object<'_>>(trigger)
                .is_some_and(|action| plays_media_action(&action))
        })
    })
}

/// Whether one action — or an array of them — plays media: a `/Rendition` or a
/// `/Movie` action, or one carrying the clip (`/R`) or the movie (`/Movie`)
/// itself. `/Next` chains another action to this one, so a chain is followed.
fn plays_media_action(object: &Object<'_>) -> bool {
    match object {
        Object::Array(array) => {
            let mut actions = array.flex_iter();
            while let Some(action) = actions.next::<Object<'_>>() {
                if plays_media_action(&action) {
                    return true;
                }
            }
            false
        }
        Object::Dict(action) => {
            let plays = action
                .get::<Name<'_>>(b"S")
                .is_some_and(|kind| matches!(kind.as_str(), "Rendition" | "Movie"));
            plays
                || action.contains_key(b"R")
                || action.contains_key(b"Movie")
                || action
                    .get::<Object<'_>>(b"Next")
                    .is_some_and(|next| plays_media_action(&next))
        }
        _ => false,
    }
}

/// Whether `/F` carries the Hidden or NoView flag.
fn hidden(dict: &Dict<'_>) -> bool {
    dict.get::<i32>(b"F")
        .is_some_and(|flags| flags & (ANNOT_FLAG_HIDDEN | ANNOT_FLAG_NO_VIEW) != 0)
}

/// Whether an annotation is the on-page half of a signature field: its `/FT` —
/// its own, or the one it inherits from the field it belongs to — is `/Sig`.
fn is_signature(dict: &Dict<'_>) -> bool {
    inherited(dict, b"FT")
        .and_then(Object::into_name)
        .is_some_and(|name| name.as_str() == "Sig")
}

/// A mark's author: its `/T`, on the one line ([`one_line`]) the kind word and
/// the page share it with. Never read for a signature, where `/T` is the field's
/// name rather than an author.
fn mark_author(dict: &Dict<'_>) -> Option<String> {
    if is_signature(dict) {
        return None;
    }
    let author = decode_text_string(dict.get::<PdfString>(b"T")?.as_bytes());
    let author = author.trim();
    (!author.is_empty()).then(|| one_line(author.to_string()))
}

/// A mark's text: its `/Contents`, or, when that is missing or blank, its `/RC`.
fn mark_text(dict: &Dict<'_>) -> Option<String> {
    let contents = dict
        .get::<PdfString>(b"Contents")
        .map(|contents| decode_text_string(contents.as_bytes()));
    if let Some(contents) = contents {
        let contents = contents.trim();
        if !contents.is_empty() {
            return Some(contents.to_string());
        }
    }
    let rich = dict
        .get::<PdfString>(b"RC")
        .map(|rich| decode_text_string(rich.as_bytes()))?;
    let text = strip_markup(&rich);
    let text = text.trim();
    (!text.is_empty()).then(|| text.to_string())
}

fn strip_markup(markup: &str) -> String {
    let mut text = String::with_capacity(markup.len());
    let mut in_tag = false;
    for character in markup.chars() {
        match character {
            '<' => in_tag = true,
            '>' => in_tag = false,
            _ if !in_tag => text.push(character),
            _ => {}
        }
    }
    decode_html_entities(&text)
}

/// The form fields of one document: the lines it lists and whether either bound truncated.
struct FieldLines {
    lines: Vec<String>,
    truncated: bool,
    options_truncated: bool,
}

/// The form-field lines of `acroform`, in `/Fields` order. `None` when no field a fill can
/// reach exists.
fn read_fields(acroform: &Dict<'_>, widget_pages: &HashMap<DictId, usize>) -> Option<FieldLines> {
    let fields = acroform.get::<Array<'_>>(b"Fields")?;
    let mut walk = FieldWalk {
        widget_pages,
        lines: Vec::new(),
        visited: HashSet::new(),
        truncated: false,
        options_truncated: false,
    };
    let mut fields = fields.flex_iter();
    while let Some(object) = fields.next::<Object<'_>>() {
        let Some(field) = object.into_dict() else {
            continue;
        };
        walk.visit(&field, "", 0);
        if walk.truncated {
            break;
        }
    }
    Some(FieldLines {
        lines: walk.lines,
        truncated: walk.truncated,
        options_truncated: walk.options_truncated,
    })
}

/// One pass over the field tree: the fields it reaches, and the bounds that keep it finite.
struct FieldWalk<'a> {
    widget_pages: &'a HashMap<DictId, usize>,
    lines: Vec<String>,
    /// The field objects already visited, so `/Kids` that point back terminate.
    visited: HashSet<DictId>,
    truncated: bool,
    options_truncated: bool,
}

impl FieldWalk<'_> {
    /// Visit `field` and, through it, the named kids below it. `prefix` is the qualified name its
    /// ancestors established.
    fn visit(&mut self, field: &Dict<'_>, prefix: &str, depth: usize) {
        if depth > MAX_FIELD_DEPTH {
            return;
        }
        if !self.visited.insert(dict_id(field)) {
            return;
        }
        let name = field_name(field, prefix);
        // A dict whose kids are fields of their own is a container, not a field: its kids are
        // visited under the prefix it established.
        if !is_non_terminal(field)
            && let Some(kind) = field_kind(field)
        {
            if self.lines.len() == MAX_FIELDS {
                self.truncated = true;
                return;
            }
            let page = field_page(field, self.widget_pages);
            let options = field_options(field, kind);
            if options.len() > MAX_FIELD_OPTIONS {
                self.options_truncated = true;
            }
            let value = field_value(field, kind, &options);
            let fillable = !name.is_empty() && field_is_fillable(field, kind, &options);
            self.lines.push(render_field(
                &name,
                kind,
                &options,
                page,
                value.as_deref(),
                fillable,
            ));
        }
        let Some(kids) = field.get::<Array<'_>>(b"Kids") else {
            return;
        };
        let mut kids = kids.flex_iter();
        while let Some(object) = kids.next::<Object<'_>>() {
            let Some(kid) = object.into_dict() else {
                continue;
            };
            // A kid that names itself with `/T` is a field of its own — the same test the filler
            // uses, so
            // the two agree on what a field is.
            if !kid.contains_key(b"T") {
                continue;
            }
            self.visit(&kid, &name, depth + 1);
            if self.truncated {
                return;
            }
        }
    }
}

/// Whether a field is a container rather than a field: a dict whose `/Kids` are fields of their
/// own.
fn is_non_terminal(field: &Dict<'_>) -> bool {
    let Some(kids) = field.get::<Array<'_>>(b"Kids") else {
        return false;
    };
    let mut kids = kids.flex_iter();
    while let Some(object) = kids.next::<Object<'_>>() {
        if object.into_dict().is_some_and(|kid| kid.contains_key(b"T")) {
            return true;
        }
    }
    false
}

/// A field's fully qualified name: its own `/T` under the `prefix` its ancestors established.
fn field_name(field: &Dict<'_>, prefix: &str) -> String {
    let own = field
        .get::<PdfString>(b"T")
        .map(|name| one_line(decode_text_string(name.as_bytes())))
        .filter(|own| !own.is_empty());
    match own {
        None => prefix.to_string(),
        Some(own) if prefix.is_empty() => own,
        Some(own) => format!("{prefix}.{own}"),
    }
}

/// The kind of a fillable form field, in the vocabulary a model reads.
#[derive(Clone, Copy)]
enum FieldKind {
    Text,
    Checkbox,
    Radio,
    Choice,
}

impl FieldKind {
    fn word(self) -> &'static str {
        let kinds = crate::docgen::pdf_field_kinds();
        match self {
            Self::Text => kinds.text.as_str(),
            Self::Checkbox => kinds.checkbox.as_str(),
            Self::Radio => kinds.radio.as_str(),
            Self::Choice => kinds.choice.as_str(),
        }
    }
}

/// A field's kind from its (inherited) `/FT` and `/Ff`; `None` for a field no fill can reach.
fn field_kind(field: &Dict<'_>) -> Option<FieldKind> {
    match inherited(field, b"FT")?.into_name()?.as_str() {
        "Tx" => Some(FieldKind::Text),
        "Ch" => Some(FieldKind::Choice),
        "Btn" => {
            let flags = field_flags(field);
            if flags & FIELD_FLAG_PUSH_BUTTON != 0 {
                None
            } else if flags & FIELD_FLAG_RADIO != 0 {
                Some(FieldKind::Radio)
            } else {
                Some(FieldKind::Checkbox)
            }
        }
        _ => None,
    }
}

fn field_flags(field: &Dict<'_>) -> i32 {
    inherited(field, b"Ff")
        .and_then(Object::into_i32)
        .unwrap_or(0)
}

/// The value a field carries, by its kind: a text field's string, a choice's selected options, a
/// button's state.
fn field_value(field: &Dict<'_>, kind: FieldKind, options: &[String]) -> Option<String> {
    match kind {
        FieldKind::Text => text_value(field),
        FieldKind::Choice => choice_value(field),
        FieldKind::Checkbox => Some(checkbox_value(field)),
        FieldKind::Radio => Some(radio_value(field, options)),
    }
}

/// The options a field offers, as the model should read them: a radio's fill values, a choice's
/// display names.
fn field_options(field: &Dict<'_>, kind: FieldKind) -> Vec<String> {
    match kind {
        FieldKind::Radio => radio_options(field),
        FieldKind::Choice => choice_options(field),
        FieldKind::Text | FieldKind::Checkbox => Vec::new(),
    }
}

/// Whether a filler can put a value into the field: a radio group or a list box without `/Opt`
/// cannot.
fn field_is_fillable(field: &Dict<'_>, kind: FieldKind, options: &[String]) -> bool {
    match kind {
        FieldKind::Text | FieldKind::Checkbox => true,
        FieldKind::Radio => !options.is_empty(),
        FieldKind::Choice => !options.is_empty() || field_flags(field) & FIELD_FLAG_COMBO != 0,
    }
}

/// A text field's value: its `/V` string, or nothing when it is absent or blank.
fn text_value(field: &Dict<'_>) -> Option<String> {
    let value = inherited(field, b"V")?.into_string()?;
    let text = decode_text_string(value.as_bytes());
    let text = text.trim();
    (!text.is_empty()).then(|| one_line(text.to_string()))
}

/// A checkbox's value: whether it is checked, and — when the field offers more than one on-state —
/// the states it offers.
fn checkbox_value(field: &Dict<'_>) -> String {
    let selected = selected_states(field);
    let checked = selected.iter().any(|state| state != "Off");
    let mut value = checked_word(checked);
    if !checked {
        return value;
    }
    let states = on_states(field);
    if states.len() > 1
        && let Some(state) = selected.iter().find(|state| *state != "Off")
        && !is_bare_number(state)
    {
        value = format!("{value} ({state})");
    }
    value
}

/// A radio group's value: whether it is checked, and the fill value of its selected state.
fn radio_value(field: &Dict<'_>, options: &[String]) -> String {
    let selected = selected_states(field);
    let checked = selected.iter().any(|state| state != "Off");
    let mut value = checked_word(checked);
    if !checked {
        return value;
    }
    let states = on_states(field);
    if (options.len() > 1 || states.len() > 1)
        && let Some(state) = selected.iter().find(|state| *state != "Off")
        && let Some(name) = radio_fill_value(state, options, &states)
    {
        value = format!("{value} ({name})");
    }
    value
}

fn checked_word(checked: bool) -> String {
    if checked { "checked" } else { "not checked" }.to_string()
}

/// The fill value a selected radio state names: the `/Opt` entry the state corresponds to, or
/// the state itself.
fn radio_fill_value(state: &str, options: &[String], states: &[String]) -> Option<String> {
    if let Some(option) = options.iter().find(|option| *option == state) {
        return Some(option.clone());
    }
    let position = states.iter().position(|known| known == state)?;
    options.get(position).cloned()
}

/// A choice field's value: each selected `/V` resolved through `/Opt`, joined for display.
fn choice_value(field: &Dict<'_>) -> Option<String> {
    let mut selected = selected_strings(field);
    selected.retain(|value| !value.trim().is_empty());
    if selected.is_empty() {
        return None;
    }
    let options = option_entries(field);
    let names = selected
        .iter()
        .map(|value| {
            options
                .iter()
                .find(|option| option.export == *value || option.display == *value)
                .map_or_else(|| value.clone(), |option| option.display.clone())
        })
        .collect::<Vec<_>>();
    Some(one_line(names.join(", ")))
}

/// A field's selected button states: its `/V` (a name, or the names of a multi-select).
fn selected_states(field: &Dict<'_>) -> Vec<String> {
    match inherited(field, b"V") {
        Some(Object::Name(name)) => vec![name.as_str().to_string()],
        Some(Object::Array(array)) => name_strings(&array),
        _ => first_widget_state(field).into_iter().collect(),
    }
}

/// A choice field's selected `/V` strings (one, or the several of a multi-select).
fn selected_strings(field: &Dict<'_>) -> Vec<String> {
    match inherited(field, b"V") {
        Some(Object::String(value)) => vec![decode_text_string(value.as_bytes())],
        Some(Object::Array(array)) => string_items(&array),
        _ => Vec::new(),
    }
}

/// The name states an array of names holds.
fn name_strings(array: &Array<'_>) -> Vec<String> {
    let mut names = Vec::new();
    let mut items = array.flex_iter();
    while let Some(object) = items.next::<Object<'_>>() {
        if let Object::Name(name) = object {
            names.push(name.as_str().to_string());
        }
    }
    names
}

/// The text of an array's string items, in order.
fn string_items(array: &Array<'_>) -> Vec<String> {
    let mut items = Vec::new();
    let mut strings = array.flex_iter();
    while let Some(object) = strings.next::<Object<'_>>() {
        if let Object::String(text) = object {
            items.push(decode_text_string(text.as_bytes()));
        }
    }
    items
}

/// A field's first widget's `/AS` — the state a button is in when its `/V` says nothing.
fn first_widget_state(field: &Dict<'_>) -> Option<String> {
    field_widget(field)?
        .get::<Name<'_>>(b"AS")
        .map(|state| state.as_str().to_string())
}

/// The widget that carries a field's own state and page: the field itself when it is one, else
/// its first `/Widget` kid.
fn field_widget<'a>(field: &Dict<'a>) -> Option<Dict<'a>> {
    if is_widget(field) {
        Some(field.clone())
    } else {
        widget_kids(field).into_iter().next()
    }
}

/// The distinct on-state names a button offers, `Off` excluded — what tells a checkbox from a
/// radio group.
fn on_states(field: &Dict<'_>) -> Vec<String> {
    let mut states = Vec::new();
    let widgets = widget_kids(field);
    if widgets.is_empty() {
        collect_on_states(field, &mut states);
    } else {
        for widget in &widgets {
            collect_on_states(widget, &mut states);
        }
    }
    states
}

fn collect_on_states(dict: &Dict<'_>, states: &mut Vec<String>) {
    let Some(appearance) = dict
        .get::<Dict<'_>>(b"AP")
        .and_then(|appearance| appearance.get::<Dict<'_>>(b"N"))
    else {
        return;
    };
    for name in appearance.keys() {
        let state = name.as_str();
        if state != "Off" && !states.iter().any(|known| known == state) {
            states.push(state.to_string());
        }
    }
}

/// One `/Opt` entry: the export value a `/V` names, and the display name the model reads.
struct OptionEntry {
    export: String,
    display: String,
}

/// A field's `/Opt` entries, in order. A single string is one entry, the shape a one-option list
/// box uses.
fn option_entries(field: &Dict<'_>) -> Vec<OptionEntry> {
    let mut entries = Vec::new();
    let mut options = match field.get::<Object<'_>>(b"Opt") {
        Some(Object::String(text)) => {
            let text = decode_text_string(text.as_bytes());
            entries.push(OptionEntry {
                export: text.clone(),
                display: text,
            });
            return entries;
        }
        Some(Object::Array(array)) => array.flex_iter(),
        _ => return entries,
    };
    while let Some(object) = options.next::<Object<'_>>() {
        match object {
            Object::String(text) => {
                let text = decode_text_string(text.as_bytes());
                entries.push(OptionEntry {
                    export: text.clone(),
                    display: text,
                });
            }
            Object::Array(pair) => {
                let parts = string_items(&pair);
                match parts.len() {
                    0 => {}
                    1 => entries.push(OptionEntry {
                        export: parts[0].clone(),
                        display: parts[0].clone(),
                    }),
                    _ => entries.push(OptionEntry {
                        export: parts[0].clone(),
                        display: parts[1].clone(),
                    }),
                }
            }
            _ => {}
        }
    }
    entries
}

/// A radio group's options: its own `/Opt` — one string, or the string items of an array.
fn radio_options(field: &Dict<'_>) -> Vec<String> {
    match field.get::<Object<'_>>(b"Opt") {
        Some(Object::String(text)) => vec![one_line(decode_text_string(text.as_bytes()))],
        Some(Object::Array(array)) => string_items(&array)
            .into_iter()
            .map(one_line)
            .collect::<Vec<_>>(),
        Some(_) => Vec::new(),
        None => on_states(field),
    }
}

/// A choice field's options: the display name of each `/Opt` entry.
fn choice_options(field: &Dict<'_>) -> Vec<String> {
    option_entries(field)
        .into_iter()
        .map(|option| one_line(option.display))
        .collect()
}

/// Whether a state name is only digits, and so a service code rather than a name.
fn is_bare_number(state: &str) -> bool {
    !state.is_empty() && state.bytes().all(|byte| byte.is_ascii_digit())
}

/// The page a field's own widget is on. `None` for a field with no widget.
fn field_page(field: &Dict<'_>, widget_pages: &HashMap<DictId, usize>) -> Option<usize> {
    widget_pages.get(&dict_id(&field_widget(field)?)).copied()
}

/// The `/Widget` kids of a field, in order.
fn widget_kids<'a>(field: &Dict<'a>) -> Vec<Dict<'a>> {
    let Some(kids) = field.get::<Array<'a>>(b"Kids") else {
        return Vec::new();
    };
    let mut widgets = Vec::new();
    let mut kids = kids.flex_iter();
    while let Some(object) = kids.next::<Object<'a>>() {
        if let Some(kid) = object.into_dict()
            && is_widget(&kid)
        {
            widgets.push(kid);
        }
    }
    widgets
}

fn is_widget(dict: &Dict<'_>) -> bool {
    matches!(dict.get::<Name<'_>>(b"Subtype").as_deref(), Some(b"Widget"))
}

/// `key` on `field`, or on the nearest ancestor that carries it — `/FT`, `/Ff` and the like are
/// inherited.
fn inherited<'a>(field: &Dict<'a>, key: &[u8]) -> Option<Object<'a>> {
    let mut current = field.clone();
    for _ in 0..MAX_FIELD_DEPTH {
        if let Some(value) = current.get::<Object<'a>>(key) {
            return Some(value);
        }
        current = current.get::<Dict<'a>>(b"Parent")?;
    }
    None
}

/// One field's line: `name (kind[; options: …][; not fillable])[ on page n]: value`.
fn render_field(
    name: &str,
    kind: FieldKind,
    options: &[String],
    page: Option<usize>,
    value: Option<&str>,
    fillable: bool,
) -> String {
    let words = crate::docgen::pdf_form_words();
    let mut label = kind.word().to_string();
    if !options.is_empty() {
        label.push_str("; options: ");
        let shown = &options[..options.len().min(MAX_FIELD_OPTIONS)];
        label.push_str(&shown.join(", "));
        if options.len() > MAX_FIELD_OPTIONS {
            label.push_str(", …");
        }
    }
    if !fillable {
        label.push_str("; ");
        label.push_str(&words.not_fillable);
    }
    let name = if name.is_empty() {
        words.unnamed.as_str()
    } else {
        name
    };
    let value = value.unwrap_or(words.no_value.as_str());
    match page {
        Some(page) => format!("{name} ({label}) on page {page}: {value}"),
        None => format!("{name} ({label}): {value}"),
    }
}

/// A PDF text string decoded to Unicode. A leading `FE FF` BOM marks UTF-16BE, `FF FE`
/// UTF-16LE; otherwise PDFDocEncoding applies.
fn decode_text_string(bytes: &[u8]) -> String {
    if let Some(rest) = bytes.strip_prefix(&[0xFE, 0xFF]) {
        let units = rest
            .as_chunks::<2>()
            .0
            .iter()
            .map(|pair| u16::from_be_bytes(*pair));
        return String::from_utf16_lossy(&units.collect::<Vec<_>>());
    }
    if let Some(rest) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
        return String::from_utf8_lossy(rest).into_owned();
    }
    bytes.iter().copied().map(pdf_doc_encoding).collect()
}

/// The accent characters PDFDocEncoding places at `0x18..=0x1F` (PDF 32000-1, Annex D).
const PDF_DOC_ENCODING_ACCENTS: [char; 8] = [
    '\u{02D8}', '\u{02C7}', '\u{02C6}', '\u{02D9}', '\u{02DD}', '\u{02DB}', '\u{02DA}', '\u{02DC}',
];

/// The special range PDFDocEncoding places at `0x80..=0xA0` (PDF 32000-1, Annex D).
const PDF_DOC_ENCODING_SPECIAL: [char; 33] = [
    '\u{2022}', '\u{2020}', '\u{2021}', '\u{2026}', '\u{2014}', '\u{2013}', '\u{0192}', '\u{2044}',
    '\u{2039}', '\u{203A}', '\u{2212}', '\u{2030}', '\u{201E}', '\u{201C}', '\u{201D}', '\u{2018}',
    '\u{2019}', '\u{201A}', '\u{2122}', '\u{FB01}', '\u{FB02}', '\u{0141}', '\u{0152}', '\u{0160}',
    '\u{0178}', '\u{017D}', '\u{0131}', '\u{0142}', '\u{0153}', '\u{0161}', '\u{017E}', '\u{FFFD}',
    '\u{20AC}',
];

/// One byte of PDFDocEncoding: the two special ranges, and ASCII/Latin-1 for the rest.
fn pdf_doc_encoding(byte: u8) -> char {
    match byte {
        0x18..=0x1F => PDF_DOC_ENCODING_ACCENTS[usize::from(byte - 0x18)],
        0x80..=0xA0 => PDF_DOC_ENCODING_SPECIAL[usize::from(byte - 0x80)],
        _ => char::from(byte),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::document::test_fixtures::{PdfFixture, pdf_text_string};

    /// A PDF whose catalog carries `/Pages` and the `catalog_extra` of `build`.
    fn pdf_with(build: impl FnOnce(&mut PdfFixture) -> (Vec<Vec<String>>, String)) -> Vec<u8> {
        pdf_with_trailer(|fixture| {
            let (pages, catalog_extra) = build(fixture);
            (pages, catalog_extra, String::new())
        })
    }

    /// [`pdf_with`] with `trailer_extra` written into the trailer — the hook a test uses.
    fn pdf_with_trailer(
        build: impl FnOnce(&mut PdfFixture) -> (Vec<Vec<String>>, String, String),
    ) -> Vec<u8> {
        let mut fixture = PdfFixture::new();
        let (pages, catalog_extra, trailer_extra) = build(&mut fixture);
        let page_refs: Vec<String> = pages.iter().map(|_| fixture.reserve()).collect();
        let pages_ref = fixture.push(format!(
            "<< /Type /Pages /Kids [{}] /Count {} >>",
            page_refs.join(" "),
            page_refs.len()
        ));
        for (page_ref, annotations) in page_refs.iter().zip(&pages) {
            let annots = if annotations.is_empty() {
                String::new()
            } else {
                format!(" /Annots [{}]", annotations.join(" "))
            };
            fixture.set(
                page_ref,
                format!("<< /Type /Page /Parent {pages_ref} /MediaBox [0 0 612 792]{annots} >>"),
            );
        }
        fixture.build_with_trailer(
            &format!("/Pages {pages_ref}{catalog_extra}"),
            &trailer_extra,
        )
    }

    fn read_pdf(bytes: Vec<u8>) -> Marks {
        let pdf = Pdf::new(bytes).expect("fixture PDF must parse");
        read(&pdf)
    }

    #[test]
    fn every_readable_mark_kind_is_reported_on_its_page() {
        let marks = read_pdf(pdf_with(|fixture| {
            let note = fixture.push("<< /Subtype /Text /Contents (please verify) >>".to_string());
            let highlight = fixture.push(format!(
                "<< /Subtype /Highlight /T {} /Contents {} >>",
                pdf_text_string("Иван Петров"),
                pdf_text_string("проверьте третью фигуру")
            ));
            let stamp = fixture.push("<< /Subtype /Stamp >>".to_string());
            let square = fixture.push("<< /Subtype /Square >>".to_string());
            let free_text =
                fixture.push("<< /Subtype /FreeText /RC (<body>Approved</body>) >>".to_string());
            (
                vec![
                    vec![note],
                    vec![highlight],
                    vec![stamp],
                    vec![square],
                    vec![free_text],
                ],
                String::new(),
            )
        }));
        assert_eq!(
            marks.annotations.as_deref(),
            Some(
                "Annotations:\nnote on page 1:\n  please verify\n\
                 highlight (Иван Петров) on page 2:\n  проверьте третью фигуру\n\
                 stamp on page 3\nsquare on page 4\n\
                 free text on page 5:\n  Approved"
            )
        );
        assert!(marks.fields.is_none());
        assert!(marks.notes.is_empty());
    }

    #[test]
    fn service_only_annotations_are_not_marks() {
        let marks = read_pdf(pdf_with(|fixture| {
            let link = fixture.push("<< /Subtype /Link /Rect [0 0 0 0] >>".to_string());
            let popup = fixture.push("<< /Subtype /Popup /Rect [0 0 0 0] >>".to_string());
            let widget = fixture.push("<< /Subtype /Widget /FT /Tx /T (field) >>".to_string());
            let hidden = fixture.push("<< /Subtype /Text /Contents (hidden) /F 2 >>".to_string());
            let no_view = fixture.push("<< /Subtype /Text /Contents (noview) /F 32 >>".to_string());
            let visible = fixture.push("<< /Subtype /Text /Contents (visible) >>".to_string());
            (
                vec![vec![link, popup, widget, hidden, no_view, visible]],
                String::new(),
            )
        }));
        assert_eq!(
            marks.annotations.as_deref(),
            Some("Annotations:\nnote on page 1:\n  visible")
        );
        assert!(
            marks.notes.is_empty(),
            "a widget without an /AcroForm is no unreadable form: {marks:?}"
        );
    }

    /// The annotations that are no mark but still hold content are named for the model, not
    /// dropped.
    #[test]
    fn marks_report_attachments_and_media_they_do_not_show() {
        let marks = read_pdf(pdf_with(|fixture| {
            let attachment = fixture.push(
                "<< /Subtype /FileAttachment /FS << /Type /Filespec /F (notes.txt) >> >>"
                    .to_string(),
            );
            let sound = fixture.push("<< /Subtype /Sound /Sound << >> >>".to_string());
            let empty_screen = fixture.push("<< /Subtype /Screen >>".to_string());
            let screen = fixture.push("<< /Subtype /Screen /A << /S /Rendition >> >>".to_string());
            let navigating =
                fixture.push("<< /Subtype /Screen /A << /S /GoTo /D [0 0 0 0] >> >>".to_string());
            let playing =
                fixture.push("<< /Subtype /Screen /AA << /PO << /S /Movie >> >> >>".to_string());
            let note = fixture.push("<< /Subtype /Text /Contents (please verify) >>".to_string());
            let hidden_movie = fixture.push("<< /Subtype /Movie /F 2 /Movie << >> >>".to_string());
            (
                vec![vec![
                    attachment.clone(),
                    attachment,
                    sound,
                    empty_screen,
                    screen,
                    navigating,
                    playing,
                    note,
                    hidden_movie,
                ]],
                String::new(),
            )
        }));
        assert_eq!(
            marks.unshown.lines(),
            [
                "1 attached file(s) not shown",
                "3 media annotation(s) not shown",
            ]
        );
        assert_eq!(
            marks.annotations.as_deref(),
            Some("Annotations:\nnote on page 1:\n  please verify")
        );
        assert!(marks.notes.is_empty());
    }

    #[test]
    fn filled_field_values_are_reported_by_kind_and_page() {
        let marks = read_pdf(pdf_with(|fixture| {
            let appearance =
                fixture.push("<< /Type /XObject /Subtype /Form /BBox [0 0 1 1] >>".to_string());
            let name = fixture.push(format!(
                "<< /Subtype /Widget /FT /Tx /T (Full name) /V {} >>",
                pdf_text_string("Иван Петров")
            ));
            let subscribe = fixture.push(format!(
                "<< /Subtype /Widget /FT /Btn /T (Subscribe) /V /Yes \
                 /AP << /N << /Yes {appearance} /Off {appearance} >> >> /AS /Yes >>"
            ));
            let unsubscribe = fixture.push(format!(
                "<< /Subtype /Widget /FT /Btn /T (Unsubscribe) /V /Off \
                 /AP << /N << /Yes {appearance} /Off {appearance} >> >> /AS /Off >>"
            ));
            let empty = fixture.push("<< /Subtype /Widget /FT /Tx /T (Empty) >>".to_string());
            let delivery = fixture.reserve();
            let first = fixture.push(format!(
                "<< /Subtype /Widget /Parent {delivery} \
                 /AP << /N << /exp {appearance} /Off {appearance} >> >> /AS /Off >>"
            ));
            let second = fixture.push(format!(
                "<< /Subtype /Widget /Parent {delivery} \
                 /AP << /N << /std {appearance} /Off {appearance} >> >> /AS /std >>"
            ));
            fixture.set(
                &delivery,
                format!(
                    "<< /FT /Btn /T (Delivery) /V /std /Ff 32768 \
                     /Opt [[(exp) (Express)] [(std) (Standard)]] /Kids [{first} {second}] >>"
                ),
            );
            let city = fixture.push(
                "<< /Subtype /Widget /FT /Ch /T (City) /V (spb) \
                 /Opt [[(msk) (Moscow)] [(spb) (Saint Petersburg)]] >>"
                    .to_string(),
            );
            let computed = fixture.push("<< /FT /Tx /T (Computed) /V (42) >>".to_string());
            // A value whose `/V` carries a newline, written as the ASCII bytes
            // `two\nlines` a hex string holds unambiguously.
            let note = fixture.push("<< /FT /Tx /T (Note) /V <74776f0a6c696e6573> >>".to_string());
            let acroform = fixture.push(format!(
                "<< /Fields [{name} {subscribe} {unsubscribe} {delivery} {city} {computed} {note} \
                 {empty}] >>"
            ));
            (
                vec![
                    vec![name, subscribe, unsubscribe, empty, first, second],
                    vec![city],
                ],
                format!(" /AcroForm {acroform}"),
            )
        }));
        assert_eq!(
            marks.fields.as_deref(),
            Some(
                "Form fields:\nFull name (text) on page 1: Иван Петров\n\
                 Subscribe (checkbox) on page 1: checked\n\
                 Unsubscribe (checkbox) on page 1: not checked\n\
                 Delivery (radio; not fillable) on page 1: checked\n\
                 City (choice; options: Moscow, Saint Petersburg) on page 2: Saint Petersburg\n\
                 Computed (text): 42\nNote (text): two\\nlines\n\
                 Empty (text) on page 1: (no value)"
            )
        );
        assert!(marks.notes.is_empty());
    }

    /// A checkbox that offers more than one on-state says which one it is in: a
    /// bare `checked` would read the same for either, and could mean the
    /// opposite of the state the file records.
    #[test]
    fn a_multi_state_checkbox_names_the_state_it_is_in() {
        let marks = read_pdf(pdf_with(|fixture| {
            let appearance =
                fixture.push("<< /Type /XObject /Subtype /Form /BBox [0 0 1 1] >>".to_string());
            let answer = fixture.push(format!(
                "<< /Subtype /Widget /FT /Btn /T (Answer) /V /No \
                 /AP << /N << /Yes {appearance} /No {appearance} /Off {appearance} >> >> >>"
            ));
            let acroform = fixture.push(format!("<< /Fields [{answer}] >>"));
            (vec![vec![answer]], format!(" /AcroForm {acroform}"))
        }));
        assert_eq!(
            marks.fields.as_deref(),
            Some("Form fields:\nAnswer (checkbox) on page 1: checked (No)")
        );
    }

    #[test]
    fn a_choice_with_more_options_than_the_cap_lists_the_first_ones() {
        let options = (0..=MAX_FIELD_OPTIONS)
            .map(|index| format!("[(o{index}) (Option {index})]"))
            .collect::<Vec<_>>()
            .join(" ");
        let marks = read_pdf(pdf_with(|fixture| {
            let field = fixture.push(format!(
                "<< /Subtype /Widget /FT /Ch /T (Long) /V () /Opt [{options}] >>"
            ));
            let acroform = fixture.push(format!("<< /Fields [{field}] >>"));
            (vec![vec![field]], format!(" /AcroForm {acroform}"))
        }));
        let listed = (0..MAX_FIELD_OPTIONS)
            .map(|index| format!("Option {index}"))
            .collect::<Vec<_>>()
            .join(", ");
        let expected =
            format!("Form fields:\nLong (choice; options: {listed}, …) on page 1: (no value)");
        assert_eq!(marks.fields.as_deref(), Some(expected.as_str()));
        assert_eq!(
            marks.notes,
            vec![format!(
                "only the first {MAX_FIELD_OPTIONS} options of a form field were listed"
            )]
        );
    }

    /// Every field a form declares is listed with its kind: a field with no
    /// value prints `(no value)`, a checkbox prints the state it is in, a radio
    /// group prints the options its appearance states offer, a choice prints its
    /// options, and a field with no `/T` is shown as unnamed and marked not
    /// fillable rather than left out or read as a bare value.
    #[test]
    fn a_form_lists_every_field_it_holds() {
        let without_values: fn(&mut PdfFixture) -> (Vec<Vec<String>>, String) = |fixture| {
            let first = fixture.push("<< /Subtype /Widget /FT /Tx /T (One) >>".to_string());
            let second = fixture.push("<< /Subtype /Widget /FT /Tx /T (Two) >>".to_string());
            let acroform = fixture.push(format!("<< /Fields [{first} {second}] >>"));
            (vec![vec![first, second]], format!(" /AcroForm {acroform}"))
        };
        let blank: fn(&mut PdfFixture) -> (Vec<Vec<String>>, String) = |fixture| {
            let appearance =
                fixture.push("<< /Type /XObject /Subtype /Form /BBox [0 0 1 1] >>".to_string());
            let name = fixture.push("<< /Subtype /Widget /FT /Tx /T (Name) >>".to_string());
            let agree =
                fixture.push("<< /Subtype /Widget /FT /Btn /T (Agree) /V /Off >>".to_string());
            let plan = fixture.reserve();
            let basic = fixture.push(format!(
                "<< /Subtype /Widget /Parent {plan} \
                 /AP << /N << /basic {appearance} /Off {appearance} >> >> /AS /Off >>"
            ));
            let pro = fixture.push(format!(
                "<< /Subtype /Widget /Parent {plan} \
                 /AP << /N << /pro {appearance} /Off {appearance} >> >> /AS /Off >>"
            ));
            fixture.set(
                &plan,
                format!("<< /FT /Btn /Ff 32768 /T (Plan) /V /Off /Kids [{basic} {pro}] >>"),
            );
            let city = fixture.push(
                "<< /Subtype /Widget /FT /Ch /T (City) \
                 /Opt [[(msk) (Moscow)] [(spb) (Saint Petersburg)]] >>"
                    .to_string(),
            );
            let acroform = fixture.push(format!("<< /Fields [{name} {agree} {plan} {city}] >>"));
            (
                vec![vec![name, agree, basic, pro, city]],
                format!(" /AcroForm {acroform}"),
            )
        };
        let unnamed: fn(&mut PdfFixture) -> (Vec<Vec<String>>, String) = |fixture| {
            let field = fixture.push("<< /Subtype /Widget /FT /Tx /V (secret) >>".to_string());
            let acroform = fixture.push(format!("<< /Fields [{field}] >>"));
            (vec![vec![field]], format!(" /AcroForm {acroform}"))
        };
        for (label, build, expected) in [
            (
                "a form whose fields carry no value",
                without_values,
                "Form fields:\nOne (text) on page 1: (no value)\n\
                 Two (text) on page 1: (no value)",
            ),
            (
                "a blank form",
                blank,
                "Form fields:\nName (text) on page 1: (no value)\n\
                 Agree (checkbox) on page 1: not checked\n\
                 Plan (radio; options: basic, pro) on page 1: not checked\n\
                 City (choice; options: Moscow, Saint Petersburg) on page 1: (no value)",
            ),
            (
                "a field with no /T",
                unnamed,
                "Form fields:\nunnamed field (text; not fillable) on page 1: secret",
            ),
        ] {
            let marks = read_pdf(pdf_with(build));
            assert!(
                marks.annotations.is_none(),
                "{label}: a widget is no mark: {marks:?}"
            );
            assert_eq!(
                marks.fields.as_deref(),
                Some(expected),
                "{label}: the fields it lists"
            );
            assert!(
                marks.notes.is_empty(),
                "{label}: no loss to report: {marks:?}"
            );
        }
    }

    /// A signature keeps its annotation mark and is never listed as a field
    /// value, whether it is one widget, a field whose widget is its kid, or one
    /// beside a pushbutton — and a pushbutton, which fills nothing, is not
    /// listed at all. A form of only those says so instead of looking empty.
    #[test]
    fn a_signature_is_a_mark_and_a_pushbutton_is_no_field() {
        let widget: fn(&mut PdfFixture) -> (Vec<Vec<String>>, String) = |fixture| {
            let signature = fixture
                .push("<< /Subtype /Widget /FT /Sig /T (Approval) /Rect [0 0 0 0] >>".to_string());
            let acroform = fixture.push(format!("<< /Fields [{signature}] >>"));
            (vec![vec![signature]], format!(" /AcroForm {acroform}"))
        };
        let beside_a_pushbutton: fn(&mut PdfFixture) -> (Vec<Vec<String>>, String) = |fixture| {
            let button = fixture.push(
                "<< /Subtype /Widget /FT /Btn /Ff 65536 /T (Submit) /Rect [0 0 0 0] >>".to_string(),
            );
            let signature = fixture
                .push("<< /Subtype /Widget /FT /Sig /T (Approval) /Rect [0 0 0 0] >>".to_string());
            let acroform = fixture.push(format!("<< /Fields [{button} {signature}] >>"));
            (
                vec![vec![button, signature]],
                format!(" /AcroForm {acroform}"),
            )
        };
        let split_from_its_widget: fn(&mut PdfFixture) -> (Vec<Vec<String>>, String) = |fixture| {
            let field = fixture.reserve();
            let widget = fixture.push(format!(
                "<< /Subtype /Widget /Parent {field} /Rect [0 0 0 0] >>"
            ));
            fixture.set(
                &field,
                format!("<< /FT /Sig /T (Approval) /Kids [{widget}] >>"),
            );
            let acroform = fixture.push(format!("<< /Fields [{field}] >>"));
            (vec![vec![widget]], format!(" /AcroForm {acroform}"))
        };
        for (label, build, expected) in [
            (
                "a signature widget",
                widget,
                "Annotations:\nsignature on page 1",
            ),
            (
                "a pushbutton beside a signature",
                beside_a_pushbutton,
                "Annotations:\nsignature on page 1",
            ),
            (
                "a signature field split from its widget",
                split_from_its_widget,
                "Annotations:\nsignature on page 1",
            ),
        ] {
            let marks = read_pdf(pdf_with(build));
            assert_eq!(
                marks.annotations.as_deref(),
                Some(expected),
                "{label}: the signature stays a mark"
            );
            assert!(
                marks.fields.is_none(),
                "{label}: no signature is a field value: {marks:?}"
            );
            assert_eq!(
                marks.notes,
                vec![NO_FILLABLE_FIELDS_NOTE.to_string()],
                "{label}: the form is said to hold nothing fillable"
            );
        }
    }

    /// A walk of the field tree and of the arrays it reads stops rather than
    /// looping or giving up: a field tree that points at an ancestor terminates
    /// (the container is not listed, the kid its own ancestor reference cannot
    /// resolve is read as the terminal field it looks like), and an array entry
    /// that is no name or no dictionary is skipped without ending the walk.
    #[test]
    fn the_field_tree_walk_terminates_and_skips_unknown_entries() {
        let ancestor: fn(&mut PdfFixture) -> (Vec<Vec<String>>, String) = |fixture| {
            let parent = fixture.reserve();
            let child = fixture.reserve();
            fixture.set(
                &parent,
                format!("<< /FT /Tx /T (A) /V (alpha) /Kids [{child}] >>"),
            );
            fixture.set(
                &child,
                format!("<< /FT /Tx /T (B) /V (beta) /Kids [{parent}] /Parent {parent} >>"),
            );
            let acroform = fixture.push(format!("<< /Fields [{parent}] >>"));
            (vec![vec![]], format!(" /AcroForm {acroform}"))
        };
        let unknown_entries: fn(&mut PdfFixture) -> (Vec<Vec<String>>, String) = |fixture| {
            let named_contents =
                fixture.push("<< /Subtype /Stamp /Contents /NotAString >>".to_string());
            let note = fixture.push("<< /Subtype /Text /Contents (kept) >>".to_string());
            let field = fixture.push("<< /FT /Tx /T (Name) /V (value) >>".to_string());
            let acroform = fixture.push(format!("<< /Fields [42 {field}] >>"));
            (
                vec![vec![
                    named_contents,
                    "7".to_string(),
                    "/Foo".to_string(),
                    note,
                ]],
                format!(" /AcroForm {acroform}"),
            )
        };
        for (label, build, expected) in [
            (
                "a field tree that points at an ancestor",
                ancestor,
                (None, Some("Form fields:\nA.B (text): beta")),
            ),
            (
                "unknown entries in the annotation and field arrays",
                unknown_entries,
                (
                    Some("Annotations:\nstamp on page 1\nnote on page 1:\n  kept"),
                    Some("Form fields:\nName (text): value"),
                ),
            ),
        ] {
            let (expected_annotations, expected_fields) = expected;
            let marks = read_pdf(pdf_with(build));
            assert_eq!(
                marks.annotations.as_deref(),
                expected_annotations,
                "{label}: the marks the walk kept"
            );
            assert_eq!(
                marks.fields.as_deref(),
                expected_fields,
                "{label}: the fields the walk kept"
            );
        }
    }

    /// Dictionaries written straight into an array carry no object id of their
    /// own: each is still its own mark and its own field, and a field with no
    /// `/T` is named as one rather than left as a bare value.
    #[test]
    fn direct_dictionaries_are_read_as_their_own_marks_and_fields() {
        let marks = read_pdf(pdf_with(|_fixture| {
            (
                vec![vec![
                    "<< /Subtype /Text /Contents (first) >>".to_string(),
                    "<< /Subtype /Text /Contents (second) >>".to_string(),
                ]],
                " /AcroForm << /Fields [<< /FT /Tx /T (One) /V (1) >> \
                 << /FT /Tx /T (Two) /V (2) >> << /FT /Tx /V (unnamed) >>] >>"
                    .to_string(),
            )
        }));
        assert_eq!(
            marks.annotations.as_deref(),
            Some("Annotations:\nnote on page 1:\n  first\nnote on page 1:\n  second")
        );
        assert_eq!(
            marks.fields.as_deref(),
            Some(
                "Form fields:\nOne (text): 1\nTwo (text): 2\n\
                 unnamed field (text; not fillable): unnamed"
            )
        );
    }

    /// A container whose widget kids each carry their own `/FT`/`/T`/`/V` is read
    /// as the fields it holds, named the way the filler names them — and a checked
    /// button whose `/Opt` does not name the state it is in shows only its state,
    /// never a name guessed from the state's position.
    #[test]
    fn self_contained_widget_kids_are_read_as_their_own_fields() {
        let marks = read_pdf(pdf_with(|fixture| {
            let appearance =
                fixture.push("<< /Type /XObject /Subtype /Form /BBox [0 0 1 1] >>".to_string());
            let group = fixture.reserve();
            let first = fixture.push(format!(
                "<< /Subtype /Widget /Parent {group} /FT /Tx /T (First) /V (one) \
                 /Rect [0 0 0 0] >>"
            ));
            let plan = fixture.push(format!(
                "<< /Subtype /Widget /FT /Btn /T (Plan) /V /1 /Opt [[(one) (One)] [(two) (Two)]] \
                 /AP << /N << /1 {appearance} /2 {appearance} /Off {appearance} >> >> /AS /1 >>"
            ));
            fixture.set(&group, format!("<< /T (Group) /Kids [{first}] >>"));
            let acroform = fixture.push(format!("<< /Fields [{group} {plan}] >>"));
            (vec![vec![first, plan]], format!(" /AcroForm {acroform}"))
        }));
        assert_eq!(
            marks.fields.as_deref(),
            Some(
                "Form fields:\nGroup.First (text) on page 1: one\n\
                 Plan (checkbox) on page 1: checked"
            )
        );
    }

    /// The document's own description leads its reading: only the entries the
    /// Info dictionary carries, in a fixed order, with dates in calendar form
    /// and the file's own offset.
    #[test]
    fn a_documents_description_shows_only_what_it_carries() {
        let marks = read_pdf(pdf_with_trailer(|fixture| {
            let info = fixture.push(format!(
                "<< /Title {} /Author {} /Subject {} /Keywords {} /Creator {} /Producer {} \
                 /CreationDate (D:20240102030405+03'30') /ModDate (D:20230607080910Z) >>",
                pdf_text_string("Annual report"),
                pdf_text_string("Иван Петров"),
                pdf_text_string("Figures and notes"),
                pdf_text_string("report, figures"),
                pdf_text_string("Writer"),
                pdf_text_string("MahBot"),
            ));
            (vec![vec![]], String::new(), format!(" /Info {info}"))
        }));
        let description = marks
            .description
            .as_deref()
            .expect("the file carries a description");
        assert_eq!(
            description,
            "Description:\n  title: Annual report\n  author: Иван Петров\n  \
             subject: Figures and notes\n  keywords: report, figures\n  \
             creator: Writer\n  producer: MahBot\n  \
             created: 2024-01-02T03:04:05+03:30\n  modified: 2023-06-07T08:09:10Z"
        );
        // Every field the shared rules state is one this reading knows how to
        // print, so a field added to the rules without a value here is caught.
        for field in crate::docgen::pdf_metadata_fields() {
            assert!(
                description.contains(&format!("{}: ", field.key)),
                "the description must print every rules field, missing {:?}: {description}",
                field.key
            );
        }
    }
}