logoxide 0.1.1

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

```toml
[package]
id = "bsb"
name = "Berean Standard Bible"
abbreviation = "BSB"
version = "1.0.0"
language = "en"
license = "LicenseRef-PublicDomain"
keywords = ["modern english", "literal"]
repository = "https://github.com/someone/bsb"

[formats]
usx = { path = "usx/" }
sword = { path = "sword/", feature = "sword" }

[features]
default = ["usx"]
usx = []
sword = []
strongs = ["dep:strongs-greek"]

[dependencies]
strongs-greek = { git = "https://example.org/strongs-greek", version = "2", optional = true }

[settings]
default = "bsb"
```
*/

use std::collections::{BTreeMap, BTreeSet};

use serde::{Deserialize, Serialize};

use crate::error::{LogoxideError, Result};

/// The manifest's file name, in a package and in a vault
pub const MANIFEST: &str = "logoxide.toml";

#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct Manifest {
    /// What this package is; a vault's manifest has none
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub package: Option<Package>,
    /// Each format of the text, by name (`usx`, `usfm`, `sword`, ...)
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub formats: BTreeMap<String, FormatEntry>,
    /// Each feature and what it turns on: other features, `dep:name` (an optional dependency), or
    /// `name/feature` (a dependency's feature)
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub features: BTreeMap<String, Vec<String>>,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub dependencies: BTreeMap<String, Dependency>,
    /// A vault's (or a machine's) choices: the default Bible, the ones to compare
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub settings: Option<Settings>,
    /// Audio and video, listed by URL and hash, never stored in the package
    /// ([`crate::media`])
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub media: Option<crate::media::Media>,
    /// Files' titles, by path, in place of what the files say ([`crate::titles`])
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub titles: BTreeMap<String, String>,
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Package {
    /// What dependencies call it: lowercase letters, digits, `-`, and `_`
    pub id: String,
    pub name: String,
    /// What references name it by (`John 3:16 BSB`): required for a Bible or a commentary
    /// ([`PackageKind::needs_abbreviation`]), optional for the kinds references never name
    /// ([`Package::short_name`] falls back on the id)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub abbreviation: Option<String>,
    /// Who wrote it (a book's authors, a translation's translators), in order
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub authors: Vec<String>,
    /// A sentence or two about it (a book's subtitle)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub aliases: Vec<String>,
    pub version: semver::Version,
    #[serde(default)]
    pub kind: PackageKind,
    /// BCP 47: `en`, `grc`, `sr-Latn` ([`crate::language`]). Required unless the kind has no
    /// language of its own ([`PackageKind::needs_language`]: a collection, a versification map),
    /// where it may be left out and reads as `und` ([`Manifest::parse`] fills it in)
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub language: String,
    /// The language's name (`English`), when the tag doesn't say enough: an import keeps the
    /// publisher's own here when it isn't a tag (`und`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub language_name: Option<String>,
    /// Its script, ISO 15924 (`Latn`, `Hebr`): when not said, the language tag's (see
    /// [`Package::text_script`])
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub script: Option<String>,
    /// Which way its text runs: when not said, the script's (see [`Package::text_direction`])
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub direction: Option<Direction>,
    /// An SPDX expression (`CC0-1.0`, `LicenseRef-PublicDomain`); shown, never enforced
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub license: Option<String>,
    /// What the license allows, where it's said rather than derived from `license`
    /// (`[package.rights]`; see [`Package::text_rights`] and [`crate::license`])
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rights: Option<crate::license::Rights>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub license_file: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub publisher: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub homepage: Option<String>,
    /// Where its files are kept (its git repository's page)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub repository: Option<String>,
    /// Where it's documented, if not in its README
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub documentation: Option<String>,
    /// Its README's path in the package (part of the package, like `license-file`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub readme: Option<String>,
    /// Words a search should find it by, besides its names (`justification`, `puritan`)
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub keywords: Vec<String>,
    /// What it's about: up to [`MAX_CATEGORIES`] of [`CATEGORIES`] (`systematic-theology`,
    /// `church-history`); `keywords` say anything narrower
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub categories: Vec<String>,
    /// The books of the Bible it's mainly about, as their USFM codes (`["ROM", "GAL"]` for a
    /// commentary on Romans and Galatians). Said by its author, never worked out from its text;
    /// not the books a Bible has
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub about_books: Vec<String>,
    /// The work it's an edition of (`kjv`), by the id logoxide's table of works gives it
    /// ([`crate::works`]), or another of the same form: packages of one work are editions of
    /// one text, which searches group
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub work: Option<String>,
    /// Which edition of its work it is (`1769-oxford`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub edition: Option<String>,
    /// The year of that edition (`1769`; before the common era, negative)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub edition_year: Option<i32>,
    /// Where the text was imported from, if anywhere: the download, the import's name, and the
    /// publisher's version (written by `logoxide-import`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub upstream: Option<Upstream>,
    /// `own` (the text's verse markers say), or a named system: `KJV`, `NRSV`, `MT`, ...
    #[serde(default = "own", skip_serializing_if = "is_own")]
    pub versification: String,
    /// For a versification map: the versification it maps `versification` to
    /// (logoxide-text's `versification`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub maps_to: Option<String>,
    /// For a dictionary (the `dictionary` format): what its entries are keyed by, Strong's Greek
    /// or Hebrew numbers or headwords, which says how a key is matched (see [`Keys`])
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub keys: Option<Keys>,
    /// More files the package is made of, as patterns (`README.md`, `images/**`): besides
    /// these, only what the manifest names is (see [`crate::package::declared_files`])
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub include: Vec<String>,
}

/**
`[package.upstream]`: where an imported package's text came from, so an update finds its
publisher's entry again and knows whether the publisher has a newer one. The package's own
`version` is logoxide's (1.0.0 for a new import, raised by what each update changes); the
publisher's, which says nothing about what changed, is kept here as given
*/
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Upstream {
    /// The download it was made from (eBible.org's
    /// `https://ebible.org/Scriptures/eng-asv_usfm.zip`); every import writes one, but a package
    /// made by hand from a source with no URL (a Digital Bible Library bundle) may say so in
    /// `note` instead
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
    /// What `lx import` takes for it (`ebible:eng-asv`, `sword:crosswire/KJV`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub import: Option<String>,
    /// The publisher's version of what was downloaded, as the publisher gives it (eBible.org's
    /// update date `2026-10-08`, a SWORD module's `3.1`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<String>,
    /// The import rewrote the publisher's markup (a SWORD module's entries made into OSIS
    /// files), its words unchanged. logoxide doesn't count that as a derivative (the owner's D7),
    /// but `lx publish` says so when the license allows none
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub converted: bool,
    /// Where it came from, in words, for a source `url` and `import` can't name (`Digital Bible
    /// Library text release bundle 317e03834065a236, revision 1`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub note: Option<String>,
}

impl Package {
    /// Its script: `script`, else the language tag's script subtag (`sr-Latn`); none if neither
    /// says
    pub fn text_script(&self) -> Option<String> {
        (self.script.clone()).or_else(|| crate::language::script_of_tag(&self.language))
    }

    /// Which way its text runs: `direction`, else its script's ([`crate::language::RTL_SCRIPTS`]
    /// run right to left), else left to right
    pub fn text_direction(&self) -> Direction {
        (self.direction)
            .unwrap_or_else(|| crate::language::script_direction(self.text_script().as_deref()))
    }
}

