sbol-cli 0.2.0

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

use std::collections::BTreeSet;
use std::env;
use std::fs;
use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::{Parser, Subcommand, ValueEnum};

use sbol::{
    Blocker, Document, DowngradeOptions, DowngradeWarning, ExternalValidationMode, FileResolver,
    MapsToSide, NamespaceSource, NormativeSeverity, RdfFormat, ReadError, RuleStatus, Severity,
    UpgradeCounts, UpgradeOptions, UpgradeReport, UpgradeWarning, ValidationContext,
    ValidationIssue, ValidationOptions, ValidationReport, ValidationRuleStatus, WriteError,
    validation_rule_statuses,
};
use sbol_ontology::{KnownOntology, OntologyCache, OntologyDescriptor};
use serde_json::{Value, json};

#[cfg(feature = "http-resolver")]
use sbol::CachingHttpResolver;

#[cfg(feature = "sarif")]
mod sarif;

#[derive(Parser)]
#[command(
    name = "sbol",
    version = env!("SBOL_VERSION_FULL"),
    about = "Command-line tool for SBOL 3 documents",
    propagate_version = true
)]
struct Cli {
    /// When to colorize output. `auto` colorizes the streams that are
    /// TTYs and `NO_COLOR` is unset.
    #[arg(long, value_enum, default_value_t = ColorMode::Auto, global = true)]
    color: ColorMode,

    #[command(subcommand)]
    command: Command,
}

#[derive(Clone, Copy)]
struct Styles {
    stdout: bool,
    stderr: bool,
}

impl Styles {
    fn resolve(mode: ColorMode) -> Self {
        let no_color = env::var_os("NO_COLOR").is_some();
        match mode {
            ColorMode::Always => Self {
                stdout: true,
                stderr: true,
            },
            ColorMode::Never => Self {
                stdout: false,
                stderr: false,
            },
            ColorMode::Auto => Self {
                stdout: !no_color && io::stdout().is_terminal(),
                stderr: !no_color && io::stderr().is_terminal(),
            },
        }
    }

    fn err_label(self) -> &'static str {
        if self.stderr {
            "\x1b[1;31merror\x1b[0m"
        } else {
            "error"
        }
    }
}

fn paint(enabled: bool, code: &str, text: &str) -> String {
    if enabled {
        format!("\x1b[{code}m{text}\x1b[0m")
    } else {
        text.to_string()
    }
}

fn severity_code(severity: Severity) -> Option<&'static str> {
    match severity {
        Severity::Error => Some("1;31"),
        Severity::Warning => Some("1;33"),
        _ => None,
    }
}

fn rule_status_code(status: RuleStatus) -> Option<&'static str> {
    match status {
        RuleStatus::Error => Some("31"),
        RuleStatus::Warning => Some("33"),
        RuleStatus::Configurable => Some("36"),
        RuleStatus::MachineUncheckable => Some("90"),
        RuleStatus::Unimplemented => Some("35"),
        _ => None,
    }
}

#[derive(Subcommand)]
enum Command {
    /// Validate an SBOL 3 document against the spec.
    Validate(ValidateArgs),
    /// Convert an SBOL 3 document between RDF serializations.
    Convert(ConvertArgs),
    /// Upgrade an SBOL 2 RDF document to SBOL 3.
    Upgrade(UpgradeArgs),
    /// Downgrade an SBOL 3 RDF document to SBOL 2.
    Downgrade(DowngradeArgs),
    /// Import a GenBank file (.gb / .gbk) into SBOL 3.
    ImportGenbank(ImportGenbankArgs),
    /// Import a FASTA file (.fasta / .fa / .fna / .faa) into SBOL 3.
    ImportFasta(ImportFastaArgs),
    /// Inspect the built-in validation rule catalog.
    #[command(subcommand)]
    Rules(RulesCommand),
    /// Manage cached extension ontologies (NCIT and others).
    #[command(subcommand)]
    Ontology(OntologyCommand),
}

#[derive(Subcommand)]
enum RulesCommand {
    /// List validation rules, their implementation status, and spec section.
    List(RulesListArgs),
}

#[derive(Subcommand)]
enum OntologyCommand {
    /// Download and build a named ontology extension into the cache.
    Install(OntologyInstallArgs),
    /// List installed ontology extensions.
    List,
    /// Print the cache directory path.
    Path,
    /// Remove an installed ontology extension.
    Remove(OntologyRemoveArgs),
    /// Re-hash an installed extension's TSV and compare against its
    /// manifest. Errors if the extension is missing or tampered with.
    Verify(OntologyVerifyArgs),
}

#[derive(clap::Args)]
struct OntologyInstallArgs {
    /// Built-in ontology to install. Currently: `ncit`.
    name: String,
    /// Re-download and rebuild even if already installed.
    #[arg(long)]
    force: bool,
}

#[derive(clap::Args)]
struct OntologyRemoveArgs {
    /// Cache entry name (e.g. `ncit`).
    name: String,
}