fn own() -> String {
    String::from("own")
}

fn is_own(versification: &str) -> bool {
    versification == "own"
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum PackageKind {
    #[default]
    Bible,
    Commentary,
    Lexicon,
    CrossReferences,
    VersificationMap,
    Book,
    /// Other packages, as its dependencies (a library: a feature can turn on each one), and no
    /// text of its own
    Collection,
}

impl PackageKind {
    /// Its name as manifests give it (`cross-references`)
    pub fn name(self) -> &'static str {
        match self {
            PackageKind::Bible => "bible",
            PackageKind::Commentary => "commentary",
            PackageKind::Lexicon => "lexicon",
            PackageKind::CrossReferences => "cross-references",
            PackageKind::VersificationMap => "versification-map",
            PackageKind::Book => "book",
            PackageKind::Collection => "collection",
        }
    }

    /// Whether references name packages of this kind (`John 3:16 BSB`, a commentary's note
    /// labeled `MHCC`), so `abbreviation` is required
    pub fn needs_abbreviation(self) -> bool {
        matches!(self, PackageKind::Bible | PackageKind::Commentary)
    }

    /// Whether a package of this kind has a language of its own: a collection of packages and a
    /// versification map don't, so `language` may be left out of theirs (read as `und`)
    pub fn needs_language(self) -> bool {
        !matches!(
            self,
            PackageKind::Collection | PackageKind::VersificationMap
        )
    }
}

impl Package {
    /// What to call it in short: its abbreviation, else its id (a book or a collection, which
    /// references never name, may have none)
    pub fn short_name(&self) -> &str {
        self.abbreviation.as_deref().unwrap_or(&self.id)
    }
}

/**
What a dictionary's entries are keyed by (`[package] keys`), which says how a key is matched
(`doc/entries.md`): Strong's numbers are normalized (`G0025`, `g25`, and `G25` are one key,
written `G25`: an uppercase letter, the number without leading zeros, any suffix as given);
headwords are matched ignoring case and accents, as catalog search matches names
*/
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Keys {
    /// Strong's Greek numbers (`G25`)
    StrongsGreek,
    /// Strong's Hebrew numbers (`H430`)
    StrongsHebrew,
    /// Words, as a dictionary's headwords (`Aaron`, `ἀγαπάω`)
    Headword,
}

impl Keys {
    /// Its name as manifests give it (`strongs-greek`)
    pub fn name(self) -> &'static str {
        match self {
            Keys::StrongsGreek => "strongs-greek",
            Keys::StrongsHebrew => "strongs-hebrew",
            Keys::Headword => "headword",
        }
    }

    pub fn from_name(name: &str) -> Option<Keys> {
        Some(match name.trim().to_ascii_lowercase().as_str() {
            "strongs-greek" => Keys::StrongsGreek,
            "strongs-hebrew" => Keys::StrongsHebrew,
            "headword" => Keys::Headword,
            _ => return None,
        })
    }
}

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Direction {
    #[default]
    Ltr,
    Rtl,
}

/// Where a format's files are, and the feature that turns it on (always on without one)
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FormatEntry {
    pub path: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub feature: Option<String>,
}

/// The formats logoxide knows the names of
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum Format {
    Usx,
    Usfm,
    Usj,
    Osis,
    Sword,
    Thml,
    /// GBF (the General Bible Format, SWORD's older modules): a book a file, or a whole Bible,
    /// its books, chapters, and verses marked by `<SB…>`, `<SC…>`, and `<SV…>` sync marks
    Gbf,
    Zefania,
    /// A book as an EPUB: kept and summarized as files, not read as verses (topos finds the
    /// references in it)
    Epub,
    /// A versification map's lines, as Paratext's `.vrs` files write them
    /// (logoxide-text's `versification`)
    Vrs,
    /// A dictionary's entries (`entries/*.xml`: `<entry key="G25">…</entry>` elements in the
    /// markup each file declares; `doc/entries.md`), keyed as `[package] keys` says
    Dictionary,
    /// Cross-references (`xref/*.tsv`: `from`, `to`, and an optional weight a line, as OSIS
    /// references; `doc/entries.md`)
    Xref,
}

impl Format {
    pub fn from_name(name: &str) -> Option<Format> {
        Some(match name.to_ascii_lowercase().as_str() {
            "usx" => Format::Usx,
            "usfm" => Format::Usfm,
            "usj" => Format::Usj,
            "osis" => Format::Osis,
            "sword" => Format::Sword,
            "thml" => Format::Thml,
            "gbf" => Format::Gbf,
            "zefania" => Format::Zefania,
            "epub" => Format::Epub,
            "vrs" => Format::Vrs,
            "dictionary" => Format::Dictionary,
            "xref" => Format::Xref,
            _ => return None,
        })
    }

    /// Its name as manifests give it (`usx`)
    pub fn name(self) -> &'static str {
        match self {
            Format::Usx => "usx",
            Format::Usfm => "usfm",
            Format::Usj => "usj",
            Format::Osis => "osis",
            Format::Sword => "sword",
            Format::Thml => "thml",
            Format::Gbf => "gbf",
            Format::Zefania => "zefania",
            Format::Epub => "epub",
            Format::Vrs => "vrs",
            Format::Dictionary => "dictionary",
            Format::Xref => "xref",
        }
    }

    /// The extensions of its files (`None`: every file under its path, for formats logoxide keeps
    /// without reading, like a SWORD module's folder)
    pub fn extensions(self) -> Option<&'static [&'static str]> {
        Some(match self {
            Format::Usx => &["usx"],
            Format::Usfm => &["usfm", "sfm"],
            Format::Usj => &["json", "usj"],
            Format::Osis => &["xml", "osis"],
            Format::Thml => &["xml", "thml"],
            Format::Gbf => &["gbf", "txt"],
            Format::Zefania => &["xml"],
            Format::Epub => &["epub"],
            Format::Vrs => &["vrs"],
            Format::Dictionary => &["xml"],
            Format::Xref => &["tsv"],
            Format::Sword => return None,
        })
    }

    /// Whether logoxide reads it yet (as verses, or as a dictionary's entries or a verse's
    /// cross-references)
    pub fn readable(self) -> bool {
        matches!(
            self,
            Format::Usx
                | Format::Usfm
                | Format::Usj
                | Format::Osis
                | Format::Thml
                | Format::Gbf
                | Format::Dictionary
                | Format::Xref
        )
    }

    /// Whether it's read as verses: a Bible's text, which a summary counts and hashes
    pub fn is_verse_text(self) -> bool {
        matches!(
            self,
            Format::Usx | Format::Usfm | Format::Usj | Format::Osis | Format::Thml | Format::Gbf
        )
    }
}

/// A dependency: a version requirement alone, or where it comes from
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
// A manifest has a few dependencies, so their size doesn't matter
#[allow(clippy::large_enum_variant)]
pub enum Dependency {
    /// `bsb = "1"`: from a registry (none exist yet)
    Version(semver::VersionReq),
    Detailed(DetailedDependency),
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct DetailedDependency {
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub git: Option<String>,
    /// A registry's catalog (its URL, or a file's path) whose releases are archives: the newest
    /// release matching `version` is downloaded ([`crate::publish`])
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub registry: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub path: Option<String>,
    /**
    An import from another publisher (`ebible:eng-kjv2006`, `sword:crosswire/KJV`), made by the
    host's importer and kept in the library like a fetched package, by its files' checksum.
    `version` is then a requirement on the import's own version
    */
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub import: Option<String>,
    /// The newest tag matching this requirement (`v1.2.0` matches `1`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub version: Option<semver::VersionReq>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub tag: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub rev: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub branch: Option<String>,
    /// The package's folder in its repository (`romans`), for a repository of many packages:
    /// its releases are tagged `romans/v1.0.0` (as `lx release` tags them), and only that
    /// folder's files are the package
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub folder: Option<String>,
    /// Only used when a feature turns it on (`dep:name`)
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub optional: bool,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub features: Vec<String>,
    #[serde(default = "yes", skip_serializing_if = "Clone::clone")]
    pub default_features: bool,
    /// The package's id, when the dependency is named something else (`kjv-bob = { package =
    /// "kjv", … }`), so two forks of a package can be used side by side
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub package: Option<String>,
    /// What references name it by here, in place of the package's own abbreviation (`KJVB`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub abbreviation: Option<String>,
    /// Its aliases here, in place of the package's own
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub aliases: Option<Vec<String>>,
    /// `false` turns it off without removing it: it stays locked and installed (so `lx clean`
    /// keeps it, and turning it on again needs no download), but nothing reads it
    #[serde(default = "yes", skip_serializing_if = "Clone::clone")]
    pub enabled: bool,
}

/// As a manifest without the fields reads: default features and the dependency on
impl Default for DetailedDependency {
    fn default() -> Self {
        Self {
            git: None,
            registry: None,
            path: None,
            import: None,
            version: None,
            tag: None,
            rev: None,
            branch: None,
            folder: None,
            optional: false,
            features: vec![],
            default_features: true,
            package: None,
            abbreviation: None,
            aliases: None,
            enabled: true,
        }
    }
}

impl Dependency {
    /// Whether it's on (`enabled = false` turns it off without removing it)
    pub fn enabled(&self) -> bool {
        match self {
            Dependency::Version(_) => true,
            Dependency::Detailed(d) => d.enabled,
        }
    }
}

impl DetailedDependency {
    /// The id of the package it names: `package`, else the dependency's own name
    pub fn package_id<'a>(&'a self, name: &'a str) -> &'a str {
        self.package.as_deref().unwrap_or(name)
    }
}

fn yes() -> bool {
    true
}

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct Settings {
    /// The Bible references use when they name none
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub default: Option<String>,
    /// Bibles shown after the named one
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub compare: Vec<String>,
    /// Catalogs (or registries) to search for packages, besides eBible.org's and fetch.bible's
    /// lists: URLs or paths (see [`crate::catalog`]). Their entries come first
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub catalogs: Vec<String>,
    /// Whether eBible.org's and fetch.bible's lists are searched too
    #[serde(default = "yes", skip_serializing_if = "Clone::clone")]
    pub default_catalogs: bool,
    /// Registries by name: `dorean-local = "~/logoxide-packages"` lets `dorean-local:kjv` (or
    /// `dorean-local:books/kjv`, its folder there) name a package. Each is a folder of package
    /// repositories, or a catalog (see [`crate::catalog`]); they're searched first
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub registries: BTreeMap<String, String>,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            default: None,
            compare: Vec::new(),
            catalogs: Vec::new(),
            default_catalogs: true,
            registries: BTreeMap::new(),
        }
    }
}

impl Manifest {
    /// The registries by name (`[settings.registries]`)
    pub fn registries(&self) -> BTreeMap<String, String> {
        (self.settings.as_ref())
            .map(|s| s.registries.clone())
            .unwrap_or_default()
    }

    /// The catalogs to search: `[settings] catalogs`, then eBible.org's and fetch.bible's lists
    /// (unless `default-catalogs = false`)
    pub fn catalogs(&self) -> Vec<String> {
        self.catalogs_with(&[])
    }

    /// [`Manifest::catalogs`] with `more` (the machine's, from logoxide's config) after the
    /// manifest's own and before the default ones
    pub fn catalogs_with(&self, more: &[String]) -> Vec<String> {
        let settings = self.settings.clone().unwrap_or_default();
        let mut catalogs = settings.catalogs;
        for catalog in more {
            if !catalogs.contains(catalog) {
                catalogs.push(catalog.clone());
            }
        }
        if settings.default_catalogs {
            for default in crate::catalog::DEFAULT_CATALOGS {
                if !catalogs.iter().any(|c| c == default) {
                    catalogs.push(default.to_string());
                }
            }
        }
        catalogs
    }
}

/**
The categories a package can be in, and what each is for: subjects (what kind of package it is,
a commentary or a lexicon, is its `kind`). Traditions, eras, and narrower topics are keywords
*/
pub const CATEGORIES: [(&str, &str); 21] = [
    // The Bible
    (
        "biblical-theology",
        "Themes traced through Scripture (covenant, kingdom)",
    ),
    (
        "introduction",
        "Old and New Testament introductions and surveys, authorship, canon",
    ),
    (
        "background",
        "The Bible's history, archaeology, geography, and culture",
    ),
    ("hermeneutics", "How to interpret Scripture"),
    (
        "biblical-languages",
        "Greek, Hebrew, and Aramaic grammars and readers",
    ),
    // Theology
    ("systematic-theology", "Doctrine by topic"),
    (
        "creeds-and-confessions",
        "Creeds, confessions, and catechisms",
    ),
    ("apologetics", "Defending the faith"),
    ("ethics", "Christian ethics and moral theology"),
    // History
    ("church-history", "The church through the centuries"),
    ("biography", "Lives, memoirs, and letters"),
    // The church and its ministry
    ("preaching", "Homiletics: how to preach"),
    ("sermons", "Collected sermons"),
    (
        "pastoral",
        "Pastoral ministry, counseling, and church leadership",
    ),
    ("worship", "Liturgy, hymns, and prayer books"),
    ("missions", "Missions and evangelism"),
    // The Christian life
    ("spiritual-life", "Discipleship, prayer, and holiness"),
    ("devotional", "Daily readings and meditations"),
    ("family", "Marriage, parenting, and the home"),
    ("children", "Written for children"),
    // Reference
    (
        "reference",
        "Dictionaries, encyclopedias, atlases, and concordances",
    ),
];

/// How many categories a package can be in, so each one means something
pub const MAX_CATEGORIES: usize = 5;

/// Checks `keywords`, `categories`, and `about-books`
fn check_metadata(package: &Package) -> Result<()> {
    let err = |message: String| Err(LogoxideError::Manifest(message));
    let mut seen = BTreeSet::new();
    for keyword in &package.keywords {
        if keyword.trim().is_empty() || keyword.trim() != keyword {
            return err(format!(
                "keyword `{keyword}`: give words, without spaces around them"
            ));
        }
        if !seen.insert(keyword.to_lowercase()) {
            return err(format!("keyword `{keyword}` is listed twice"));
        }
    }
    if package.categories.len() > MAX_CATEGORIES {
        return err(format!(
            "{} categories: a package can be in at most {MAX_CATEGORIES} (keywords say more)",
            package.categories.len()
        ));
    }
    let mut seen = BTreeSet::new();
    for category in &package.categories {
        if !CATEGORIES.iter().any(|(c, _)| c == category) {
            let all: Vec<&str> = CATEGORIES.iter().map(|(c, _)| *c).collect();
            return err(format!(
                "category `{category}` is none of logoxide's ({}); a keyword can say it",
                all.join(", ")
            ));
        }
        if !seen.insert(category) {
            return err(format!("category `{category}` is listed twice"));
        }
    }
    let mut seen = BTreeSet::new();
    for book in &package.about_books {
        if crate::bible_data().books().search_usfm(book).is_none()
            || book.to_ascii_uppercase() != *book
        {
            return err(match book_code(book) {
                Some(code) => format!("about-books: `{book}` is written `{code}`"),
                None => format!("about-books: `{book}` is no book's USFM code (`ROM`, `1CO`)"),
            });
        }
        if !seen.insert(book) {
            return err(format!("about-books: `{book}` is listed twice"));
        }
    }
    Ok(())
}