#[derive(clap::Args)]
struct OntologyVerifyArgs {
    /// Cache entry name to verify. If omitted, every installed
    /// extension is verified.
    name: Option<String>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum OutputFormat {
    Text,
    Json,
    #[cfg(feature = "sarif")]
    Sarif,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum RulesFormat {
    Text,
    Json,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum ColorMode {
    Auto,
    Always,
    Never,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum RuleStatusFilter {
    Error,
    Warning,
    Configurable,
    MachineUncheckable,
    Unimplemented,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum RdfFormatArg {
    Turtle,
    Rdfxml,
    Jsonld,
    Ntriples,
}

impl From<RdfFormatArg> for RdfFormat {
    fn from(value: RdfFormatArg) -> Self {
        match value {
            RdfFormatArg::Turtle => RdfFormat::Turtle,
            RdfFormatArg::Rdfxml => RdfFormat::RdfXml,
            RdfFormatArg::Jsonld => RdfFormat::JsonLd,
            RdfFormatArg::Ntriples => RdfFormat::NTriples,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum SeverityArg {
    Warning,
    Error,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum ExternalModeArg {
    Off,
    Provided,
    Allowed,
}

impl From<ExternalModeArg> for ExternalValidationMode {
    fn from(value: ExternalModeArg) -> Self {
        match value {
            ExternalModeArg::Off => ExternalValidationMode::Off,
            ExternalModeArg::Provided => ExternalValidationMode::ProvidedOnly,
            ExternalModeArg::Allowed => ExternalValidationMode::ExternalAllowed,
        }
    }
}

impl From<SeverityArg> for Severity {
    fn from(value: SeverityArg) -> Self {
        match value {
            SeverityArg::Warning => Severity::Warning,
            SeverityArg::Error => Severity::Error,
        }
    }
}

#[derive(clap::Args)]
struct ValidateArgs {
    /// Path to an SBOL 3 document. Format is inferred from the extension —
    /// `.ttl` (Turtle), `.rdf` (RDF/XML), `.jsonld` (JSON-LD), or `.nt`
    /// (N-Triples).
    path: PathBuf,

    /// Output format.
    #[arg(long, value_enum, default_value_t = OutputFormat::Text)]
    format: OutputFormat,

    /// Destination for output. Use `-` for stdout.
    #[arg(long, default_value = "-")]
    output: String,

    /// Suppress diagnostics for these rule IDs (e.g. `--allow sbol3-10502`).
    #[arg(long = "allow", value_name = "RULE_ID")]
    allow: Vec<String>,

    /// Promote these rule IDs to error severity.
    #[arg(long = "deny", value_name = "RULE_ID")]
    deny: Vec<String>,

    /// Demote these rule IDs to warning severity.
    #[arg(long = "warn", value_name = "RULE_ID")]
    warn: Vec<String>,

    /// Floor on the severity of any emitted issue.
    #[arg(long, value_enum)]
    severity_floor: Option<SeverityArg>,

    /// Ceiling on the severity of any emitted issue.
    #[arg(long, value_enum)]
    severity_ceiling: Option<SeverityArg>,

    /// Treat warnings as errors (alias for `--severity-floor error`).
    #[arg(long)]
    treat_warnings_as_errors: bool,

    /// Use `Document::check_complete` semantics: any rule with partial
    /// coverage causes exit code 3.
    #[arg(long)]
    treat_partial_as_errors: bool,

    /// In text output, print a coverage summary after the issues.
    #[arg(long)]
    show_coverage: bool,

    /// Whether to resolve external documents and content.
    #[arg(long, value_enum, default_value_t = ExternalModeArg::Off)]
    external_mode: ExternalModeArg,

    /// Filesystem roots from which external Attachment / Model / TopLevel
    /// references may be resolved.
    #[arg(long = "resolve-documents", value_name = "DIR")]
    resolve_documents: Vec<PathBuf>,

    /// Filesystem roots for Attachment / Model byte content.
    #[arg(long = "resolve-content", value_name = "DIR")]
    resolve_content: Vec<PathBuf>,

    /// Cache directory required by `--external-mode allowed` when the
    /// `http-resolver` feature is built in.
    #[arg(long)]
    cache_dir: Option<PathBuf>,

    /// Layer an installed runtime ontology extension on top of the bundled
    /// facts for this validation run. Pass the cache entry name (e.g.
    /// `--ontology ncit`). Repeatable; later extensions override earlier
    /// ones on conflict.
    #[arg(long = "ontology", value_name = "NAME")]
    ontology: Vec<String>,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum UpgradeReportFormat {
    None,
    Text,
    Json,
}

#[derive(clap::Args)]
struct UpgradeArgs {
    /// Path to an SBOL 2 RDF document. Input format is inferred from the
    /// extension — `.ttl` (Turtle), `.rdf` / `.xml` (RDF/XML), `.jsonld`
    /// (JSON-LD), or `.nt` (N-Triples). Use `--from` to override.
    path: PathBuf,

    /// Override the input format inference. Useful for SBOL 2 files
    /// distributed with non-standard extensions.
    #[arg(long, value_enum, value_name = "FORMAT")]
    from: Option<RdfFormatArg>,

    /// Target SBOL 3 RDF serialization. If omitted, inferred from
    /// `--output`'s extension.
    #[arg(long, value_enum, value_name = "FORMAT")]
    to: Option<RdfFormatArg>,

    /// Destination path for the SBOL 3 output. Use `-` (the default) for
    /// stdout; in that case `--to` is required.
    #[arg(long, short = 'o', default_value = "-")]
    output: String,

    /// Default `hasNamespace` value for top-level objects whose namespace
    /// cannot be derived from the input. Without this flag, such objects
    /// fall back to the URL scheme+host or, failing that, omit
    /// `hasNamespace` entirely.
    #[arg(long, value_name = "IRI")]
    namespace: Option<String>,

    /// Where to write the conversion report.
    #[arg(long, value_enum, default_value_t = UpgradeReportFormat::None)]
    report: UpgradeReportFormat,

    /// Exit with status 1 if any conversion warnings were produced.
    #[arg(long)]
    strict: bool,

    /// Run SBOL 3 validation on the converted document and fold the result
    /// into the exit code: code 1 if validation finds errors.
    #[arg(long)]
    validate: bool,
}

#[derive(clap::Args)]
struct DowngradeArgs {
    /// Path to an SBOL 3 RDF document. Input format is inferred from
    /// the extension (`.ttl`, `.rdf` / `.xml`, `.jsonld`, `.nt`).
    path: PathBuf,

    /// Override the input format inference. Useful for SBOL 3 RDF files
    /// distributed with non-standard extensions.
    #[arg(long, value_enum, value_name = "FORMAT")]
    from: Option<RdfFormatArg>,

    /// Target SBOL 2 RDF serialization. If omitted, inferred from
    /// `--output`'s extension.
    #[arg(long, value_enum, value_name = "FORMAT")]
    to: Option<RdfFormatArg>,

    /// Destination path. Use `-` (the default) for stdout; in that
    /// case `--to` is required.
    #[arg(long, short = 'o', default_value = "-")]
    output: String,

    /// Version string assigned to top-level objects whose source
    /// document didn't carry `backport:sbol2version`. Omit to leave
    /// such subjects unversioned (SBOL 2 makes `sbol2:version`
    /// optional); pass `--default-version 1` to match the libSBOLj /
    /// SynBioHub convention of always emitting one.
    #[arg(long, value_name = "VERSION")]
    default_version: Option<String>,

    /// Validate the downgrade by round-tripping the produced SBOL 2
    /// back up through `sbol::upgrade` and running SBOL 3 validation
    /// on the result. There is no native SBOL 2 validator in this
    /// workspace, so this round-trip is the proxy for structural
    /// correctness. Exit code 1 on validation errors.
    #[arg(long)]
    validate: bool,

    /// Exit with status 1 if any downgrade warnings were produced.
    #[arg(long)]
    strict: bool,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, ValueEnum)]
enum FastaAlphabetArg {
    Dna,
    Rna,
    Protein,
}

impl From<FastaAlphabetArg> for sbol_fasta::Alphabet {
    fn from(value: FastaAlphabetArg) -> Self {
        match value {
            FastaAlphabetArg::Dna => sbol_fasta::Alphabet::Dna,
            FastaAlphabetArg::Rna => sbol_fasta::Alphabet::Rna,
            FastaAlphabetArg::Protein => sbol_fasta::Alphabet::Protein,
        }
    }
}

#[derive(clap::Args)]
struct ImportFastaArgs {
    /// Path to a FASTA file (`.fasta` / `.fa` / `.fna` / `.faa`).
    path: PathBuf,

    /// Namespace IRI under which the resulting SBOL 3 top-level
    /// objects will be rooted. Required because FASTA carries no
    /// namespace concept.
    #[arg(long, short = 'n', value_name = "IRI")]
    namespace: String,

    /// Override alphabet auto-detection. Pass when the sequence text
    /// is ambiguous (e.g. a short peptide composed only of A/C/G/T
    /// letters that would otherwise be misclassified as DNA).
    #[arg(long, value_enum, value_name = "ALPHABET")]
    alphabet: Option<FastaAlphabetArg>,

    /// Target SBOL 3 RDF serialization. If omitted, inferred from
    /// `--output`'s extension.
    #[arg(long, value_enum, value_name = "FORMAT")]
    to: Option<RdfFormatArg>,

    /// Destination path. Use `-` (the default) for stdout; in that
    /// case `--to` is required.
    #[arg(long, short = 'o', default_value = "-")]
    output: String,

    /// Run SBOL 3 validation on the converted document and fold the
    /// result into the exit code: code 1 if validation finds errors.
    #[arg(long)]
    validate: bool,

    /// Exit with status 1 if any import warnings were produced.
    #[arg(long)]
    strict: bool,
}

#[derive(clap::Args)]
struct ImportGenbankArgs {
    /// Path to a GenBank flat-file (`.gb` / `.gbk`). Mixed-case month
    /// names in the LOCUS line (as emitted by SynBioHub) are tolerated.
    path: PathBuf,

    /// Namespace IRI under which the resulting SBOL 3 top-level
    /// objects will be rooted. Required because GenBank carries no
    /// namespace concept.
    #[arg(long, short = 'n', value_name = "IRI")]
    namespace: String,

    /// Target SBOL 3 RDF serialization. If omitted, inferred from
    /// `--output`'s extension.
    #[arg(long, value_enum, value_name = "FORMAT")]
    to: Option<RdfFormatArg>,

    /// Destination path. Use `-` (the default) for stdout; in that
    /// case `--to` is required.
    #[arg(long, short = 'o', default_value = "-")]
    output: String,

    /// Run SBOL 3 validation on the converted document and fold the
    /// result into the exit code: code 1 if validation finds errors.
    #[arg(long)]
    validate: bool,

    /// Exit with status 1 if any import warnings were produced.
    #[arg(long)]
    strict: bool,
}

#[derive(clap::Args)]
struct ConvertArgs {
    /// Path to an SBOL 3 document. Input format is inferred from the
    /// extension — `.ttl` (Turtle), `.rdf` (RDF/XML), `.jsonld` (JSON-LD),
    /// or `.nt` (N-Triples).
    path: PathBuf,

    /// Target serialization. If omitted, inferred from `--output`'s
    /// extension.
    #[arg(long, value_enum, value_name = "FORMAT")]
    to: Option<RdfFormatArg>,

    /// Destination path. Use `-` (the default) for stdout; in that case
    /// `--to` is required.
    #[arg(long, short = 'o', default_value = "-")]
    output: String,
}

#[derive(clap::Args)]
struct RulesListArgs {
    /// Output format.
    #[arg(long, value_enum, default_value_t = RulesFormat::Text)]
    format: RulesFormat,

    /// Only show rules with this implementation status.
    #[arg(long, value_enum, value_name = "STATUS")]
    status: Option<RuleStatusFilter>,

    /// Show full notes instead of truncating to fit one line per rule.
    #[arg(long)]
    full: bool,
}

fn main() -> ExitCode {
    let cli = Cli::parse();
    let styles = Styles::resolve(cli.color);
    match cli.command {
        Command::Validate(args) => validate(args, styles),
        Command::Convert(args) => convert(args, styles),
        Command::Upgrade(args) => upgrade(args, styles),
        Command::Downgrade(args) => downgrade(args, styles),
        Command::ImportGenbank(args) => import_genbank(args, styles),
        Command::ImportFasta(args) => import_fasta(args, styles),
        Command::Rules(command) => rules(command, styles),
        Command::Ontology(command) => ontology(command, styles),
    }
}

fn ontology(command: OntologyCommand, styles: Styles) -> ExitCode {
    let cache = OntologyCache::from_default_path();
    match command {
        OntologyCommand::Install(args) => ontology_install(&cache, args, styles),
        OntologyCommand::List => ontology_list(&cache, styles),
        OntologyCommand::Path => {
            println!("{}", cache.path().display());
            ExitCode::SUCCESS
        }
        OntologyCommand::Remove(args) => ontology_remove(&cache, args, styles),
        OntologyCommand::Verify(args) => ontology_verify(&cache, args, styles),
    }
}

fn known_ontology_by_name(name: &str) -> Option<KnownOntology> {
    match name.to_ascii_lowercase().as_str() {
        "ncit" => Some(KnownOntology::Ncit),
        _ => None,
    }
}

fn ontology_install(cache: &OntologyCache, args: OntologyInstallArgs, styles: Styles) -> ExitCode {
    let Some(known) = known_ontology_by_name(&args.name) else {
        eprintln!(
            "{}: unknown ontology `{}` — try one of: ncit",
            styles.err_label(),
            args.name
        );
        return ExitCode::from(2);
    };
    let descriptor: &OntologyDescriptor = known.descriptor();
    let result = if args.force {
        cache.install(descriptor)
    } else {
        cache.ensure_installed(descriptor)
    };
    match result {
        Ok(installed) => {
            println!(
                "{} `{}` from {}\n  fact sha256: {}",
                paint(styles.stdout, "1;32", "installed"),
                installed.name,
                installed.source_url,
                installed.fact_sha256,
            );
            ExitCode::SUCCESS
        }
        Err(error) => {
            eprintln!("{}: ontology install failed: {error}", styles.err_label());
            ExitCode::from(2)
        }
    }
}

fn ontology_list(cache: &OntologyCache, styles: Styles) -> ExitCode {
    match cache.list() {
        Ok(installed) => {
            if installed.is_empty() {
                println!("(no extensions installed)");
                return ExitCode::SUCCESS;
            }
            for entry in installed {
                println!(
                    "{name}\t{url}\tsha256={hash}\tinstalled_at={installed_at}",
                    name = entry.name,
                    url = entry.source_url,
                    hash = entry.fact_sha256,
                    installed_at = entry.installed_at,
                );
            }
            ExitCode::SUCCESS
        }
        Err(error) => {
            eprintln!("{}: cache list failed: {error}", styles.err_label());
            ExitCode::from(2)
        }
    }
}

fn ontology_remove(cache: &OntologyCache, args: OntologyRemoveArgs, styles: Styles) -> ExitCode {
    match cache.remove(&args.name) {
        Ok(true) => {
            println!(
                "{} `{}`",
                paint(styles.stdout, "1;32", "removed"),
                args.name
            );
            ExitCode::SUCCESS
        }
        Ok(false) => {
            eprintln!("{}: `{}` is not installed", styles.err_label(), args.name);
            ExitCode::from(2)
        }
        Err(error) => {
            eprintln!("{}: cache remove failed: {error}", styles.err_label());
            ExitCode::from(2)
        }
    }
}

fn ontology_verify(cache: &OntologyCache, args: OntologyVerifyArgs, styles: Styles) -> ExitCode {
    let names = match args.name {
        Some(name) => vec![name],
        None => match cache.list() {
            Ok(installed) => installed.into_iter().map(|m| m.name).collect(),
            Err(error) => {
                eprintln!("{}: cache list failed: {error}", styles.err_label());
                return ExitCode::from(2);
            }
        },
    };
    if names.is_empty() {
        println!("(no extensions installed)");
        return ExitCode::SUCCESS;
    }
    let mut had_failure = false;
    for name in names {
        match cache.verify(&name) {
            Ok(_) => println!("{}\t{name}", paint(styles.stdout, "32", "ok")),
            Err(error) => {
                eprintln!("{}\t{name}: {error}", paint(styles.stderr, "1;31", "FAIL"));
                had_failure = true;
            }
        }
    }
    if had_failure {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    }
}

fn validate(args: ValidateArgs, styles: Styles) -> ExitCode {
    let options = match build_options(&args) {
        Ok(options) => options,
        Err(message) => {
            eprintln!("{}: {message}", styles.err_label());
            return ExitCode::from(2);
        }
    };

    if args.external_mode == ExternalModeArg::Allowed && !cfg!(feature = "http-resolver") {
        eprintln!(
            "{}: --external-mode allowed requires the `http-resolver` feature \
             (rebuild sbol-cli with --features http-resolver)",
            styles.err_label()
        );
        return ExitCode::from(2);
    }
    if args.external_mode == ExternalModeArg::Allowed && args.cache_dir.is_none() {
        eprintln!(
            "{}: --external-mode allowed requires --cache-dir (so HTTP fetches stay deterministic)",
            styles.err_label()
        );
        return ExitCode::from(2);
    }

    let document = match read_document(&args.path, styles) {
        Ok(document) => document,
        Err(code) => return code,
    };

    let document_resolver = build_document_resolver(&args);
    let content_resolver = build_content_resolver(&args);
    #[cfg(feature = "http-resolver")]
    let caching_http = args
        .cache_dir
        .as_ref()
        .filter(|_| args.external_mode == ExternalModeArg::Allowed)
        .map(|dir| CachingHttpResolver::new(dir.clone()));

    let mut context =
        ValidationContext::with_options(options).with_external_mode(args.external_mode.into());
    if let Some(resolver) = &document_resolver {
        context = context.with_document_resolver(resolver);
    }
    if let Some(resolver) = &content_resolver {
        context = context.with_content_resolver(resolver);
    }
    #[cfg(feature = "http-resolver")]
    if let Some(resolver) = &caching_http {
        let doc_ref: &dyn sbol::DocumentResolver = resolver;
        let content_ref: &dyn sbol::ContentResolver = resolver;
        context = context
            .with_content_resolver(content_ref)
            .with_document_resolver(doc_ref);
    }

    let report = document.validate_with_context(context);

    if let Err(message) = render_output(&args, &report, styles) {
        eprintln!("{}: failed to write output: {message}", styles.err_label());
        return ExitCode::from(2);
    }

    let has_errors = report.has_errors();
    let has_partial = !report.coverage().partially_applied.is_empty();
    if has_errors {
        ExitCode::from(1)
    } else if args.treat_partial_as_errors && has_partial {
        ExitCode::from(3)
    } else {
        ExitCode::SUCCESS
    }
}

fn build_document_resolver(args: &ValidateArgs) -> Option<FileResolver> {
    if args.resolve_documents.is_empty() {
        return None;
    }
    let mut resolver = FileResolver::new();
    for root in &args.resolve_documents {
        resolver.add_root(root.clone());
    }
    Some(resolver)
}

fn build_content_resolver(args: &ValidateArgs) -> Option<FileResolver> {
    if args.resolve_content.is_empty() {
        return None;
    }
    let mut resolver = FileResolver::new();
    for root in &args.resolve_content {
        resolver.add_root(root.clone());
    }
    Some(resolver)
}

fn build_options(args: &ValidateArgs) -> Result<ValidationOptions, String> {
    let mut options = ValidationOptions::default();
    let mut configured: BTreeSet<&str> = BTreeSet::new();

    for rule in &args.allow {
        check_first_use(&mut configured, rule)?;
        options = options.allow(rule).map_err(|err| err.to_string())?;
    }
    for rule in &args.deny {
        check_first_use(&mut configured, rule)?;
        options = options.deny(rule).map_err(|err| err.to_string())?;
    }
    for rule in &args.warn {
        check_first_use(&mut configured, rule)?;
        options = options.warn(rule).map_err(|err| err.to_string())?;
    }

    if let Some(floor) = args.severity_floor {
        options = options.with_severity_floor(floor.into());
    }
    if let Some(ceiling) = args.severity_ceiling {
        options = options.with_severity_ceiling(ceiling.into());
    }
    if args.treat_warnings_as_errors {
        options = options.with_severity_floor(Severity::Error);
    }

    if !args.ontology.is_empty() {
        let cache = OntologyCache::from_default_path();
        for name in &args.ontology {
            let extension = cache.load(name).map_err(|error| {
                if known_ontology_by_name(name).is_some() {
                    format!(
                        "failed to load ontology extension `{name}` from {}: {error}. \
                         Install it first with `sbol ontology install {name}`.",
                        cache.path().display(),
                    )
                } else {
                    format!(
                        "unknown ontology extension `{name}` — try one of: ncit \
                         (run `sbol ontology install <name>` to install it)"
                    )
                }
            })?;
            options = options.with_ontology_extension(extension);
        }
    }
    Ok(options)
}

fn check_first_use<'a>(configured: &mut BTreeSet<&'a str>, rule: &'a str) -> Result<(), String> {
    if !configured.insert(rule) {
        return Err(format!(
            "rule `{rule}` is given more than one override on the command line"
        ));
    }
    Ok(())
}

fn render_output(args: &ValidateArgs, report: &ValidationReport, styles: Styles) -> io::Result<()> {
    let writing_to_stdout = args.output == "-";
    let payload = match args.format {
        OutputFormat::Text => {
            let color = styles.stdout && writing_to_stdout;
            format_text(args, report, color)
        }
        OutputFormat::Json => sbol::to_json(report),
        #[cfg(feature = "sarif")]
        OutputFormat::Sarif => sarif::to_sarif(report, &args.path),
    };

    if writing_to_stdout {
        let mut stdout = io::stdout().lock();
        stdout.write_all(payload.as_bytes())?;
        if !payload.ends_with('\n') {
            stdout.write_all(b"\n")?;
        }
        Ok(())
    } else {
        fs::write(&args.output, payload)
    }
}

fn format_text(args: &ValidateArgs, report: &ValidationReport, color: bool) -> String {
    let mut out = String::new();
    for issue in report.issues() {
        out.push_str(&format_issue(issue, &args.path, color));
        out.push('\n');
    }

    let errors = report.errors().count();
    let warnings = report.warnings().count();
    out.push_str(&format!(
        "{}: {errors} error{}, {warnings} warning{}",
        args.path.display(),
        plural(errors),
        plural(warnings),
    ));
    if errors == 0 && warnings == 0 {
        out.push_str(&format!(" {}", paint(color, "1;32", "— OK")));
    }
    out.push('\n');

    if args.show_coverage {
        let coverage = report.coverage();
        let line = format!(
            "coverage: {} fully applied, {} partially applied, {} not applied\n",
            coverage.fully_applied.len(),
            coverage.partially_applied.len(),
            coverage.not_applied.len(),
        );
        out.push_str(&paint(color, "2", &line));
    }

    out
}

fn format_issue(issue: &ValidationIssue, path: &Path, color: bool) -> String {
    let severity_label = match issue.severity {
        Severity::Error => "error",
        Severity::Warning => "warning",
        _ => "issue",
    };
    let severity_painted = match severity_code(issue.severity) {
        Some(code) => paint(color, code, severity_label),
        None => severity_label.to_string(),
    };
    let property = issue
        .property
        .map(|property| format!(" <{property}>"))
        .unwrap_or_default();
    format!(
        "{}: {severity_painted}[{}] [{}]{property}: {}",
        path.display(),
        issue.rule,
        issue.subject,
        issue.message,
    )
}

fn plural(n: usize) -> &'static str {
    if n == 1 { "" } else { "s" }
}

fn read_document(path: &Path, styles: Styles) -> Result<Document, ExitCode> {
    match Document::read_path(path) {
        Ok(document) => Ok(document),
        Err(ReadError::Io { source, .. }) => {
            eprintln!(
                "{}: failed to read {}: {source}",
                styles.err_label(),
                path.display()
            );
            Err(ExitCode::from(2))
        }
        Err(ReadError::UnknownFormat { extension, .. }) => {
            let ext = extension.as_deref().unwrap_or("<none>");
            eprintln!(
                "{}: unsupported extension `{ext}` for {} — supported: .ttl, .rdf, .jsonld, .nt",
                styles.err_label(),
                path.display()
            );
            Err(ExitCode::from(2))
        }
        Err(error) => {
            eprintln!(
                "{}: failed to parse {}: {error}",
                styles.err_label(),
                path.display()
            );
            Err(ExitCode::from(2))
        }
    }
}

fn read_document_with_format(
    path: &Path,
    format: RdfFormat,
    styles: Styles,
) -> Result<Document, ExitCode> {
    let input = match fs::read_to_string(path) {
        Ok(text) => text,
        Err(err) => {
            eprintln!(
                "{}: failed to read {}: {err}",
                styles.err_label(),
                path.display()
            );
            return Err(ExitCode::from(2));
        }
    };
    match Document::read(&input, format) {
        Ok(document) => Ok(document),
        Err(error) => {
            eprintln!(
                "{}: failed to parse {} as {format}: {error}",
                styles.err_label(),
                path.display()
            );
            Err(ExitCode::from(2))
        }
    }
}

fn convert(args: ConvertArgs, styles: Styles) -> ExitCode {
    let writing_to_stdout = args.output == "-";
    let target_format = match args.to {
        Some(format) => RdfFormat::from(format),
        None => {
            if writing_to_stdout {
                eprintln!(
                    "{}: --to is required when writing to stdout; \
                     pass --to <FORMAT> or --output <PATH>",
                    styles.err_label()
                );
                return ExitCode::from(2);
            }
            match RdfFormat::from_path(Path::new(&args.output)) {
                Some(format) => format,
                None => {
                    eprintln!(
                        "{}: cannot infer target format from `{}` — pass --to <FORMAT> \
                         (one of: turtle, rdfxml, jsonld, ntriples)",
                        styles.err_label(),
                        args.output
                    );
                    return ExitCode::from(2);
                }
            }
        }
    };

    let document = match read_document(&args.path, styles) {
        Ok(document) => document,
        Err(code) => return code,
    };

    let payload = match document.write(target_format) {
        Ok(payload) => payload,
        Err(WriteError::Io { source, .. }) => {
            eprintln!(
                "{}: failed to serialize as {}: {source}",
                styles.err_label(),
                target_format
            );
            return ExitCode::from(2);
        }
        Err(error) => {
            eprintln!(
                "{}: failed to serialize as {}: {error}",
                styles.err_label(),
                target_format
            );
            return ExitCode::from(2);
        }
    };

    if writing_to_stdout {
        let mut stdout = io::stdout().lock();
        if let Err(error) = stdout.write_all(payload.as_bytes()) {
            eprintln!("{}: failed to write output: {error}", styles.err_label());
            return ExitCode::from(2);
        }
        if !payload.ends_with('\n') && stdout.write_all(b"\n").is_err() {
            return ExitCode::from(2);
        }
    } else if let Err(error) = fs::write(&args.output, payload) {
        eprintln!(
            "{}: failed to write {}: {error}",
            styles.err_label(),
            args.output
        );
        return ExitCode::from(2);
    }
    ExitCode::SUCCESS
}

/// Maps a path to an RDF format, treating `.xml` as RDF/XML for SBOL
/// conversion commands. The library's strict `from_path` rejects `.xml` as
/// ambiguous, but SBOL files from SynBioHub, iGEM, and the SBOLTestSuite
/// commonly use that extension for RDF/XML.
fn infer_conversion_rdf_format(path: &Path) -> Option<RdfFormat> {
    if let Some(format) = RdfFormat::from_path(path) {
        return Some(format);
    }
    let extension = path.extension()?.to_str()?.to_ascii_lowercase();
    if extension == "xml" {
        return Some(RdfFormat::RdfXml);
    }
    None
}

fn upgrade(args: UpgradeArgs, styles: Styles) -> ExitCode {
    let writing_to_stdout = args.output == "-";
    let target_format = match args.to {
        Some(format) => RdfFormat::from(format),
        None => {
            if writing_to_stdout {
                eprintln!(
                    "{}: --to is required when writing to stdout; \
                     pass --to <FORMAT> or --output <PATH>",
                    styles.err_label()
                );
                return ExitCode::from(2);
            }
            match infer_conversion_rdf_format(Path::new(&args.output)) {
                Some(format) => format,
                None => {
                    eprintln!(
                        "{}: cannot infer target format from `{}` — pass --to <FORMAT> \
                         (one of: turtle, rdfxml, jsonld, ntriples)",
                        styles.err_label(),
                        args.output
                    );
                    return ExitCode::from(2);
                }
            }
        }
    };

    let mut options = UpgradeOptions::default();
    if let Some(ns) = args.namespace.as_deref() {
        match sbol::Iri::new(ns) {
            Ok(iri) => options.default_namespace = Some(iri),
            Err(err) => {
                eprintln!("{}: invalid --namespace `{ns}`: {err}", styles.err_label());
                return ExitCode::from(2);
            }
        }
    }

    let format = match args.from {
        Some(format) => RdfFormat::from(format),
        None => match infer_conversion_rdf_format(&args.path) {
            Some(format) => format,
            None => {
                let ext = args
                    .path
                    .extension()
                    .and_then(|ext| ext.to_str())
                    .unwrap_or("<none>");
                eprintln!(
                    "{}: unsupported extension `{ext}` for {} — pass --from <FORMAT> \
                     (one of: turtle, rdfxml, jsonld, ntriples)",
                    styles.err_label(),
                    args.path.display()
                );
                return ExitCode::from(2);
            }
        },
    };
    let input = match fs::read_to_string(&args.path) {
        Ok(text) => text,
        Err(err) => {
            eprintln!(
                "{}: failed to read {}: {err}",
                styles.err_label(),
                args.path.display()
            );
            return ExitCode::from(2);
        }
    };

    let (document, report) = match Document::upgrade_from_sbol2_with(&input, format, options) {
        Ok(pair) => pair,
        Err(err) => {
            eprintln!(
                "{}: failed to upgrade {}: {err}",
                styles.err_label(),
                args.path.display()
            );
            return ExitCode::from(2);
        }
    };

    let payload = match document.write(target_format) {
        Ok(payload) => payload,
        Err(err) => {
            eprintln!(
                "{}: failed to serialize as {target_format}: {err}",
                styles.err_label()
            );
            return ExitCode::from(2);
        }
    };

    if writing_to_stdout {
        let mut stdout = io::stdout().lock();
        if let Err(err) = stdout.write_all(payload.as_bytes()) {
            eprintln!("{}: failed to write output: {err}", styles.err_label());
            return ExitCode::from(2);
        }
        if !payload.ends_with('\n') && stdout.write_all(b"\n").is_err() {
            return ExitCode::from(2);
        }
    } else if let Err(err) = fs::write(&args.output, payload) {
        eprintln!(
            "{}: failed to write {}: {err}",
            styles.err_label(),
            args.output
        );
        return ExitCode::from(2);
    }

    emit_upgrade_report(&report, args.report, styles);

    if args.strict && !report.is_clean() {
        return ExitCode::from(1);
    }

    if args.validate {
        let validation = document.validate();
        if validation.has_errors() {
            for issue in validation.issues() {
                eprintln!("{}", format_issue(issue, &args.path, styles.stderr));
            }
            return ExitCode::from(1);
        }
    }
    ExitCode::SUCCESS
}

fn emit_upgrade_report(report: &UpgradeReport, format: UpgradeReportFormat, _styles: Styles) {
    match format {
        UpgradeReportFormat::None => {}
        UpgradeReportFormat::Text => {
            let counts = report.counts();
            eprintln!("{}", format_upgrade_counts(counts));
            for warning in report.warnings() {
                eprintln!("warning: {}", format_upgrade_warning(warning));
            }
        }
        UpgradeReportFormat::Json => {
            let payload = format_upgrade_report_json(report);
            eprintln!("{payload}");
        }
    }
}

fn format_upgrade_counts(counts: &UpgradeCounts) -> String {
    format!(
        "upgrade summary: {} CD→Component, {} MD→Component, {} SubComponent, \
         {} SequenceFeature, {} SA collapsed onto SubComponent, \
         {} MapsTo decomposed, {} Interface synthesized, \
         {} Location.hasSequence inferred",
        counts.component_definitions,
        counts.module_definitions,
        counts.sub_components,
        counts.sequence_features,
        counts.sequence_annotations_collapsed,
        counts.mapstos_decomposed,
        counts.interfaces_synthesized,
        counts.locations_with_inferred_sequence,
    )
}

fn namespace_source_label(source: &NamespaceSource) -> &'static str {
    match source {
        NamespaceSource::UrlOrigin => "derived from URL scheme+host",
        NamespaceSource::DefaultOption => "fell back to --namespace value",
        NamespaceSource::None => "no namespace assigned",
        _ => "unknown source",
    }
}

fn namespace_source_token(source: &NamespaceSource) -> &'static str {
    match source {
        NamespaceSource::UrlOrigin => "url_origin",
        NamespaceSource::DefaultOption => "default_option",
        NamespaceSource::None => "none",
        _ => "unknown",
    }
}

fn mapsto_side_token(side: &MapsToSide) -> &'static str {
    match side {
        MapsToSide::Local => "local",
        MapsToSide::Remote => "remote",
        MapsToSide::Carrier => "carrier",
        _ => "unknown",
    }
}

fn format_upgrade_warning(warning: &UpgradeWarning) -> String {
    match warning {
        UpgradeWarning::NamespaceFallback { subject, source } => format!(
            "namespace fallback for <{subject}>: {}",
            namespace_source_label(source)
        ),
        UpgradeWarning::UnresolvedMapsTo { mapsto, side } => format!(
            "unresolved MapsTo <{mapsto}>: {} side did not resolve",
            mapsto_side_token(side)
        ),
        UpgradeWarning::UnsupportedRefinement { mapsto, refinement } => {
            format!("MapsTo <{mapsto}> uses refinement <{refinement}> with no SBOL 3 equivalent")
        }
        UpgradeWarning::SequenceAnnotationWithComponent { annotation } => format!(
            "SequenceAnnotation <{annotation}> references a Component; \
             upgrade collapsed it onto the referenced SubComponent"
        ),
        UpgradeWarning::UnknownSbol2Type {
            subject,
            sbol2_type,
        } => format!("subject <{subject}> has unrecognized SBOL 2 type <{sbol2_type}>"),
        UpgradeWarning::LocationWithoutSequence {
            location,
            component,
            sequence_count,
        } => format!(
            "location <{location}> on component <{component}> has no inferable sbol3:hasSequence \
             (component owns {sequence_count} sequences — need exactly 1)"
        ),
        UpgradeWarning::IdentityCollision { canonical, sources } => format!(
            "{} distinct SBOL 2 subjects canonicalize to <{canonical}>; the SBOL 3 output \
             merges their triples into a single subject. Sources: {}",
            sources.len(),
            sources
                .iter()
                .map(|s| format!("<{s}>"))
                .collect::<Vec<_>>()
                .join(", ")
        ),
        _ => "unrecognized upgrade warning".to_string(),
    }
}

fn format_upgrade_report_json(report: &UpgradeReport) -> String {
    let counts = report.counts();
    let counts_json = json!({
        "component_definitions": counts.component_definitions,
        "module_definitions": counts.module_definitions,
        "sub_components": counts.sub_components,
        "sequence_features": counts.sequence_features,
        "sequence_annotations_collapsed": counts.sequence_annotations_collapsed,
        "mapstos_decomposed": counts.mapstos_decomposed,
        "interfaces_synthesized": counts.interfaces_synthesized,
        "locations_with_inferred_sequence": counts.locations_with_inferred_sequence,
    });
    let warnings: Vec<Value> = report
        .warnings()
        .iter()
        .map(|w| match w {
            UpgradeWarning::NamespaceFallback { subject, source } => json!({
                "kind": "namespace_fallback",
                "subject": subject,
                "source": namespace_source_token(source),
            }),
            UpgradeWarning::UnresolvedMapsTo { mapsto, side } => json!({
                "kind": "unresolved_mapsto",
                "mapsto": mapsto,
                "side": mapsto_side_token(side),
            }),
            UpgradeWarning::UnsupportedRefinement { mapsto, refinement } => json!({
                "kind": "unsupported_refinement",
                "mapsto": mapsto,
                "refinement": refinement,
            }),
            UpgradeWarning::SequenceAnnotationWithComponent { annotation } => json!({
                "kind": "sequence_annotation_with_component",
                "annotation": annotation,
            }),
            UpgradeWarning::UnknownSbol2Type {
                subject,
                sbol2_type,
            } => json!({
                "kind": "unknown_sbol2_type",
                "subject": subject,
                "sbol2_type": sbol2_type,
            }),
            UpgradeWarning::LocationWithoutSequence {
                location,
                component,
                sequence_count,
            } => json!({
                "kind": "location_without_sequence",
                "location": location,
                "component": component,
                "sequence_count": sequence_count,
            }),
            UpgradeWarning::IdentityCollision { canonical, sources } => json!({
                "kind": "identity_collision",
                "canonical": canonical,
                "sources": sources,
            }),
            _ => json!({ "kind": "unknown" }),
        })
        .collect();
    let payload = json!({ "counts": counts_json, "warnings": warnings });
    serde_json::to_string_pretty(&payload).unwrap_or_else(|_| payload.to_string())
}

fn downgrade(args: DowngradeArgs, styles: Styles) -> ExitCode {
    let writing_to_stdout = args.output == "-";
    let input_format = match args.from {
        Some(format) => RdfFormat::from(format),
        None => match infer_conversion_rdf_format(&args.path) {
            Some(format) => format,
            None => {
                let ext = args
                    .path
                    .extension()
                    .and_then(|ext| ext.to_str())
                    .unwrap_or("<none>");
                eprintln!(
                    "{}: unsupported extension `{ext}` for {} — pass --from <FORMAT> \
                     (one of: turtle, rdfxml, jsonld, ntriples)",
                    styles.err_label(),
                    args.path.display()
                );
                return ExitCode::from(2);
            }
        },
    };
    let target_format = match args.to {
        Some(format) => RdfFormat::from(format),
        None => {
            if writing_to_stdout {
                eprintln!(
                    "{}: --to is required when writing to stdout; \
                     pass --to <FORMAT> or --output <PATH>",
                    styles.err_label()
                );
                return ExitCode::from(2);
            }
            match infer_conversion_rdf_format(Path::new(&args.output)) {
                Some(format) => format,
                None => {
                    eprintln!(
                        "{}: cannot infer target format from `{}` — pass --to <FORMAT> \
                         (one of: turtle, rdfxml, jsonld, ntriples)",
                        styles.err_label(),
                        args.output
                    );
                    return ExitCode::from(2);
                }
            }
        }
    };

    let document = match read_document_with_format(&args.path, input_format, styles) {
        Ok(doc) => doc,
        Err(code) => return code,
    };

    let mut options = DowngradeOptions::default();
    options.default_version = args.default_version;
    let (sbol2_graph, report) = match document.downgrade_to_sbol2_with(options) {
        Ok(pair) => pair,
        Err(err) => {
            eprintln!("{}: downgrade failed: {err}", styles.err_label());
            return ExitCode::from(2);
        }
    };

    let payload = match sbol2_graph.write(target_format) {
        Ok(payload) => payload,
        Err(err) => {
            eprintln!(
                "{}: failed to serialize as {target_format}: {err}",
                styles.err_label()
            );
            return ExitCode::from(2);
        }
    };

    if writing_to_stdout {
        let mut stdout = io::stdout().lock();
        if let Err(err) = stdout.write_all(payload.as_bytes()) {
            eprintln!("{}: failed to write output: {err}", styles.err_label());
            return ExitCode::from(2);
        }
        if !payload.ends_with('\n') && stdout.write_all(b"\n").is_err() {
            return ExitCode::from(2);
        }
    } else if let Err(err) = fs::write(&args.output, payload) {
        eprintln!(
            "{}: failed to write {}: {err}",
            styles.err_label(),
            args.output
        );
        return ExitCode::from(2);
    }

    // Print the conversion summary to stderr — same style as upgrade.
    let counts = report.counts();
    eprintln!(
        "downgraded: {} CD, {} MD, {} split-into-both, {} SubComponent, \
         {} SequenceFeature, {} MapsTo, {} backport-restored, {} synthesized{}",
        counts.components_to_component_definition,
        counts.components_to_module_definition,
        counts.components_split_into_both,
        counts.sub_components_emitted,
        counts.sequence_features_emitted,
        counts.maps_to_reconstructed,
        counts.identities_restored_from_backport,
        counts.identities_synthesized,
        if report.warnings().is_empty() {
            String::new()
        } else {
            format!(", {} warning(s)", report.warnings().len())
        }
    );
    for warning in report.warnings() {
        eprintln!("  warning: {}", format_downgrade_warning(warning));
    }

    if args.strict && !report.is_clean() {
        return ExitCode::from(1);
    }

    if args.validate {
        // Round-trip: upgrade the produced SBOL 2 back to SBOL 3,
        // then run the SBOL 3 validator. This is the closest thing
        // we have to an SBOL 2 validator without bundling one.
        let sbol2_text = match sbol2_graph.write(RdfFormat::Turtle) {
            Ok(t) => t,
            Err(err) => {
                eprintln!(
                    "{}: round-trip serialization failed: {err}",
                    styles.err_label()
                );
                return ExitCode::from(2);
            }
        };
        match Document::upgrade_from_sbol2(&sbol2_text, RdfFormat::Turtle) {
            Ok((re_upgraded, _)) => {
                let validation = re_upgraded.validate();
                if validation.has_errors() {
                    for issue in validation.issues() {
                        eprintln!("{}", format_issue(issue, &args.path, styles.stderr));
                    }
                    return ExitCode::from(1);
                }
            }
            Err(err) => {
                eprintln!(
                    "{}: --validate round-trip failed at the re-upgrade step: {err}",
                    styles.err_label()
                );
                return ExitCode::from(1);
            }
        }
    }
    ExitCode::SUCCESS
}

fn format_downgrade_warning(warning: &DowngradeWarning) -> String {
    match warning {
        DowngradeWarning::DualRoleComponent {
            component,
            component_definition,
            module_definition,
        } => format!(
            "Component <{component}> carries both structure and function; \
             split into ComponentDefinition <{component_definition}> + \
             ModuleDefinition <{module_definition}>"
        ),
        DowngradeWarning::UnresolvableConstraintToMapsTo { constraint, reason } => {
            format!("Constraint <{constraint}> couldn't fold back into a MapsTo: {reason}")
        }
        DowngradeWarning::OrphanComponentReference {
            component_reference,
        } => format!(
            "ComponentReference <{component_reference}> had no matching Constraint — dropped"
        ),
        DowngradeWarning::UnsupportedSbol3Type {
            subject,
            sbol3_type,
        } => format!(
            "subject <{subject}> has SBOL 3 type <{sbol3_type}> with no SBOL 2 equivalent — dropped"
        ),
        DowngradeWarning::SynthesizedVersion { subject, version } => format!(
            "subject <{subject}> had no backport version; synthesized version \"{version}\""
        ),
        DowngradeWarning::IdentityCollision { canonical, sources } => format!(
            "{} distinct SBOL 3 subjects rewrite to <{canonical}>; the SBOL 2 output \
             merges their triples into a single subject. Sources: {}",
            sources.len(),
            sources
                .iter()
                .map(|s| format!("<{s}>"))
                .collect::<Vec<_>>()
                .join(", ")
        ),
        other => format!("downgrade warning: {other:?}"),
    }
}

fn import_genbank(args: ImportGenbankArgs, styles: Styles) -> ExitCode {
    let writing_to_stdout = args.output == "-";
    let target_format = match args.to {
        Some(format) => RdfFormat::from(format),
        None => {
            if writing_to_stdout {
                eprintln!(
                    "{}: --to is required when writing to stdout; \
                     pass --to <FORMAT> or --output <PATH>",
                    styles.err_label()
                );
                return ExitCode::from(2);
            }
            match RdfFormat::from_path(Path::new(&args.output)) {
                Some(format) => format,
                None => {
                    eprintln!(
                        "{}: cannot infer target format from `{}` — pass --to <FORMAT> \
                         (one of: turtle, rdfxml, jsonld, ntriples)",
                        styles.err_label(),
                        args.output
                    );
                    return ExitCode::from(2);
                }
            }
        }
    };

    let importer = match sbol_genbank::GenbankImporter::new(&args.namespace) {
        Ok(importer) => importer,
        Err(err) => {
            eprintln!(
                "{}: invalid --namespace `{}`: {err}",
                styles.err_label(),
                args.namespace
            );
            return ExitCode::from(2);
        }
    };

    let (document, report) = match importer.read_path(&args.path) {
        Ok(pair) => pair,
        Err(err) => {
            eprintln!(
                "{}: failed to import {}: {err}",
                styles.err_label(),
                args.path.display()
            );
            return ExitCode::from(2);
        }
    };

    let payload = match document.write(target_format) {
        Ok(payload) => payload,
        Err(err) => {
            eprintln!(
                "{}: failed to serialize as {target_format}: {err}",
                styles.err_label()
            );
            return ExitCode::from(2);
        }
    };

    if writing_to_stdout {
        let mut stdout = io::stdout().lock();
        if let Err(err) = stdout.write_all(payload.as_bytes()) {
            eprintln!("{}: failed to write output: {err}", styles.err_label());
            return ExitCode::from(2);
        }
        if !payload.ends_with('\n') && stdout.write_all(b"\n").is_err() {
            return ExitCode::from(2);
        }
    } else if let Err(err) = fs::write(&args.output, payload) {
        eprintln!(
            "{}: failed to write {}: {err}",
            styles.err_label(),
            args.output
        );
        return ExitCode::from(2);
    }

    // Always print the import summary to stderr — it's the user's
    // signal that the conversion actually picked up the right number of
    // Components, Sequences, and Features. Mirrors the `sbol upgrade`
    // summary line.
    eprintln!(
        "imported: {} Component(s), {} Sequence(s), {} SequenceFeature(s){}",
        report.components,
        report.sequences,
        report.features,
        if report.warnings.is_empty() {
            String::new()
        } else {
            format!(", {} warning(s)", report.warnings.len())
        }
    );
    for warning in &report.warnings {
        eprintln!("  warning: {}", format_import_warning(warning));
    }

    if args.strict && !report.is_clean() {
        return ExitCode::from(1);
    }

    if args.validate {
        let validation = document.validate();
        if validation.has_errors() {
            for issue in validation.issues() {
                eprintln!("{}", format_issue(issue, &args.path, styles.stderr));
            }
            return ExitCode::from(1);
        }
    }
    ExitCode::SUCCESS
}

fn import_fasta(args: ImportFastaArgs, styles: Styles) -> ExitCode {
    let writing_to_stdout = args.output == "-";
    let target_format = match args.to {
        Some(format) => RdfFormat::from(format),
        None => {
            if writing_to_stdout {
                eprintln!(
                    "{}: --to is required when writing to stdout; \
                     pass --to <FORMAT> or --output <PATH>",
                    styles.err_label()
                );
                return ExitCode::from(2);
            }
            match RdfFormat::from_path(Path::new(&args.output)) {
                Some(format) => format,
                None => {
                    eprintln!(
                        "{}: cannot infer target format from `{}` — pass --to <FORMAT> \
                         (one of: turtle, rdfxml, jsonld, ntriples)",
                        styles.err_label(),
                        args.output
                    );
                    return ExitCode::from(2);
                }
            }
        }
    };

    let mut importer = match sbol_fasta::FastaImporter::new(&args.namespace) {
        Ok(importer) => importer,
        Err(err) => {
            eprintln!(
                "{}: invalid --namespace `{}`: {err}",
                styles.err_label(),
                args.namespace
            );
            return ExitCode::from(2);
        }
    };
    if let Some(alphabet) = args.alphabet {
        importer = importer.with_alphabet(alphabet.into());
    }

    let (document, report) = match importer.read_path(&args.path) {
        Ok(pair) => pair,
        Err(err) => {
            eprintln!(
                "{}: failed to import {}: {err}",
                styles.err_label(),
                args.path.display()
            );
            return ExitCode::from(2);
        }
    };

    let payload = match document.write(target_format) {
        Ok(payload) => payload,
        Err(err) => {
            eprintln!(
                "{}: failed to serialize as {target_format}: {err}",
                styles.err_label()
            );
            return ExitCode::from(2);
        }
    };

    if writing_to_stdout {
        let mut stdout = io::stdout().lock();
        if let Err(err) = stdout.write_all(payload.as_bytes()) {
            eprintln!("{}: failed to write output: {err}", styles.err_label());
            return ExitCode::from(2);
        }
        if !payload.ends_with('\n') && stdout.write_all(b"\n").is_err() {
            return ExitCode::from(2);
        }
    } else if let Err(err) = fs::write(&args.output, payload) {
        eprintln!(
            "{}: failed to write {}: {err}",
            styles.err_label(),
            args.output
        );
        return ExitCode::from(2);
    }

    eprintln!(
        "imported: {} Component(s), {} Sequence(s) ({} DNA, {} RNA, {} protein){}",
        report.components,
        report.sequences,
        report.dna_records,
        report.rna_records,
        report.protein_records,
        if report.warnings.is_empty() {
            String::new()
        } else {
            format!(", {} warning(s)", report.warnings.len())
        }
    );
    for warning in &report.warnings {
        eprintln!("  warning: {}", format_fasta_import_warning(warning));
    }

    if args.strict && !report.is_clean() {
        return ExitCode::from(1);
    }

    if args.validate {
        let validation = document.validate();
        if validation.has_errors() {
            for issue in validation.issues() {
                eprintln!("{}", format_issue(issue, &args.path, styles.stderr));
            }
            return ExitCode::from(1);
        }
    }
    ExitCode::SUCCESS
}

fn format_fasta_import_warning(warning: &sbol_fasta::ImportWarning) -> String {
    match warning {
        sbol_fasta::ImportWarning::EmptyRecord { record_id } => {
            format!("record `{record_id}` has no sequence body")
        }
        _ => "unrecognized fasta import warning".to_string(),
    }
}

fn format_import_warning(warning: &sbol_genbank::ImportWarning) -> String {
    match warning {
        sbol_genbank::ImportWarning::UnknownFeatureKey { kind } => {
            format!("unrecognized GenBank feature key `{kind}` — fell back to SO:0000110")
        }
        sbol_genbank::ImportWarning::LossyLocation { feature, reason } => {
            format!("feature `{feature}`: lossy location — {reason}")
        }
        sbol_genbank::ImportWarning::SynthesizedIdentifier => {
            "GenBank record had no ACCESSION or LOCUS name; synthesized `imported_record`"
                .to_string()
        }
        _ => "unrecognized import warning".to_string(),
    }
}

fn rules(command: RulesCommand, styles: Styles) -> ExitCode {
    match command {
        RulesCommand::List(args) => rules_list(args, styles),
    }
}

fn rules_list(args: RulesListArgs, styles: Styles) -> ExitCode {
    let statuses: Vec<&ValidationRuleStatus> = validation_rule_statuses()
        .iter()
        .filter(|status| status_matches_filter(status.status, args.status))
        .collect();

    match args.format {
        RulesFormat::Text => {
            print!("{}", format_rules_text(&statuses, styles.stdout, args.full));
        }
        RulesFormat::Json => {
            let payload = format_rules_json(&statuses);
            println!("{payload}");
        }
    }
    ExitCode::SUCCESS
}

fn status_matches_filter(status: RuleStatus, filter: Option<RuleStatusFilter>) -> bool {
    let Some(filter) = filter else {
        return true;
    };
    matches!(
        (filter, status),
        (RuleStatusFilter::Error, RuleStatus::Error)
            | (RuleStatusFilter::Warning, RuleStatus::Warning)
            | (RuleStatusFilter::Configurable, RuleStatus::Configurable)
            | (
                RuleStatusFilter::MachineUncheckable,
                RuleStatus::MachineUncheckable,
            )
            | (RuleStatusFilter::Unimplemented, RuleStatus::Unimplemented)
    )
}

const FALLBACK_TERMINAL_COLS: usize = 100;
const COLUMN_SEPARATOR_WIDTH: usize = 2;
const MIN_NOTE_WIDTH: usize = 10;

fn format_rules_text(statuses: &[&ValidationRuleStatus], color: bool, full: bool) -> String {
    if statuses.is_empty() {
        return String::from("(no rules match)\n");
    }

    let rule_w = column_width("rule", statuses.iter().map(|s| s.rule));
    let status_w = column_width(
        "status",
        statuses.iter().map(|s| rule_status_label(s.status)),
    );
    let normative_w = column_width(
        "normative",
        statuses
            .iter()
            .map(|s| normative_severity_label(s.normative_severity)),
    );
    let section_w = column_width("section", statuses.iter().map(|s| s.spec_section));
    let blocker_w = column_width(
        "blocker",
        statuses
            .iter()
            .map(|s| s.blocker.map(blocker_label).unwrap_or("-")),
    );

    let note_truncate = if full {
        None
    } else {
        let fixed =
            rule_w + status_w + normative_w + section_w + blocker_w + COLUMN_SEPARATOR_WIDTH * 5;
        let total = detect_terminal_cols();
        let remaining = total.saturating_sub(fixed);
        Some(remaining.max(MIN_NOTE_WIDTH))
    };

    let mut out = String::new();
    let header = format!(
        "{rule:<rule_w$}  {status:<status_w$}  {normative:<normative_w$}  {section:<section_w$}  {blocker:<blocker_w$}  {note}\n",
        rule = "rule",
        status = "status",
        normative = "normative",
        section = "section",
        blocker = "blocker",
        note = "note",
    );
    out.push_str(&paint(color, "1", &header));

    let mut counts = StatusCounts::default();
    for status in statuses {
        counts.tally(status.status);
        let status_label = rule_status_label(status.status);
        let status_col = paint_padded(
            status_label,
            status_w,
            rule_status_code(status.status).filter(|_| color),
        );
        let blocker = status.blocker.map(blocker_label).unwrap_or("-");
        let note = match note_truncate {
            Some(max) => truncate(status.note, max),
            None => status.note.to_string(),
        };
        out.push_str(&format!(
            "{rule:<rule_w$}  {status_col}  {normative:<normative_w$}  {section:<section_w$}  {blocker:<blocker_w$}  {note}\n",
            rule = status.rule,
            normative = normative_severity_label(status.normative_severity),
            section = status.spec_section,
        ));
    }

    let summary = format!("\n{} rules{}\n", statuses.len(), counts.summary());
    out.push_str(&paint(color, "2", &summary));
    out
}

fn detect_terminal_cols() -> usize {
    if let Some((width, _)) = terminal_size::terminal_size() {
        return width.0 as usize;
    }
    if let Some(cols) = env::var("COLUMNS").ok().and_then(|s| s.parse().ok()) {
        return cols;
    }
    FALLBACK_TERMINAL_COLS
}

#[derive(Default)]
struct StatusCounts {
    error: usize,
    warning: usize,
    configurable: usize,
    machine_uncheckable: usize,
    unimplemented: usize,
}

impl StatusCounts {
    fn tally(&mut self, status: RuleStatus) {
        match status {
            RuleStatus::Error => self.error += 1,
            RuleStatus::Warning => self.warning += 1,
            RuleStatus::Configurable => self.configurable += 1,
            RuleStatus::MachineUncheckable => self.machine_uncheckable += 1,
            RuleStatus::Unimplemented => self.unimplemented += 1,
            _ => {}
        }
    }

    fn summary(&self) -> String {
        let parts: Vec<String> = [
            ("Error", self.error),
            ("Warning", self.warning),
            ("Configurable", self.configurable),
            ("MachineUncheckable", self.machine_uncheckable),
            ("Unimplemented", self.unimplemented),
        ]
        .into_iter()
        .filter(|(_, n)| *n > 0)
        .map(|(label, n)| format!("{n} {label}"))
        .collect();
        if parts.is_empty() {
            String::new()
        } else {
            format!("{}", parts.join(", "))
        }
    }
}

fn column_width<'a>(header: &str, values: impl Iterator<Item = &'a str>) -> usize {
    let mut width = header.chars().count();
    for value in values {
        let n = value.chars().count();
        if n > width {
            width = n;
        }
    }
    width
}

fn paint_padded(label: &str, width: usize, code: Option<&str>) -> String {
    let pad = width.saturating_sub(label.chars().count());
    let painted = match code {
        Some(code) => paint(true, code, label),
        None => label.to_string(),
    };
    format!("{painted}{}", " ".repeat(pad))
}

fn truncate(text: &str, max_chars: usize) -> String {
    let count = text.chars().count();
    if count <= max_chars {
        text.to_string()
    } else {
        let mut out: String = text.chars().take(max_chars.saturating_sub(1)).collect();
        out.push('');
        out
    }
}

fn format_rules_json(statuses: &[&ValidationRuleStatus]) -> String {
    let entries: Vec<Value> = statuses
        .iter()
        .map(|status| {
            json!({
                "rule": status.rule,
                "status": rule_status_label(status.status),
                "normative_severity": normative_severity_label(status.normative_severity),
                "spec_section": status.spec_section,
                "blocker": status.blocker.map(blocker_label),
                "note": status.note,
                "validator_function": status.validator_function,
            })
        })
        .collect();
    serde_json::to_string(&Value::Array(entries)).expect("rule-catalog JSON is always serializable")
}

fn rule_status_label(status: RuleStatus) -> &'static str {
    match status {
        RuleStatus::Error => "Error",
        RuleStatus::Warning => "Warning",
        RuleStatus::Configurable => "Configurable",
        RuleStatus::MachineUncheckable => "MachineUncheckable",
        RuleStatus::Unimplemented => "Unimplemented",
        _ => "Unknown",
    }
}

fn normative_severity_label(severity: NormativeSeverity) -> &'static str {
    match severity {
        NormativeSeverity::Must => "MUST",
        NormativeSeverity::Should => "SHOULD",
        NormativeSeverity::May => "MAY",
        _ => "UNKNOWN",
    }
}

fn blocker_label(blocker: Blocker) -> &'static str {
    match blocker {
        Blocker::Ontology => "Ontology",
        Blocker::Resolver => "Resolver",
        Blocker::StrictDatatype => "StrictDatatype",
        Blocker::Policy => "Policy",
        Blocker::External => "External",
        _ => "Unknown",
    }
}