/// A book's USFM code from its code in any case or its name (`rom`, `Romans`, `1 Cor` are `ROM`,
/// `ROM`, `1CO`)
pub fn book_code(name: &str) -> Option<String> {
    let books = crate::bible_data().books();
    let id = (books.search_usfm(&name.trim().to_ascii_uppercase()))
        .or_else(|| books.search(name.trim()))?;
    books.get_usfm(id).cloned()
}

/// What a feature selection turns on
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Enabled {
    pub features: BTreeSet<String>,
    /// Optional dependencies turned on (`dep:name`)
    pub dependencies: BTreeSet<String>,
    /// Features of dependencies (`name/feature`)
    pub dependency_features: BTreeMap<String, BTreeSet<String>>,
}

impl Manifest {
    /// Reads and checks a manifest
    pub fn parse(text: &str) -> Result<Manifest> {
        let mut manifest: Manifest =
            toml::from_str(text).map_err(|e| LogoxideError::Manifest(e.to_string()))?;
        // A kind with no language of its own may leave `language` out: it reads as `und`
        if let Some(package) = &mut manifest.package
            && package.language.is_empty()
            && !package.kind.needs_language()
        {
            package.language = String::from(crate::language::UNDETERMINED);
        }
        manifest.validate()?;
        Ok(manifest)
    }

    pub fn to_toml(&self) -> Result<String> {
        toml::to_string_pretty(self).map_err(|e| LogoxideError::Manifest(e.to_string()))
    }

    /// Checks what the types can't: ids, feature names, and where dependencies come from
    pub fn validate(&self) -> Result<()> {
        let err = |message: String| Err(LogoxideError::Manifest(message));
        if let Some(package) = &self.package {
            if !is_valid_id(&package.id) {
                return err(format!(
                    "package id `{}`: use lowercase letters, digits, `-`, and `_`",
                    package.id
                ));
            }
            check_metadata(package)?;
            if package.abbreviation.is_none() && package.kind.needs_abbreviation() {
                return err(format!(
                    "a {} needs an abbreviation (what references name it by: `BSB`)",
                    package.kind.name()
                ));
            }
            // Empty only in a manifest built in code for a kind that may leave it out (parsed,
            // it's `und`)
            match (package.language.is_empty(), package.kind.needs_language()) {
                (true, true) => {
                    return err(format!(
                        "a {} needs a language (BCP 47: `en`; `und` when unknown)",
                        package.kind.name()
                    ));
                }
                (true, false) => {}
                (false, _) => crate::language::check_language(&package.language)?,
            }
            if let Some(script) = &package.script {
                crate::language::check_script(script)?;
            }
            if let Some(license) = &package.license {
                crate::license::check_license(license)?;
            }
            if let Some(work) = &package.work {
                check_id("work", work)?;
            }
            if let Some(edition) = &package.edition {
                check_id("edition", edition)?;
            }
            // A collection is only its dependencies; a recording may read another's text
            let recording = (self.media.as_ref()).is_some_and(crate::media::Media::names_its_text);
            match (
                package.kind == PackageKind::Collection,
                self.formats.is_empty(),
            ) {
                (false, true) if !recording => {
                    return err(String::from(
                        "a package needs [formats] (a recording without a text of its own \
                         names the one it reads: [media] text, or versification)",
                    ));
                }
                (true, false) => {
                    return err(String::from(
                        "a collection has no [formats]: its packages are its dependencies",
                    ));
                }
                _ => {}
            }
            // A map names both versifications
            match (package.kind, &package.maps_to) {
                (PackageKind::VersificationMap, None) => {
                    return err(String::from(
                        "a versification map names what it maps to: maps-to = \"Original\"",
                    ));
                }
                (PackageKind::VersificationMap, Some(_)) if is_own(&package.versification) => {
                    return err(String::from(
                        "a versification map names what it maps from: versification = \"English\"",
                    ));
                }
                (PackageKind::VersificationMap, _) | (_, None) => {}
                (_, Some(_)) => {
                    return err(String::from(
                        "only a versification map has maps-to (kind = \"versification-map\")",
                    ));
                }
            }
            // A dictionary says what its entries are keyed by
            let dictionary =
                (self.formats.keys()).any(|n| Format::from_name(n) == Some(Format::Dictionary));
            match (dictionary, package.keys) {
                (true, None) => {
                    return err(String::from(
                        "a dictionary names what its entries are keyed by: keys = \"strongs-greek\", \
                         \"strongs-hebrew\", or \"headword\"",
                    ));
                }
                (false, Some(_)) => {
                    return err(String::from(
                        "only a dictionary has keys (a `dictionary` format)",
                    ));
                }
                _ => {}
            }
        }
        for (name, format) in &self.formats {
            if let Some(feature) = &format.feature
                && !self.features.contains_key(feature)
            {
                return err(format!(
                    "format `{name}` needs feature `{feature}`, which [features] doesn't have"
                ));
            }
        }
        for (feature, turns_on) in &self.features {
            for item in turns_on {
                if let Some(dep) = item.strip_prefix("dep:") {
                    match self.dependencies.get(dep) {
                        Some(Dependency::Detailed(d)) if d.optional => {}
                        _ => {
                            return err(format!(
                                "feature `{feature}`: `{item}` must name an optional dependency"
                            ));
                        }
                    }
                } else if let Some((dep, _)) = item.split_once('/') {
                    if !self.dependencies.contains_key(dep) {
                        return err(format!("feature `{feature}`: `{item}` names no dependency"));
                    }
                } else if !self.features.contains_key(item) {
                    return err(format!("feature `{feature}`: `{item}` is no feature"));
                }
            }
        }
        for (name, dependency) in &self.dependencies {
            let Dependency::Detailed(d) = dependency else {
                continue;
            };
            let sources = [
                d.git.is_some(),
                d.path.is_some(),
                d.registry.is_some(),
                d.import.is_some(),
            ];
            if sources.iter().filter(|s| **s).count() != 1 {
                return err(format!(
                    "dependency `{name}`: give one of `git`, `registry`, `path`, or `import`"
                ));
            }
            let pins = [&d.tag, &d.rev, &d.branch]
                .iter()
                .filter(|p| p.is_some())
                .count();
            if pins > 1 || (pins == 1 && d.git.is_none()) {
                return err(format!(
                    "dependency `{name}`: at most one of `tag`, `rev`, and `branch`, with `git`"
                ));
            }
            check_dependency(name, d)?;
        }
        if let Some(media) = &self.media {
            for file in &media.files {
                crate::media::check_sha256(&file.sha256)?;
            }
            if let Some(text) = &media.text
                && !self.dependencies.contains_key(text)
            {
                return err(format!(
                    "[media] text `{text}` names no dependency: the recording reads a text \
                     [dependencies] has"
                ));
            }
            if media
                .versification
                .as_deref()
                .is_some_and(|v| v.trim().is_empty())
            {
                return err(String::from("[media] versification is empty"));
            }
        }
        Ok(())
    }

    /**
    What's allowed but should change, for a caller to warn of: a `language` that isn't canonical
    BCP 47 (`eng`, which is `en`: [`crate::language::canonical`]), saying what it should be
    */
    pub fn warnings(&self) -> Vec<String> {
        (self.package.iter())
            .filter_map(|p| crate::language::canonical_warning(&p.language))
            .collect()
    }

    /**
    The keys in a manifest's text that logoxide doesn't know, as dotted paths
    (`package.funding`, `dependencies.kjv.mirror`), so a caller can warn of them as Cargo does.
    They're no error: a newer logoxide may write keys an older one doesn't read
    */
    pub fn unknown_keys(text: &str) -> Result<Vec<String>> {
        let table: toml::Table =
            toml::from_str(text).map_err(|e| LogoxideError::Manifest(e.to_string()))?;
        let mut unknown = vec![];
        let check = |at: &str, value: &toml::Value, fields: &[&str], unknown: &mut Vec<String>| {
            if let Some(table) = value.as_table() {
                for key in table.keys() {
                    if !fields.contains(&key.as_str()) {
                        unknown.push(format!("{at}.{key}"));
                    }
                }
            }
        };
        for (key, value) in &table {
            match key.as_str() {
                "package" => {
                    check(key, value, fields_of::<Package>(), &mut unknown);
                    if let Some(upstream) = value.get("upstream") {
                        let fields = fields_of::<Upstream>();
                        check("package.upstream", upstream, fields, &mut unknown);
                    }
                    if let Some(rights) = value.get("rights") {
                        let fields = fields_of::<crate::license::Rights>();
                        check("package.rights", rights, fields, &mut unknown);
                    }
                }
                "formats" | "dependencies" => {
                    let fields = match key.as_str() {
                        "formats" => fields_of::<FormatEntry>(),
                        _ => fields_of::<DetailedDependency>(),
                    };
                    for (name, entry) in value.as_table().into_iter().flatten() {
                        check(&format!("{key}.{name}"), entry, fields, &mut unknown);
                    }
                }
                "settings" => check(key, value, fields_of::<Settings>(), &mut unknown),
                "media" => {
                    check(key, value, fields_of::<crate::media::Media>(), &mut unknown);
                    let files = value.get("files").and_then(toml::Value::as_array);
                    for file in files.into_iter().flatten() {
                        let fields = fields_of::<crate::media::MediaFile>();
                        check("media.files", file, fields, &mut unknown);
                    }
                }
                _ if fields_of::<Manifest>().contains(&key.as_str()) => {}
                _ => unknown.push(key.clone()),
            }
        }
        unknown.sort();
        unknown.dedup();
        Ok(unknown)
    }
}

/// Whether `id` can be a package's id (or a dependency's name): lowercase letters, digits, `-`,
/// and `_`. Ids name folders in the library, so nothing else is allowed
pub fn is_valid_id(id: &str) -> bool {
    !id.is_empty()
        && (id.bytes())
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
}

/// [`is_valid_id`] as an error naming what the id is of
pub fn check_id(what: &str, id: &str) -> Result<()> {
    match is_valid_id(id) {
        true => Ok(()),
        false => Err(LogoxideError::Manifest(format!(
            "{what} `{id}`: use lowercase letters, digits, `-`, and `_`"
        ))),
    }
}

/**
Checks a dependency's `rev`: a commit's full object id (40 hex digits, or 64 for SHA-256
repositories). A shorter prefix could come to name another commit as the repository grows, and
only a whole one can be fetched by itself from a host
*/
pub fn check_rev(rev: &str) -> Result<()> {
    if matches!(rev.len(), 40 | 64) && rev.bytes().all(|b| b.is_ascii_hexdigit()) {
        return Ok(());
    }
    Err(LogoxideError::Manifest(format!(
        "rev `{rev}` isn't a full commit id (40 or 64 hex digits: `git rev-parse {rev}` gives \
         it); name a branch with `branch`, a tag with `tag`"
    )))
}

/**
Whether `name` reads as an import's name: a publisher's prefix (lowercase letters and digits), a
colon, and the publisher's id, with no control characters or spaces
*/
pub fn is_import_name(name: &str) -> bool {
    let Some((prefix, id)) = name.split_once(':') else {
        return false;
    };
    !prefix.is_empty()
        && prefix
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
        && !id.is_empty()
        && !id.starts_with('-')
        && !id.chars().any(|c| c.is_control() || c.is_whitespace())
}

/**
Checks what a dependency gives git and the library: its name and `package` are ids, and nothing
it hands git could be read as an option (`--upload-pack=…`), so a manifest from anywhere can't run
commands. A revision is a commit's hex; a folder is a plain relative path
*/
fn check_dependency(name: &str, d: &DetailedDependency) -> Result<()> {
    let err = |message: String| Err(LogoxideError::Manifest(message));
    check_id("dependency", name)?;
    if let Some(package) = &d.package {
        check_id(&format!("dependency `{name}`: package"), package)?;
    }
    for (key, value) in [
        ("git", &d.git),
        ("registry", &d.registry),
        ("import", &d.import),
        ("tag", &d.tag),
        ("branch", &d.branch),
        ("rev", &d.rev),
    ] {
        if let Some(value) = value
            && (value.starts_with('-') || value.trim().is_empty() || value.contains('\0'))
        {
            return err(format!(
                "dependency `{name}`: `{key} = \"{value}\"` isn't one"
            ));
        }
    }
    if let Some(import) = &d.import
        && !is_import_name(import)
    {
        return err(format!(
            "dependency `{name}`: `import = \"{import}\"` isn't an import (`ebible:eng-kjv2006`)"
        ));
    }
    // A registry by name (`doc/manifest.md`) is read as the rule says, but not resolved yet:
    // refused here, so no reader ever fetches `https://dorean`
    if let Some(registry) = &d.registry
        && is_registry_name(registry)
    {
        return err(format!(
            "dependency `{name}`: `registry = \"{registry}\"` names a registry by name, which \
             this logoxide doesn't resolve yet: give its catalog's URL or path (lx add \
             --registry <URL> {name})"
        ));
    }
    if let Some(rev) = &d.rev {
        check_rev(rev).map_err(|e| LogoxideError::Manifest(format!("dependency `{name}`: {e}")))?;
    }
    if let Some(folder) = &d.folder {
        let plain = |part: &str| {
            !part.is_empty()
                && part != "."
                && part != ".."
                && !part.starts_with('-')
                && !part.contains([':', '\\', '\0', '*', '?', '[', '~', '^'])
        };
        if !folder.trim_matches('/').split('/').all(plain) {
            return err(format!(
                "dependency `{name}`: folder `{folder}` isn't a folder in the repository"
            ));
        }
        if d.git.is_none() {
            return err(format!(
                "dependency `{name}`: `folder` names a folder of a `git` repository"
            ));
        }
    }
    Ok(())
}

/// Whether a dependency's `registry` is a registry's name (`dorean`: an id, resolved through
/// `[settings.registries]` and the config) rather than its catalog's URL or path, which has a
/// `/`, a `:`, or a `.` (`doc/manifest.md`)
pub fn is_registry_name(registry: &str) -> bool {
    !registry.contains(['/', ':', '.'])
}

/// The field names serde reads for a struct: its `deserialize_struct` hands them to the
/// deserializer, which this one keeps (and fails, having nothing to give)
fn fields_of<T: serde::de::DeserializeOwned>() -> &'static [&'static str] {
    use serde::de::Visitor;
    #[derive(Debug)]
    struct Fields(&'static [&'static str]);
    impl std::fmt::Display for Fields {
        fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
            write!(f, "fields")
        }
    }
    impl std::error::Error for Fields {}
    impl serde::de::Error for Fields {
        fn custom<M: std::fmt::Display>(_: M) -> Self {
            Fields(&[])
        }
    }
    struct Capture;
    impl<'de> serde::Deserializer<'de> for Capture {
        type Error = Fields;
        fn deserialize_any<V: Visitor<'de>>(self, _: V) -> std::result::Result<V::Value, Fields> {
            Err(Fields(&[]))
        }
        fn deserialize_struct<V: Visitor<'de>>(
            self,
            _: &'static str,
            fields: &'static [&'static str],
            _: V,
        ) -> std::result::Result<V::Value, Fields> {
            Err(Fields(fields))
        }
        serde::forward_to_deserialize_any! {
            bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
            option unit unit_struct newtype_struct seq tuple tuple_struct map enum identifier
            ignored_any
        }
    }
    match T::deserialize(Capture) {
        Err(Fields(fields)) => fields,
        Ok(_) => &[],
    }
}

impl Manifest {
    /// What `features` (plus `default`, unless left out) turn on, following each feature
    pub fn enable(&self, features: &[&str], default: bool) -> Result<Enabled> {
        let mut enabled = Enabled::default();
        let mut todo: Vec<String> = features.iter().map(|f| f.to_string()).collect();
        if default && self.features.contains_key("default") {
            todo.push(String::from("default"));
        }
        while let Some(feature) = todo.pop() {
            if !enabled.features.insert(feature.clone()) {
                continue;
            }
            let Some(turns_on) = self.features.get(&feature) else {
                return Err(LogoxideError::Manifest(format!("no feature `{feature}`")));
            };
            for item in turns_on {
                if let Some(dep) = item.strip_prefix("dep:") {
                    enabled.dependencies.insert(dep.to_string());
                } else if let Some((dep, f)) = item.split_once('/') {
                    enabled.dependencies.insert(dep.to_string());
                    (enabled
                        .dependency_features
                        .entry(dep.to_string())
                        .or_default())
                    .insert(f.to_string());
                } else {
                    todo.push(item.clone());
                }
            }
        }
        enabled.features.remove("default");
        Ok(enabled)
    }

    /// The formats the enabled features turn on (and those without a feature), by name
    pub fn formats(&self, enabled: &Enabled) -> Vec<(&str, &FormatEntry)> {
        self.formats
            .iter()
            .filter(|(_, f)| {
                f.feature
                    .as_ref()
                    .is_none_or(|f| enabled.features.contains(f))
            })
            .map(|(name, f)| (name.as_str(), f))
            .collect()
    }
}

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

    /// A commentary's manifest with these lines added to its `[package]`
    fn commentary(lines: &str) -> Result<Manifest> {
        Manifest::parse(&format!(
            "[package]\nid = \"gill\"\nname = \"Gill on Romans\"\nabbreviation = \"GILL\"\n\
             version = \"1.0.0\"\nlanguage = \"en\"\nkind = \"commentary\"\n{lines}\n\
             [formats]\nusx = {{ path = \"usx/\" }}\n"
        ))
    }

    #[test]
    fn abbreviation_and_language_by_kind() {
        let package = |kind: &str, lines: &str| {
            Manifest::parse(&format!(
                "[package]\nid = \"x\"\nname = \"X\"\nversion = \"1.0.0\"\nkind = \"{kind}\"\n\
                 {lines}\n[formats]\nepub = {{ path = \"books/\" }}\n"
            ))
        };
        let collection = |lines: &str| {
            Manifest::parse(&format!(
                "[package]\nid = \"x\"\nname = \"X\"\nversion = \"1.0.0\"\nkind = \"collection\"\n{lines}\n"
            ))
        };
        // References name Bibles and commentaries, so those need an abbreviation
        for kind in ["bible", "commentary"] {
            let error = package(kind, "language = \"en\"").unwrap_err().to_string();
            assert!(error.contains("needs an abbreviation"), "{kind}: {error}");
        }
        // The other kinds don't; `short_name` is then the id
        let book = package("book", "language = \"en\"").unwrap();
        let info = book.package.as_ref().unwrap();
        assert_eq!(
            (info.abbreviation.as_deref(), info.short_name()),
            (None, "x")
        );
        assert!(!book.to_toml().unwrap().contains("abbreviation"));
        let named = package("book", "language = \"en\"\nabbreviation = \"TDP\"").unwrap();
        assert_eq!(named.package.unwrap().short_name(), "TDP");
        // A collection or a map has no language of its own: left out, it reads as `und`
        let info = collection("").unwrap().package.unwrap();
        assert_eq!(info.language, "und");
        let map = package(
            "versification-map",
            "versification = \"English\"\nmaps-to = \"Original\"",
        );
        assert_eq!(map.unwrap().package.unwrap().language, "und");
        // Everything else still needs one
        let error = package("book", "").unwrap_err().to_string();
        assert!(error.contains("needs a language"), "{error}");
        let error = package("lexicon", "keys = \"headword\"")
            .unwrap_err()
            .to_string();
        assert!(error.contains("needs a language"), "{error}");
        // What's said is still checked
        assert!(collection("language = \"en_US\"").is_err());
    }

    #[test]
    fn metadata_like_cargos() {
        let manifest = commentary(
            r#"keywords = ["justification", "Puritan"]
categories = ["church-history", "biography"]
about-books = ["ROM", "1CO"]
repository = "https://github.com/someone/gill"
documentation = "https://example.org/gill"
readme = "README.md""#,
        )
        .unwrap();
        let info = manifest.package.as_ref().unwrap();
        assert_eq!(info.about_books, ["ROM", "1CO"]);
        assert_eq!(info.categories, ["church-history", "biography"]);
        assert_eq!(info.readme.as_deref(), Some("README.md"));
        // Written back the same way
        assert_eq!(
            Manifest::parse(&manifest.to_toml().unwrap()).unwrap(),
            manifest
        );
        assert!(manifest.to_toml().unwrap().contains("about-books = ["));

        let error = |lines: &str| commentary(lines).unwrap_err().to_string();
        assert!(error(r#"about-books = ["Romans"]"#).contains("`Romans` is written `ROM`"));
        assert!(error(r#"about-books = ["rom"]"#).contains("`rom` is written `ROM`"));
        assert!(error(r#"about-books = ["XYZ"]"#).contains("no book's USFM code"));
        assert!(error(r#"about-books = ["ROM", "ROM"]"#).contains("listed twice"));
        assert!(error(r#"categories = ["reformed"]"#).contains("none of logoxide's"));
        assert!(error(r#"categories = ["Church History"]"#).contains("none of logoxide's"));
        assert!(error(r#"categories = ["ethics", "ethics"]"#).contains("listed twice"));
        let six =
            r#"categories = ["ethics", "sermons", "worship", "missions", "family", "children"]"#;
        assert!(error(six).contains("at most 5"));
        assert!(error(r#"keywords = [" grace"]"#).contains("without spaces"));
        assert!(error(r#"keywords = ["grace", "Grace"]"#).contains("listed twice"));
    }

    #[test]
    fn languages_scripts_and_directions() {
        let with = |language: &str, lines: &str| {
            Manifest::parse(&format!(
                "[package]\nid = \"x\"\nname = \"X\"\nabbreviation = \"X\"\nversion = \"1.0.0\"\n\
                 language = \"{language}\"\n{lines}\n[formats]\nusx = {{ path = \"usx/\" }}\n"
            ))
            .map(|m| m.package.unwrap())
        };
        // The script from the tag, the direction from the script
        let serbian = with("sr-Latn", "").unwrap();
        assert_eq!(serbian.text_script().as_deref(), Some("Latn"));
        assert_eq!(serbian.text_direction(), Direction::Ltr);
        let hebrew = with("he", "script = \"Hebr\"").unwrap();
        assert_eq!(hebrew.text_direction(), Direction::Rtl);
        // Said, the direction wins
        let said = with("he", "script = \"Hebr\"\ndirection = \"ltr\"").unwrap();
        assert_eq!(said.text_direction(), Direction::Ltr);
        // Neither says: left to right
        assert_eq!(with("he", "").unwrap().text_direction(), Direction::Ltr);
        let error = |language: &str, lines: &str| with(language, lines).unwrap_err().to_string();
        assert!(error("en_US", "").contains("isn't a BCP 47 tag"));
        assert!(error("en", "script = \"latin\"").contains("ISO 15924"));
        // A tag that isn't canonical is read, and warned of
        let warnings = |language: &str| {
            Manifest::parse(&format!(
                "[package]\nid = \"x\"\nname = \"X\"\nabbreviation = \"X\"\nversion = \"1.0.0\"\n\
                 language = \"{language}\"\n[formats]\nusx = {{ path = \"usx/\" }}\n"
            ))
            .map(|m| m.warnings())
        };
        assert_eq!(
            warnings("eng-latn").unwrap(),
            [
                "language `eng-latn` isn't canonical BCP 47: use `en-Latn` (the shortest ISO 639 \
              code, in its case)"
            ]
        );
        assert!(warnings("en-Latn").unwrap().is_empty());
        assert!(warnings("grc").unwrap().is_empty());
    }

    #[test]
    fn a_dictionary_names_its_keys() {
        let dictionary = |keys: &str, format: &str| {
            Manifest::parse(&format!(
                "[package]\nid = \"strongs\"\nname = \"Strong's\"\nabbreviation = \"STR\"\n\
                 version = \"1.0.0\"\nlanguage = \"grc\"\nkind = \"lexicon\"\n{keys}\n\
                 [formats]\n{format}\n"
            ))
        };
        let entries = "dictionary = { path = \"entries/\" }";
        let manifest = dictionary("keys = \"strongs-greek\"", entries).unwrap();
        let info = manifest.package.as_ref().unwrap();
        assert_eq!(info.keys, Some(Keys::StrongsGreek));
        assert_eq!(
            Manifest::parse(&manifest.to_toml().unwrap()).unwrap(),
            manifest
        );
        let error = |keys: &str, format: &str| dictionary(keys, format).unwrap_err().to_string();
        assert!(error("", entries).contains("keys = \"strongs-greek\""));
        assert!(error("keys = \"strong\"", entries).contains("unknown variant"));
        assert!(
            error("keys = \"headword\"", "usx = { path = \"usx/\" }").contains("only a dictionary")
        );
        assert!(dictionary("", "xref = { path = \"xref/\" }").is_ok());
        assert_eq!(Keys::from_name("Strongs-Hebrew"), Some(Keys::StrongsHebrew));
        assert_eq!(Keys::Headword.name(), "headword");
        // The new formats' files, by extension
        assert_eq!(Format::from_name("dictionary"), Some(Format::Dictionary));
        assert_eq!(Format::Dictionary.extensions(), Some(&["xml"][..]));
        assert_eq!(Format::Xref.extensions(), Some(&["tsv"][..]));
        assert_eq!(Format::Gbf.extensions(), Some(&["gbf", "txt"][..]));
        for format in [Format::Gbf, Format::Dictionary, Format::Xref] {
            assert_eq!(Format::from_name(format.name()), Some(format));
        }
        assert!(Format::Gbf.is_verse_text() && !Format::Dictionary.is_verse_text());
    }

    #[test]
    fn book_codes_from_names() {
        assert_eq!(book_code("Romans").as_deref(), Some("ROM"));
        assert_eq!(book_code("rom").as_deref(), Some("ROM"));
        assert_eq!(book_code("1 Corinthians").as_deref(), Some("1CO"));
        assert_eq!(book_code("Song of Songs").as_deref(), Some("SNG"));
        assert_eq!(book_code("nothing"), None);
    }

    const BSB: &str = r#"
[package]
id = "bsb"
name = "Berean Standard Bible"
abbreviation = "BSB"
aliases = ["Berean"]
version = "1.2.0"
language = "en"
license = "LicenseRef-PublicDomain"

[formats]
usx = { path = "usx/", feature = "usx" }
sword = { path = "sword/", feature = "sword" }

[features]
default = ["usx", "headings"]
usx = []
sword = []
headings = []
strongs = ["dep:strongs-greek", "tsk/full"]

[dependencies]
strongs-greek = { git = "https://example.org/strongs", version = "2", optional = true }
tsk = { git = "https://example.org/tsk", tag = "v1.0.0" }
"#;

    #[test]
    fn reads_a_package() {
        let m = Manifest::parse(BSB).unwrap();
        let p = m.package.as_ref().unwrap();
        assert_eq!(
            (p.id.as_str(), p.version.to_string()),
            ("bsb", "1.2.0".into())
        );
        assert_eq!(p.kind, PackageKind::Bible);
        assert_eq!(p.versification, "own");
        // Round trip
        assert_eq!(Manifest::parse(&m.to_toml().unwrap()).unwrap(), m);
    }

    #[test]
    fn features_turn_on_formats_and_dependencies() {
        let m = Manifest::parse(BSB).unwrap();
        let names = |e: &Enabled| {
            m.formats(e)
                .iter()
                .map(|(n, _)| n.to_string())
                .collect::<Vec<_>>()
        };
        let default = m.enable(&[], true).unwrap();
        assert_eq!(
            default.features,
            BTreeSet::from(["usx".into(), "headings".into()])
        );
        assert_eq!(names(&default), ["usx"]);
        let more = m.enable(&["sword", "strongs"], false).unwrap();
        assert_eq!(names(&more), ["sword"]);
        assert_eq!(
            more.dependencies,
            BTreeSet::from(["strongs-greek".into(), "tsk".into()])
        );
        assert_eq!(
            more.dependency_features["tsk"],
            BTreeSet::from(["full".into()])
        );
        assert!(m.enable(&["nope"], false).is_err());
    }

    #[test]
    fn a_vault_has_no_package() {
        let m = Manifest::parse(
            r#"
[dependencies]
bsb = { git = "https://example.org/bsb", version = "1" }
mine = { path = "Bibles/Mine" }
later = "2"

[settings]
default = "bsb"
compare = ["mine"]
"#,
        )
        .unwrap();
        assert!(m.package.is_none());
        assert!(matches!(m.dependencies["later"], Dependency::Version(_)));
        assert_eq!(m.settings.unwrap().default.as_deref(), Some("bsb"));
    }

    #[test]
    fn a_vaults_catalogs_come_before_the_defaults() {
        use crate::catalog::{
            CCEL_CATALOG, CCEL_COMMENTARIES_CATALOG, DEFAULT_CATALOGS, EBIBLE_CATALOG,
            FETCH_BIBLE_CATALOG, SWORD_CATALOG,
        };
        let catalogs = |settings: &str| {
            Manifest::parse(&format!("[dependencies]\n[settings]\n{settings}"))
                .unwrap()
                .catalogs()
        };
        assert_eq!(Manifest::default().catalogs(), DEFAULT_CATALOGS);
        assert_eq!(
            catalogs("catalogs = [\"mine.toml\"]"),
            [
                "mine.toml",
                EBIBLE_CATALOG,
                FETCH_BIBLE_CATALOG,
                CCEL_CATALOG,
                CCEL_COMMENTARIES_CATALOG,
                SWORD_CATALOG
            ]
        );
        // Named again: listed once, where the vault puts it
        let again = format!("catalogs = [\"{FETCH_BIBLE_CATALOG}\", \"mine.toml\"]");
        assert_eq!(
            catalogs(&again),
            [
                FETCH_BIBLE_CATALOG,
                "mine.toml",
                EBIBLE_CATALOG,
                CCEL_CATALOG,
                CCEL_COMMENTARIES_CATALOG,
                SWORD_CATALOG
            ]
        );
        assert_eq!(
            catalogs("catalogs = [\"mine.toml\"]\ndefault-catalogs = false"),
            ["mine.toml"]
        );
    }

    #[test]
    fn mistakes_are_explained() {
        let bad = |extra: &str| {
            Manifest::parse(&format!("{BSB}\n{extra}"))
                .unwrap_err()
                .to_string()
        };
        assert!(
            bad("x = { path = \"a\", git = \"b\" }")
                .contains("give one of `git`, `registry`, `path`, or `import`")
        );
        assert!(bad("y = { path = \"a\", tag = \"v1\" }").contains("with `git`"));
        assert!(
            bad("z = { import = \"ebible:eng-asv\", git = \"b\" }")
                .contains("give one of `git`, `registry`, `path`, or `import`")
        );
        assert!(bad("z = { import = \"ebible:eng-asv\", tag = \"v1\" }").contains("with `git`"));
        for import in ["eng-asv", "Ebible:x", "ebible:", "ebible:-x", "ebible:a b"] {
            let error = bad(&format!("z = {{ import = \"{import}\" }}"));
            assert!(error.contains("isn't an import"), "{import}: {error}");
        }
        assert!(
            Manifest::parse(&format!(
                "{BSB}\nz = {{ import = \"sword:crosswire/KJV\" }}"
            ))
            .is_ok()
        );
        let wrong_dep = BSB.replace("dep:strongs-greek", "dep:tsk");
        assert!(
            Manifest::parse(&wrong_dep)
                .unwrap_err()
                .to_string()
                .contains("optional dependency")
        );
        let typo = BSB.replace("abbreviation", "abbrev");
        assert!(Manifest::parse(&typo).is_err());
        // Nothing that git reads as an option, and revisions are commits
        for (dependency, message) in [
            ("x = { git = \"--upload-pack=touch /tmp/x\" }", "isn't one"),
            (
                "x = { git = \"https://e.org/x\", tag = \"-x\" }",
                "isn't one",
            ),
            (
                "x = { git = \"https://e.org/x\", branch = \"--x\" }",
                "isn't one",
            ),
            (
                "x = { git = \"https://e.org/x\", rev = \"--x\" }",
                "isn't one",
            ),
            (
                "x = { git = \"https://e.org/x\", rev = \"main\" }",
                "isn't a full commit id",
            ),
            (
                "x = { git = \"https://e.org/x\", rev = \"abc\" }",
                "isn't a full commit id",
            ),
            (
                "x = { git = \"https://e.org/x\", rev = \"3f9c2a1b\" }",
                "isn't a full commit id",
            ),
            ("x = { registry = \"-r\" }", "isn't one"),
            // A registry by name is the format's rule, not resolved yet
            ("x = { registry = \"dorean\" }", "by name"),
            ("x = { registry = \"dorean_local\" }", "by name"),
            ("\"../x\" = { git = \"https://e.org/x\" }", "lowercase"),
            (
                "x = { git = \"https://e.org/x\", package = \"../x\" }",
                "lowercase",
            ),
            (
                "x = { git = \"https://e.org/x\", folder = \"../x\" }",
                "isn't a folder",
            ),
            (
                "x = { path = \"x\", folder = \"x\" }",
                "of a `git` repository",
            ),
        ] {
            let error = bad(dependency);
            assert!(error.contains(message), "{dependency}: {error}");
        }
        let fine = format!(
            "{BSB}\nx = {{ git = \"https://e.org/x\", rev = \"{}\" }}\n",
            "3f".repeat(20)
        );
        assert!(Manifest::parse(&fine).is_ok());
        let sha256 = format!(
            "{BSB}\nx = {{ git = \"https://e.org/x\", rev = \"{}\" }}\n",
            "3f".repeat(32)
        );
        assert!(Manifest::parse(&sha256).is_ok());
        let folder = format!("{BSB}\nx = {{ git = \"https://e.org/x\", folder = \"books/x\" }}\n");
        let folder = Manifest::parse(&folder).unwrap();
        let Dependency::Detailed(x) = &folder.dependencies["x"] else {
            panic!("detailed")
        };
        assert_eq!(x.folder.as_deref(), Some("books/x"));
    }

    #[test]
    fn unknown_keys_are_named_not_refused() {
        // A newer lx's keys: read, and named so a caller can warn
        let newer = BSB
            .replace(
                "license = \"LicenseRef-PublicDomain\"",
                "license = \"LicenseRef-PublicDomain\"\nfunding = \"https://e.org\"\nupstream = { url = \"u\", import = \"ebible:x\", date = \"d\" }",
            )
            .replace(
                "tag = \"v1.0.0\" }",
                "tag = \"v1.0.0\", mirror = \"https://m.org\" }",
            )
            .replace(
                "usx = { path = \"usx/\", feature = \"usx\" }",
                "usx = { path = \"usx/\", feature = \"usx\", encoding = \"utf-8\" }",
            )
            + "\n[settings]\ndefault = \"bsb\"\ntheme = \"dark\"\n\n[media]\nplayer = \"x\"\n\n[[media.files]]\npath = \"a.mp3\"\nurl = \"u\"\nsize = 0\nsha256 = \"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855\"\nlength = 3\n\n[plugins]\nx = 1\n";
        let manifest = Manifest::parse(&newer).unwrap();
        assert_eq!(manifest.package.unwrap().id, "bsb");
        assert_eq!(
            Manifest::unknown_keys(&newer).unwrap(),
            [
                "dependencies.tsk.mirror",
                "formats.usx.encoding",
                "media.files.length",
                "media.player",
                "package.funding",
                "package.upstream.date",
                "plugins",
                "settings.theme"
            ]
        );
        assert!(Manifest::unknown_keys(BSB).unwrap().is_empty());
        // Values still have to make sense
        assert!(Manifest::parse(&BSB.replace("version = \"1.2.0\"", "version = 3")).is_err());
        let id = BSB.replace("id = \"bsb\"", "id = \"BSB 2\"");
        assert!(
            Manifest::parse(&id)
                .unwrap_err()
                .to_string()
                .contains("lowercase")
        );
    }
}