acorde-cli 1.2.11

Command-line score format converter built on acorde
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
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
use acorde_core::{
    Command, FingeringSelectionPolicy, PlaybackOptions, Score, ScoreEngine, SetTabPositionCmd,
    TabPosition,
};
use acorde_io::{Diagnostic, DiagnosticSeverity, ImportReport};
use clap::{Parser, Subcommand, ValueEnum};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

const MAX_PLAYBACK_JSON_BYTES: usize = 64 * 1024 * 1024;
const RENDER_REPORT_SCHEMA_VERSION: u32 = 1;
const PRINT_REPORT_SCHEMA_VERSION: u32 = 1;

#[derive(Clone, Copy, Debug, ValueEnum)]
enum PrintPresetArg {
    /// A4 full score.
    A4Score,
    /// US Letter full score.
    LetterScore,
    /// A4 extracted part; combine with --part.
    A4Part,
    /// US Letter extracted part; combine with --part.
    LetterPart,
}

#[derive(Clone, Copy, Debug, ValueEnum)]
enum PrintFinalPagePolicyArg {
    /// Keep the configured page capacity.
    AllowSingleSystem,
    /// Redistribute automatic systems across pages.
    Balance,
}

#[derive(Clone, Copy, Debug, ValueEnum)]
enum PrintNotationBreakPolicyArg {
    /// Preserve ordinary automatic breaks.
    Preserve,
    /// Keep volta endings together when they fit.
    KeepVoltaTogether,
    /// Keep repeat sections together on one page when they fit.
    KeepRepeatsTogether,
}

#[derive(Clone, Copy, Debug, ValueEnum)]
enum PrintPickupPolicyArg {
    /// Use the default automatic pickup detection.
    Auto,
    /// Do not infer a pickup measure.
    Preserve,
    /// Detect and isolate a partial first measure.
    DetectFirstMeasure,
}

struct PrintReportOptions<'a> {
    preset: PrintPresetArg,
    part: Option<usize>,
    measures_per_system: usize,
    systems_per_page: Option<usize>,
    title_page: bool,
    running_title: Option<&'a str>,
    header_text: Option<&'a str>,
    footer_text: Option<&'a str>,
    page_number_in_footer: bool,
    show_part_names: bool,
    fail_on_issues: bool,
    scale: f32,
    first_system_measures: Option<usize>,
    final_page_policy: PrintFinalPagePolicyArg,
    notation_break_policy: PrintNotationBreakPolicyArg,
    pickup_policy: PrintPickupPolicyArg,
}

#[derive(Debug, Serialize)]
struct PrintReportSummary {
    print_report_schema_version: u32,
    import_report_schema_version: u32,
    score_schema_version: u32,
    input_format: String,
    input_path: String,
    import_warning_count: usize,
    import_error_count: usize,
    import_loss_count: usize,
    import_diagnostics: Vec<acorde_io::Diagnostic>,
    renderer_issues: Vec<acorde_render_svg::RenderPreflightIssue>,
    layout: acorde_layout::PrintLayoutResult,
}

#[derive(Parser)]
#[command(
    name = "score",
    about = "Music score format conversion and inspection tool"
)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Convert a score file between formats
    Convert {
        /// Input file (.musicxml, .mxl, .mid, .midi, .abc, .mei, .mscz, .mscx, .gp, .gpx, .gp3, .gp4, .gp5)
        input: PathBuf,
        /// Output file (.musicxml, .mid, .midi, .abc, .mei)
        output: PathBuf,
    },
    /// Render a score file to deterministic SVG
    Render {
        /// Input file (.musicxml, .mxl, .mid, .midi, .abc, .mei, .mscz, .mscx, .gp, .gpx, .gp3, .gp4, .gp5)
        input: PathBuf,
        /// Output SVG file
        output: PathBuf,
        /// SVG width in pixels
        #[arg(long, default_value_t = 900.0)]
        width: f32,
        /// Distance between adjacent staff lines in pixels
        #[arg(long, default_value_t = 24.0)]
        staff_size: f32,
        /// Measures per rendered system
        #[arg(long, default_value_t = 4)]
        measures_per_system: usize,
        /// Omit data-* note and score address hooks
        #[arg(long)]
        no_interactive: bool,
    },
    /// Render a score file to SVG and print import/renderer diagnostics as JSON
    RenderReport {
        /// Input file (.musicxml, .mxl, .mid, .midi, .abc, .mei, .mscz, .mscx, .gp, .gpx, .gp3, .gp4, .gp5)
        input: PathBuf,
        /// Output SVG file
        output: PathBuf,
        /// SVG width in pixels
        #[arg(long, default_value_t = 900.0)]
        width: f32,
        /// Distance between adjacent staff lines in pixels
        #[arg(long, default_value_t = 24.0)]
        staff_size: f32,
        /// Measures per rendered system
        #[arg(long, default_value_t = 4)]
        measures_per_system: usize,
        /// Omit data-* note and score address hooks
        #[arg(long)]
        no_interactive: bool,
        /// Exit with status 1 when import or renderer issues are present
        #[arg(long)]
        fail_on_issues: bool,
    },
    /// Print deterministic page/system layout and publication metadata as JSON
    PrintReport {
        /// Input score file
        input: PathBuf,
        /// Reproducible page preset
        #[arg(long, value_enum, default_value_t = PrintPresetArg::A4Score)]
        preset: PrintPresetArg,
        /// Zero-based part index for an extracted-part preset
        #[arg(long)]
        part: Option<usize>,
        /// Physical measures per printed system
        #[arg(long, default_value_t = 4)]
        measures_per_system: usize,
        /// Optional systems per page override
        #[arg(long)]
        systems_per_page: Option<usize>,
        /// Add a metadata-only title page
        #[arg(long)]
        title_page: bool,
        /// Running title for non-title pages
        #[arg(long)]
        running_title: Option<String>,
        /// Logical page header text
        #[arg(long)]
        header_text: Option<String>,
        /// Logical page footer text
        #[arg(long)]
        footer_text: Option<String>,
        /// Add the logical page number to the footer blocks
        #[arg(long)]
        page_number_in_footer: bool,
        /// Omit part-name publication blocks
        #[arg(long)]
        no_part_names: bool,
        /// Exit with status 1 when import diagnostics are present
        #[arg(long)]
        fail_on_issues: bool,
        /// Content scale applied to system geometry
        #[arg(long, default_value_t = 1.0)]
        scale: f32,
        /// Optional first-system physical measure capacity
        #[arg(long)]
        first_system_measures: Option<usize>,
        /// Final-page distribution policy
        #[arg(long, value_enum, default_value_t = PrintFinalPagePolicyArg::AllowSingleSystem)]
        final_page_policy: PrintFinalPagePolicyArg,
        /// Notation-aware system/page break policy
        #[arg(long, value_enum, default_value_t = PrintNotationBreakPolicyArg::Preserve)]
        notation_break_policy: PrintNotationBreakPolicyArg,
        /// Pickup-measure detection policy
        #[arg(long, value_enum, default_value_t = PrintPickupPolicyArg::Auto)]
        pickup_policy: PrintPickupPolicyArg,
    },
    /// Print title, parts, measure count, and duration estimate
    Info {
        /// Input file (.musicxml, .mxl, .mid, .midi)
        input: PathBuf,
    },
    /// Validate structural integrity; exits 1 if errors are found
    Validate {
        /// Input file (.musicxml, .mxl, .mid, .midi)
        input: PathBuf,
    },
    /// Print a structured import report as JSON
    Report {
        /// Input file (.musicxml, .mxl, .mid, .abc, .mscz, .mscx, .mei)
        input: PathBuf,
    },
    /// Print renderer capability preflight issues as JSON
    Preflight {
        /// Input score file
        input: PathBuf,
        /// Exit with status 1 when any renderer capability issue is found
        #[arg(long)]
        fail_on_issues: bool,
    },
    /// Analyze chords, melodic intervals, and key candidates as JSON
    Analyze {
        /// Input file (.musicxml, .mxl, .mid, .midi, .abc, .mei, .mscz, .mscx, .gp, .gpx, .gp3, .gp4, .gp5)
        input: PathBuf,
    },
    /// Run a local analysis benchmark manifest and print its JSON report
    Benchmark {
        /// Manifest JSON containing benchmark cases and expected category counts
        manifest: PathBuf,
        /// Exit with status 1 when any benchmark case has a category mismatch
        #[arg(long)]
        fail_on_mismatch: bool,
        /// Expected corpus fingerprint; exits 1 when manifest or fixture bytes drift
        #[arg(long)]
        expected_fingerprint: Option<String>,
    },
    /// Extract a single part from a score
    Extract {
        /// Input file (.musicxml, .mxl, .mid, .midi)
        input: PathBuf,
        /// Output file (.musicxml, .mid, .midi)
        output: PathBuf,
        /// Zero-based part index to extract
        #[arg(short, long)]
        part: usize,
    },
    /// Transpose every pitched note and key signature by semitones
    Transpose {
        /// Input file (.musicxml, .mxl, .mid, .midi, .abc, .mei, .mscz, .mscx, .gp, .gpx, .gp3, .gp4, .gp5)
        input: PathBuf,
        /// Output file (.musicxml, .mid, .midi)
        output: PathBuf,
        /// Semitones to shift (negative values transpose down)
        #[arg(short, long)]
        semitones: i8,
    },
    /// Parse, structurally validate, and rewrite a score in canonical output form
    Normalize {
        /// Input score file
        input: PathBuf,
        /// Canonical output file (.musicxml, .mid, .midi)
        output: PathBuf,
    },
    /// Set or clear one note's tablature string/fret position
    TabPosition {
        /// Input score file
        input: PathBuf,
        /// Output score file
        output: PathBuf,
        /// Zero-based part index
        #[arg(long)]
        part: usize,
        /// Zero-based staff index
        #[arg(long, default_value_t = 0)]
        staff: usize,
        /// Zero-based measure index
        #[arg(long)]
        measure: usize,
        /// Zero-based voice index
        #[arg(long, default_value_t = 0)]
        voice: usize,
        /// Zero-based note index in the voice
        #[arg(long)]
        note: usize,
        /// One-based string number
        #[arg(long, conflicts_with = "clear")]
        string: Option<u8>,
        /// Fret number (0 = open string)
        #[arg(long, conflicts_with = "clear")]
        fret: Option<u8>,
        /// Clear the explicit tablature position
        #[arg(long, conflicts_with_all = ["string", "fret"])]
        clear: bool,
    },
    /// Assign and optimize tablature positions for a score
    AutoTab {
        /// Input score file
        input: PathBuf,
        /// Output score file
        output: PathBuf,
    },
    /// Assign tablature positions and print a deterministic JSON result report
    AutoTabReport {
        /// Input score file
        input: PathBuf,
        /// Output score file
        output: PathBuf,
    },
    /// Project authored tablature positions onto the deterministic playback schedule
    TabPerformanceReport {
        /// Input score file
        input: PathBuf,
        /// Override the score tempo for the projected event timestamps
        #[arg(long)]
        bpm: Option<u16>,
        /// Exit with status 1 when any tablature projection diagnostic is found
        #[arg(long)]
        fail_on_diagnostics: bool,
    },
    /// Print the deterministic playback event schedule as JSON
    PlaybackReport {
        /// Input score file
        input: PathBuf,
        /// Override the score tempo for event timestamps
        #[arg(long)]
        bpm: Option<u16>,
        /// Inclusive zero-based physical measure at which the report starts
        #[arg(long, requires = "loop_end")]
        loop_start: Option<usize>,
        /// Inclusive zero-based physical measure at which the report ends
        #[arg(long, requires = "loop_start")]
        loop_end: Option<usize>,
    },
    /// Compare expected and host-observed playback event JSON files
    PlaybackCompare {
        /// JSON file produced by `playback-report`
        expected: PathBuf,
        /// JSON file produced by a browser or Composer host
        actual: PathBuf,
        /// Maximum permitted absolute start-time error in seconds
        #[arg(long, default_value_t = 0.005)]
        start_tolerance: f64,
        /// Maximum permitted absolute duration error in seconds
        #[arg(long, default_value_t = 0.005)]
        duration_tolerance: f64,
        /// Exit with status 1 when any mismatch is found
        #[arg(long)]
        fail_on_mismatch: bool,
    },
    /// Report a deterministic selection from alternate fingering candidates
    FingeringReport {
        /// Input score file
        input: PathBuf,
        /// Selection policy: source-order, lowest, or highest
        #[arg(long, default_value = "source-order")]
        policy: String,
    },
    /// Export a score and print machine-readable conversion diagnostics
    ExportReport {
        /// Input score file
        input: PathBuf,
        /// Output file (.musicxml, .mid, .midi)
        output: PathBuf,
    },
    /// Compare two score files and print a deterministic semantic compatibility report
    CompatibilityReport {
        /// Source score file
        source: PathBuf,
        /// Candidate score file after conversion
        candidate: PathBuf,
        /// Exit with status 1 when the semantic diff is non-empty
        #[arg(long)]
        fail_on_differences: bool,
        /// Exit with status 1 when either file reports an information-loss diagnostic
        #[arg(long)]
        fail_on_loss: bool,
    },
}

fn main() {
    let cli = Cli::parse();
    let result = match &cli.command {
        Commands::Convert { input, output } => cmd_convert(input, output),
        Commands::Render {
            input,
            output,
            width,
            staff_size,
            measures_per_system,
            no_interactive,
        } => cmd_render(
            input,
            output,
            *width,
            *staff_size,
            *measures_per_system,
            !*no_interactive,
        ),
        Commands::RenderReport {
            input,
            output,
            width,
            staff_size,
            measures_per_system,
            no_interactive,
            fail_on_issues,
        } => cmd_render_report(
            input,
            output,
            *width,
            *staff_size,
            *measures_per_system,
            !*no_interactive,
            *fail_on_issues,
        ),
        Commands::PrintReport {
            input,
            preset,
            part,
            measures_per_system,
            systems_per_page,
            title_page,
            running_title,
            header_text,
            footer_text,
            page_number_in_footer,
            no_part_names,
            fail_on_issues,
            scale,
            first_system_measures,
            final_page_policy,
            notation_break_policy,
            pickup_policy,
        } => cmd_print_report(
            input,
            PrintReportOptions {
                preset: *preset,
                part: *part,
                measures_per_system: *measures_per_system,
                systems_per_page: *systems_per_page,
                title_page: *title_page,
                running_title: running_title.as_deref(),
                header_text: header_text.as_deref(),
                footer_text: footer_text.as_deref(),
                page_number_in_footer: *page_number_in_footer,
                show_part_names: !*no_part_names,
                fail_on_issues: *fail_on_issues,
                scale: *scale,
                first_system_measures: *first_system_measures,
                final_page_policy: *final_page_policy,
                notation_break_policy: *notation_break_policy,
                pickup_policy: *pickup_policy,
            },
        ),
        Commands::Info { input } => cmd_info(input),
        Commands::Validate { input } => cmd_validate(input),
        Commands::Report { input } => cmd_report(input),
        Commands::Preflight {
            input,
            fail_on_issues,
        } => cmd_preflight(input, *fail_on_issues),
        Commands::Analyze { input } => cmd_analyze(input),
        Commands::Benchmark {
            manifest,
            fail_on_mismatch,
            expected_fingerprint,
        } => cmd_benchmark(manifest, *fail_on_mismatch, expected_fingerprint.as_deref()),
        Commands::Extract {
            input,
            output,
            part,
        } => cmd_extract(input, output, *part),
        Commands::Transpose {
            input,
            output,
            semitones,
        } => cmd_transpose(input, output, *semitones),
        Commands::Normalize { input, output } => cmd_normalize(input, output),
        Commands::TabPosition {
            input,
            output,
            part,
            staff,
            measure,
            voice,
            note,
            string,
            fret,
            clear,
        } => cmd_tab_position(
            input, output, *part, *staff, *measure, *voice, *note, *string, *fret, *clear,
        ),
        Commands::AutoTab { input, output } => cmd_auto_tab(input, output),
        Commands::AutoTabReport { input, output } => cmd_auto_tab_report(input, output),
        Commands::TabPerformanceReport {
            input,
            bpm,
            fail_on_diagnostics,
        } => cmd_tab_performance_report(input, *bpm, *fail_on_diagnostics),
        Commands::PlaybackReport {
            input,
            bpm,
            loop_start,
            loop_end,
        } => cmd_playback_report(input, *bpm, *loop_start, *loop_end),
        Commands::PlaybackCompare {
            expected,
            actual,
            start_tolerance,
            duration_tolerance,
            fail_on_mismatch,
        } => cmd_playback_compare(
            expected,
            actual,
            *start_tolerance,
            *duration_tolerance,
            *fail_on_mismatch,
        ),
        Commands::FingeringReport { input, policy } => cmd_fingering_report(input, policy),
        Commands::ExportReport { input, output } => cmd_export_report(input, output),
        Commands::CompatibilityReport {
            source,
            candidate,
            fail_on_differences,
            fail_on_loss,
        } => cmd_compatibility_report(source, candidate, *fail_on_differences, *fail_on_loss),
    };
    if let Err(e) = result {
        eprintln!("error: {e}");
        std::process::exit(1);
    }
}

// ── parse ─────────────────────────────────────────────────────────────────────

fn parse_score(path: &Path) -> Result<Score, String> {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_ascii_lowercase();
    let data = std::fs::read(path).map_err(|e| format!("cannot read '{}': {e}", path.display()))?;

    match ext.as_str() {
        "xml" | "musicxml" => {
            let xml = acorde_io::decode_xml_text(&data)
                .map_err(|e| format!("cannot decode '{}': {e}", path.display()))?;
            acorde_io::parse_musicxml(&xml).map_err(|e| e.to_string())
        }
        "mxl" => acorde_io::parse_mxl(&data).map_err(|e| e.to_string()),
        "gp" | "gpx" | "gp3" | "gp4" | "gp5" => {
            acorde_io::parse_gp(&data).map_err(|e| e.to_string())
        }
        "mid" | "midi" => acorde_io::parse_midi(&data).map_err(|e| e.to_string()),
        "abc" => {
            let text = acorde_io::decode_xml_text(&data)
                .map_err(|e| format!("cannot decode '{}': {e}", path.display()))?;
            acorde_io::parse_abc(&text).map_err(|e| e.to_string())
        }
        "mei" => {
            let text = acorde_io::decode_xml_text(&data)
                .map_err(|e| format!("cannot decode '{}': {e}", path.display()))?;
            acorde_io::parse_mei(&text).map_err(|e| e.to_string())
        }
        "mscz" => acorde_io::parse_mscz(&data).map_err(|e| e.to_string()),
        "mscx" => {
            let xml = acorde_io::decode_xml_text(&data)
                .map_err(|e| format!("cannot decode '{}': {e}", path.display()))?;
            acorde_io::parse_mscx(&xml).map_err(|e| e.to_string())
        }
        other => Err(format!("unsupported input format: '.{other}'")),
    }
}

fn parse_report(path: &Path) -> Result<ImportReport, String> {
    let ext = path
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_ascii_lowercase();
    let data = std::fs::read(path).map_err(|e| format!("cannot read '{}': {e}", path.display()))?;
    match ext.as_str() {
        "xml" | "musicxml" => {
            let text = acorde_io::decode_xml_text(&data).map_err(|e| e.to_string())?;
            acorde_io::parse_musicxml_with_report(&text).map_err(|e| e.to_string())
        }
        "mxl" => acorde_io::parse_mxl_with_report(&data).map_err(|e| e.to_string()),
        "gp" | "gpx" | "gp3" | "gp4" | "gp5" => {
            acorde_io::parse_gp_with_report(&data).map_err(|e| e.to_string())
        }
        "mid" | "midi" => acorde_io::parse_midi_with_report(&data).map_err(|e| e.to_string()),
        "abc" => {
            let text = acorde_io::decode_xml_text(&data).map_err(|e| e.to_string())?;
            acorde_io::parse_abc_with_report(&text).map_err(|e| e.to_string())
        }
        "mei" => {
            let text = acorde_io::decode_xml_text(&data).map_err(|e| e.to_string())?;
            acorde_io::parse_mei_with_report(&text).map_err(|e| e.to_string())
        }
        "mscz" => acorde_io::parse_mscz_with_report(&data).map_err(|e| e.to_string()),
        "mscx" => {
            let text = acorde_io::decode_xml_text(&data).map_err(|e| e.to_string())?;
            acorde_io::parse_mscx_with_report(&text).map_err(|e| e.to_string())
        }
        other => Err(format!("unsupported input format: '.{other}'")),
    }
}

fn cmd_report(input: &Path) -> Result<(), String> {
    let report = parse_report(input)?;
    let json = serde_json::to_string_pretty(&report)
        .map_err(|e| format!("report serialization failed: {e}"))?;
    println!("{json}");
    Ok(())
}

fn cmd_preflight(input: &Path, fail_on_issues: bool) -> Result<(), String> {
    let score = parse_score(input)?;
    let issues = acorde_render_svg::render_preflight(&score);
    serde_json::to_writer_pretty(std::io::stdout(), &issues)
        .map_err(|e| format!("preflight serialization failed: {e}"))?;
    println!();
    if fail_on_issues && !issues.is_empty() {
        return Err(format!(
            "renderer preflight found {} issue(s)",
            issues.len()
        ));
    }
    Ok(())
}

fn cmd_render(
    input: &Path,
    output: &Path,
    width: f32,
    staff_size: f32,
    measures_per_system: usize,
    interactive: bool,
) -> Result<(), String> {
    let score = parse_score(input)?;
    let options = acorde_render_svg::SvgRenderOptions {
        width,
        staff_size,
        measures_per_system,
        interactive,
    };
    let svg = acorde_render_svg::render_svg(&score, &options)
        .map_err(|e| format!("SVG rendering failed: {e}"))?;
    std::fs::write(output, svg).map_err(|e| format!("cannot write '{}': {e}", output.display()))?;
    println!("rendered '{}' to '{}'", input.display(), output.display());
    Ok(())
}

#[derive(Debug, Serialize)]
struct RenderReportSummary {
    render_report_schema_version: u32,
    schema_version: u32,
    input_format: String,
    input_path: String,
    output_path: String,
    rendered: bool,
    svg_byte_count: usize,
    svg_fingerprint: Option<String>,
    render_error: Option<String>,
    import_warning_count: usize,
    import_error_count: usize,
    import_loss_count: usize,
    import_diagnostics: Vec<acorde_io::Diagnostic>,
    renderer_issues: Vec<acorde_render_svg::RenderPreflightIssue>,
}

fn render_report_summary(
    input: &Path,
    output: &Path,
    width: f32,
    staff_size: f32,
    measures_per_system: usize,
    interactive: bool,
) -> Result<RenderReportSummary, String> {
    let import = parse_report(input)?;
    let renderer_issues = acorde_render_svg::render_preflight(&import.score);
    let options = acorde_render_svg::SvgRenderOptions {
        width,
        staff_size,
        measures_per_system,
        interactive,
    };
    let (rendered, svg_byte_count, svg_fingerprint, render_error) =
        match acorde_render_svg::render_svg(&import.score, &options) {
            Ok(svg) => {
                let byte_count = svg.len();
                let fingerprint = bytes_fingerprint(svg.as_bytes());
                std::fs::write(output, svg)
                    .map_err(|e| format!("cannot write '{}': {e}", output.display()))?;
                (true, byte_count, Some(fingerprint), None)
            }
            Err(error) => (false, 0, None, Some(error.to_string())),
        };
    let import_warning_count = import.warning_count();
    let import_error_count = import.error_count();
    let import_loss_count = import.loss_count();
    Ok(RenderReportSummary {
        render_report_schema_version: RENDER_REPORT_SCHEMA_VERSION,
        schema_version: import.schema_version,
        input_format: import.format,
        input_path: input.display().to_string(),
        output_path: output.display().to_string(),
        rendered,
        svg_byte_count,
        svg_fingerprint,
        render_error,
        import_warning_count,
        import_error_count,
        import_loss_count,
        import_diagnostics: import.diagnostics,
        renderer_issues,
    })
}

fn cmd_render_report(
    input: &Path,
    output: &Path,
    width: f32,
    staff_size: f32,
    measures_per_system: usize,
    interactive: bool,
    fail_on_issues: bool,
) -> Result<(), String> {
    let report = render_report_summary(
        input,
        output,
        width,
        staff_size,
        measures_per_system,
        interactive,
    )?;
    let has_issues = !report.import_diagnostics.is_empty()
        || !report.renderer_issues.is_empty()
        || report.render_error.is_some();
    println!(
        "{}",
        serde_json::to_string_pretty(&report)
            .map_err(|e| format!("render report serialization failed: {e}"))?
    );
    if fail_on_issues && has_issues {
        return Err("render report found import or renderer issue(s)".to_string());
    }
    Ok(())
}

fn cmd_print_report(input: &Path, options: PrintReportOptions<'_>) -> Result<(), String> {
    let import = parse_report(input)?;
    let config = build_print_config(&options)?;
    let layout = acorde_layout::compute_print_layout(&import.score, &config)
        .map_err(|e| format!("print layout failed: {e}"))?;
    let renderer_issues = acorde_render_svg::render_preflight(&import.score);
    let has_issues = !import.diagnostics.is_empty() || !renderer_issues.is_empty();
    let import_warning_count = import.warning_count();
    let import_error_count = import.error_count();
    let import_loss_count = import.loss_count();
    let report = PrintReportSummary {
        print_report_schema_version: PRINT_REPORT_SCHEMA_VERSION,
        import_report_schema_version: import.schema_version,
        score_schema_version: import.score.schema_version,
        input_format: import.format,
        input_path: input.display().to_string(),
        import_warning_count,
        import_error_count,
        import_loss_count,
        import_diagnostics: import.diagnostics,
        renderer_issues,
        layout,
    };
    serde_json::to_writer_pretty(std::io::stdout(), &report)
        .map_err(|e| format!("print report serialization failed: {e}"))?;
    println!();
    if options.fail_on_issues && has_issues {
        return Err("print report found import or renderer issue(s)".to_string());
    }
    Ok(())
}

fn build_print_config(
    options: &PrintReportOptions<'_>,
) -> Result<acorde_layout::PrintConfig, String> {
    let preset = match options.preset {
        PrintPresetArg::A4Score if options.part.is_some() => {
            return Err("--part requires an extracted-part preset".to_string());
        }
        PrintPresetArg::LetterScore if options.part.is_some() => {
            return Err("--part requires an extracted-part preset".to_string());
        }
        PrintPresetArg::A4Score => acorde_layout::PrintPreset::A4Score,
        PrintPresetArg::LetterScore => acorde_layout::PrintPreset::LetterScore,
        PrintPresetArg::A4Part => acorde_layout::PrintPreset::A4Part {
            part_index: options
                .part
                .ok_or("--part is required for --preset a4-part")?,
        },
        PrintPresetArg::LetterPart => acorde_layout::PrintPreset::LetterPart {
            part_index: options
                .part
                .ok_or("--part is required for --preset letter-part")?,
        },
    };
    let mut config = preset.config_with_title_page(options.title_page);
    config.measures_per_system = options.measures_per_system;
    config.systems_per_page = options.systems_per_page;
    config.scale = options.scale;
    config.first_system_measures = options.first_system_measures;
    config.final_page_policy = match options.final_page_policy {
        PrintFinalPagePolicyArg::AllowSingleSystem => {
            acorde_layout::FinalPagePolicy::AllowSingleSystem
        }
        PrintFinalPagePolicyArg::Balance => acorde_layout::FinalPagePolicy::Balance,
    };
    config.notation_break_policy = match options.notation_break_policy {
        PrintNotationBreakPolicyArg::Preserve => acorde_layout::NotationBreakPolicy::Preserve,
        PrintNotationBreakPolicyArg::KeepVoltaTogether => {
            acorde_layout::NotationBreakPolicy::KeepVoltaTogether
        }
        PrintNotationBreakPolicyArg::KeepRepeatsTogether => {
            acorde_layout::NotationBreakPolicy::KeepRepeatsTogether
        }
    };
    config.pickup_policy = match options.pickup_policy {
        PrintPickupPolicyArg::Auto => acorde_layout::PickupPolicy::Auto,
        PrintPickupPolicyArg::Preserve => acorde_layout::PickupPolicy::Preserve,
        PrintPickupPolicyArg::DetectFirstMeasure => acorde_layout::PickupPolicy::DetectFirstMeasure,
    };
    config.publication.running_title = options.running_title.map(str::to_owned);
    config.publication.header_text = options.header_text.map(str::to_owned);
    config.publication.footer_text = options.footer_text.map(str::to_owned);
    config.publication.page_number_in_footer = options.page_number_in_footer;
    config.publication.show_part_names = options.show_part_names;
    Ok(config)
}

fn cmd_analyze(input: &Path) -> Result<(), String> {
    let score = parse_score(input)?;
    let analysis = acorde_analysis::analyze_score(&score);
    let json = serde_json::to_string_pretty(&analysis)
        .map_err(|e| format!("analysis serialization failed: {e}"))?;
    println!("{json}");
    Ok(())
}

#[derive(Debug, Serialize, Deserialize)]
struct BenchmarkManifest {
    schema_version: u32,
    corpus_id: String,
    corpus_version: String,
    license: String,
    cases: Vec<BenchmarkManifestCase>,
}

#[derive(Debug, Serialize, Deserialize)]
struct BenchmarkManifestCase {
    name: String,
    input: PathBuf,
    coverage: Vec<String>,
    provenance: String,
    #[serde(default)]
    expected: acorde_analysis::BenchmarkExpectation,
}

#[derive(Debug, Serialize)]
struct BenchmarkCorpusMetadata {
    schema_version: u32,
    corpus_id: String,
    corpus_version: String,
    license: String,
    fingerprint: String,
    cases: Vec<BenchmarkCorpusCaseMetadata>,
}

#[derive(Debug, Serialize)]
struct BenchmarkCorpusCaseMetadata {
    name: String,
    coverage: Vec<String>,
    provenance: String,
}

#[derive(Debug, Serialize)]
struct BenchmarkOutput {
    corpus: BenchmarkCorpusMetadata,
    report: acorde_analysis::BenchmarkSuiteReport,
}

fn cmd_benchmark(
    manifest: &Path,
    fail_on_mismatch: bool,
    expected_fingerprint: Option<&str>,
) -> Result<(), String> {
    let text = std::fs::read_to_string(manifest)
        .map_err(|e| format!("cannot read '{}': {e}", manifest.display()))?;
    let manifest_data: BenchmarkManifest = serde_json::from_str(&text)
        .map_err(|e| format!("invalid benchmark manifest '{}': {e}", manifest.display()))?;
    let base_dir = manifest.parent().unwrap_or_else(|| Path::new("."));
    let fingerprint = benchmark_fingerprint(&manifest_data, base_dir)?;
    let mut scores = Vec::with_capacity(manifest_data.cases.len());
    for case in &manifest_data.cases {
        scores.push(parse_score(&base_dir.join(&case.input))?);
    }
    let cases: Vec<_> = manifest_data
        .cases
        .iter()
        .zip(scores.iter())
        .map(|(case, score)| acorde_analysis::BenchmarkCase {
            name: &case.name,
            score,
            expected: case.expected,
        })
        .collect();
    let report = acorde_analysis::run_benchmark_suite(&cases);
    drop(cases);
    let output = BenchmarkOutput {
        corpus: BenchmarkCorpusMetadata {
            schema_version: manifest_data.schema_version,
            corpus_id: manifest_data.corpus_id,
            corpus_version: manifest_data.corpus_version,
            license: manifest_data.license,
            fingerprint,
            cases: manifest_data
                .cases
                .into_iter()
                .map(|case| BenchmarkCorpusCaseMetadata {
                    name: case.name,
                    coverage: case.coverage,
                    provenance: case.provenance,
                })
                .collect(),
        },
        report,
    };
    if let Some(expected) = expected_fingerprint
        && expected != output.corpus.fingerprint
    {
        return Err(format!(
            "benchmark fingerprint mismatch: expected '{expected}', found '{}'",
            output.corpus.fingerprint
        ));
    }
    let failed_case_count = output.report.failed_case_count;
    let json = serde_json::to_string_pretty(&output)
        .map_err(|e| format!("benchmark serialization failed: {e}"))?;
    println!("{json}");
    if fail_on_mismatch && failed_case_count > 0 {
        return Err(format!(
            "benchmark failed: {} of {} case(s) contain mismatches",
            failed_case_count, output.report.case_count
        ));
    }
    Ok(())
}

fn benchmark_fingerprint(manifest: &BenchmarkManifest, base_dir: &Path) -> Result<String, String> {
    let manifest_bytes = serde_json::to_vec(manifest)
        .map_err(|e| format!("benchmark manifest serialization failed: {e}"))?;
    let mut hash = 0xcbf29ce484222325_u64;
    for byte in manifest_bytes {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(0x100000001b3);
    }
    for case in &manifest.cases {
        let input_path = base_dir.join(&case.input);
        let bytes = std::fs::read(&input_path)
            .map_err(|e| format!("cannot read '{}': {e}", input_path.display()))?;
        for byte in bytes {
            hash ^= u64::from(byte);
            hash = hash.wrapping_mul(0x100000001b3);
        }
    }
    Ok(format!("fnv1a64-{hash:016x}"))
}

fn bytes_fingerprint(bytes: &[u8]) -> String {
    let mut hash = 0xcbf29ce484222325_u64;
    for byte in bytes {
        hash ^= u64::from(*byte);
        hash = hash.wrapping_mul(0x100000001b3);
    }
    format!("fnv1a64-{hash:016x}")
}

// ── convert ───────────────────────────────────────────────────────────────────

fn write_score(score: &Score, output: &Path) -> Result<(), String> {
    let diagnostics = write_score_with_report(score, output)?;
    print_conversion_diagnostics("export", &diagnostics);
    Ok(())
}

fn write_score_with_report(score: &Score, output: &Path) -> Result<Vec<Diagnostic>, String> {
    let ext = output
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_ascii_lowercase();
    match ext.as_str() {
        "xml" | "musicxml" => {
            let report =
                acorde_io::serialize_musicxml_with_report(score).map_err(|e| e.to_string())?;
            std::fs::write(output, report.output)
                .map_err(|e| format!("cannot write '{}': {e}", output.display()))?;
            Ok(report.diagnostics)
        }
        "mid" | "midi" => {
            let report = acorde_io::serialize_midi_with_report(score).map_err(|e| e.to_string())?;
            std::fs::write(output, report.output)
                .map_err(|e| format!("cannot write '{}': {e}", output.display()))?;
            Ok(report.diagnostics)
        }
        "abc" => {
            let report = acorde_io::serialize_abc_with_report(score).map_err(|e| e.to_string())?;
            std::fs::write(output, report.output)
                .map_err(|e| format!("cannot write '{}': {e}", output.display()))?;
            Ok(report.diagnostics)
        }
        "mei" => {
            let report = acorde_io::serialize_mei_with_report(score).map_err(|e| e.to_string())?;
            std::fs::write(output, report.output)
                .map_err(|e| format!("cannot write '{}': {e}", output.display()))?;
            Ok(report.diagnostics)
        }
        "mscx" => {
            let report = acorde_io::serialize_mscx_with_report(score).map_err(|e| e.to_string())?;
            std::fs::write(output, report.output)
                .map_err(|e| format!("cannot write '{}': {e}", output.display()))?;
            Ok(report.diagnostics)
        }
        "mscz" => {
            let report = acorde_io::serialize_mscz_with_report(score).map_err(|e| e.to_string())?;
            std::fs::write(output, report.output)
                .map_err(|e| format!("cannot write '{}': {e}", output.display()))?;
            Ok(report.diagnostics)
        }
        other => Err(format!("unsupported output format: '.{other}'")),
    }
}

fn print_conversion_diagnostics(phase: &str, diagnostics: &[Diagnostic]) {
    for diagnostic in diagnostics {
        let severity = match diagnostic.severity {
            DiagnosticSeverity::Info => "info",
            DiagnosticSeverity::Warning => "warning",
            DiagnosticSeverity::Error => "error",
        };
        let location = diagnostic
            .source_location
            .as_deref()
            .map(|value| format!(" at {value}"))
            .unwrap_or_default();
        let reason = diagnostic
            .loss_reason
            .as_deref()
            .or(diagnostic.preserved_value.as_deref())
            .unwrap_or("no additional detail");
        eprintln!(
            "{phase} diagnostic [{severity}] {}{location}: {reason}",
            diagnostic.code
        );
    }
}

fn cmd_convert(input: &Path, output: &Path) -> Result<(), String> {
    let import = parse_report(input)?;
    print_conversion_diagnostics("import", &import.diagnostics);
    let export_diagnostics = write_score_with_report(&import.score, output)?;
    print_conversion_diagnostics("export", &export_diagnostics);
    println!("wrote '{}'", output.display());
    Ok(())
}

// ── info ──────────────────────────────────────────────────────────────────────

fn cmd_info(input: &Path) -> Result<(), String> {
    let score = parse_score(input)?;
    let stats = score.statistics();
    let ts = &score.settings.time_signature;

    println!("title:    {}", score.metadata.title);
    println!("parts:    {}", stats.part_count);
    println!("measures: {}", stats.measure_count);
    println!(
        "notes:    {} (rests: {})",
        stats.note_count, stats.rest_count
    );
    println!("tempo:    {} BPM", score.settings.tempo_bpm);
    println!("time:     {}/{}", ts.numerator, ts.denominator);
    println!("duration: {:.1}s (estimate)", stats.estimated_duration_secs);
    if !score.metadata.composer.is_empty() {
        println!("composer: {}", score.metadata.composer);
    }
    Ok(())
}

// ── validate ──────────────────────────────────────────────────────────────────

fn cmd_validate(input: &Path) -> Result<(), String> {
    let score = parse_score(input)?;
    let report = acorde_core::validate(&score);
    for w in &report.warnings {
        match w {
            acorde_core::ValidationWarning::IncompleteBar {
                part,
                staff,
                measure,
                expected_beats,
                actual_beats,
            } => eprintln!(
                "warning: part {} staff {} measure {}: incomplete bar ({:.2}/{:.2} beats)",
                part + 1,
                staff + 1,
                measure + 1,
                actual_beats,
                expected_beats
            ),
            acorde_core::ValidationWarning::OverlappingVolta { part, staff } => eprintln!(
                "warning: part {} staff {}: overlapping volta brackets",
                part + 1,
                staff + 1
            ),
            acorde_core::ValidationWarning::EmptyPart { part } => {
                eprintln!("warning: part {} has no notes", part + 1)
            }
            acorde_core::ValidationWarning::DuplicateRehearsalMark { mark } => {
                eprintln!("warning: rehearsal mark '{}' appears more than once", mark)
            }
            acorde_core::ValidationWarning::MeasureRepeatContentDiffers {
                part,
                staff,
                measure,
                source,
            } => eprintln!(
                "warning: part {} staff {} measure {}: measure repeat differs from measure {}",
                part + 1,
                staff + 1,
                measure + 1,
                source + 1
            ),
        }
    }
    if report.errors.is_empty() {
        println!("OK: '{}'", input.display());
        Ok(())
    } else {
        for e in &report.errors {
            match e {
                acorde_core::ValidationError::EmptyScore => {
                    eprintln!("score has no parts")
                }
                acorde_core::ValidationError::PartWithoutStaves { part } => {
                    eprintln!("part {} has no staves", part + 1)
                }
                acorde_core::ValidationError::StaffWithoutMeasures { part, staff } => {
                    eprintln!("part {} staff {} has no measures", part + 1, staff + 1)
                }
                acorde_core::ValidationError::MeasureCountMismatch {
                    part,
                    staff,
                    expected,
                    found,
                } => eprintln!(
                    "part {} staff {}: expected {} measures, found {}",
                    part + 1,
                    staff + 1,
                    expected,
                    found
                ),
                acorde_core::ValidationError::InvalidTimeSignature {
                    part,
                    staff,
                    measure,
                    numerator,
                    denominator,
                } => eprintln!(
                    "part {} staff {} measure {}: invalid time signature {}/{}",
                    part + 1,
                    staff + 1,
                    measure + 1,
                    numerator,
                    denominator
                ),
                acorde_core::ValidationError::InvalidLyricVerse {
                    part,
                    staff,
                    measure,
                    voice,
                    note,
                    verse,
                } => eprintln!(
                    "part {} staff {} measure {} voice {} note {}: invalid lyric verse {}",
                    part + 1,
                    staff + 1,
                    measure + 1,
                    voice + 1,
                    note + 1,
                    verse
                ),
                acorde_core::ValidationError::InvalidMeasureRepeat {
                    part,
                    staff,
                    measure,
                    count,
                } => eprintln!(
                    "part {} staff {} measure {}: invalid {}-measure repeat",
                    part + 1,
                    staff + 1,
                    measure + 1,
                    count
                ),
                acorde_core::ValidationError::InvalidMidMeasureClef {
                    part,
                    staff,
                    measure,
                    index,
                } => eprintln!(
                    "part {} staff {} measure {}: mid-bar clef change {} is outside the bar or out of order",
                    part + 1,
                    staff + 1,
                    measure + 1,
                    index + 1
                ),
                acorde_core::ValidationError::InvalidMeasureLength {
                    part,
                    staff,
                    measure,
                    numerator,
                    denominator,
                } => eprintln!(
                    "part {} staff {} measure {}: invalid measure length {}/{}",
                    part + 1,
                    staff + 1,
                    measure + 1,
                    numerator,
                    denominator
                ),
                acorde_core::ValidationError::BeatCount {
                    part,
                    staff,
                    measure,
                    voice,
                    expected_beats,
                    found_beats,
                } => eprintln!(
                    "part {} staff {} measure {} voice {}: expected {:.2} beats, found {:.2}",
                    part + 1,
                    staff + 1,
                    measure + 1,
                    voice + 1,
                    expected_beats,
                    found_beats
                ),
                acorde_core::ValidationError::OutOfRange {
                    part_index,
                    staff_index,
                    measure_index,
                    note_index,
                    pitch_midi,
                    instrument_range,
                } => eprintln!(
                    "part {} staff {} measure {} note {}: pitch MIDI {} out of instrument range {}–{}",
                    part_index + 1,
                    staff_index + 1,
                    measure_index + 1,
                    note_index + 1,
                    pitch_midi,
                    instrument_range.0,
                    instrument_range.1
                ),
                acorde_core::ValidationError::InvalidTablature {
                    part,
                    staff,
                    reason,
                } => eprintln!(
                    "part {} staff {}: invalid tablature metadata: {:?}",
                    part + 1,
                    staff + 1,
                    reason
                ),
                acorde_core::ValidationError::InvalidStaffPresentation {
                    part,
                    staff,
                    reason,
                } => eprintln!(
                    "part {} staff {}: invalid staff presentation: {:?}",
                    part + 1,
                    staff + 1,
                    reason
                ),
                acorde_core::ValidationError::InvalidInstrumentDefinition { part, reason } => {
                    eprintln!(
                        "part {}: invalid instrument definition: {:?}",
                        part + 1,
                        reason
                    )
                }
                acorde_core::ValidationError::InvalidPercussionInstrument {
                    part,
                    instrument,
                    id,
                    reason,
                } => eprintln!(
                    "part {} percussion instrument {} ('{}'): invalid definition: {:?}",
                    part + 1,
                    instrument + 1,
                    id,
                    reason
                ),
                acorde_core::ValidationError::InvalidScoreView { index, id, reason } => {
                    eprintln!(
                        "score view {} ('{}'): invalid definition: {:?}",
                        index + 1,
                        id,
                        reason
                    )
                }
                acorde_core::ValidationError::InvalidScoreStyleOverride { property, value } => {
                    eprintln!(
                        "score style default {:?}: value {} must be finite and within 0.05..=64",
                        property, value
                    )
                }
                acorde_core::ValidationError::InvalidObjectStyleOverride { index, reason } => {
                    eprintln!(
                        "object style override {}: invalid definition: {:?}",
                        index + 1,
                        reason
                    )
                }
                acorde_core::ValidationError::TabPositionOutOfRange {
                    part,
                    staff,
                    measure,
                    voice,
                    note,
                    string,
                    lines,
                } => eprintln!(
                    "part {} staff {} measure {} voice {} note {}: tablature string {} exceeds {} lines",
                    part + 1,
                    staff + 1,
                    measure + 1,
                    voice + 1,
                    note + 1,
                    string,
                    lines
                ),
                acorde_core::ValidationError::MicrotoneOutOfRange {
                    part,
                    staff,
                    measure,
                    voice,
                    note,
                    pitch,
                    microtone_cents,
                } => eprintln!(
                    "part {} staff {} measure {} voice {} note {} pitch {}: microtone cents {} is outside -99..99",
                    part + 1,
                    staff + 1,
                    measure + 1,
                    voice + 1,
                    note + 1,
                    pitch + 1,
                    microtone_cents
                ),
                acorde_core::ValidationError::InvalidGuitarBendCurve {
                    part,
                    staff,
                    measure,
                    voice,
                    note,
                    reason,
                } => eprintln!(
                    "part {} staff {} measure {} voice {} note {}: invalid guitar bend curve ({reason:?})",
                    part + 1,
                    staff + 1,
                    measure + 1,
                    voice + 1,
                    note + 1
                ),
                acorde_core::ValidationError::InvalidHarmonyRange {
                    part,
                    staff,
                    measure,
                    voice,
                    note,
                    end,
                } => eprintln!(
                    "part {} staff {} measure {} voice {} note {}: harmony range ends at missing note {}:{}:{}:{}:{}",
                    part + 1,
                    staff + 1,
                    measure + 1,
                    voice + 1,
                    note + 1,
                    end.part + 1,
                    end.staff + 1,
                    end.measure + 1,
                    end.voice + 1,
                    end.note + 1
                ),
                acorde_core::ValidationError::InvalidSpannerId { index, id } => eprintln!(
                    "notation spanner {} has an empty stable id ('{}')",
                    index + 1,
                    id
                ),
                acorde_core::ValidationError::DuplicateSpannerId {
                    first,
                    duplicate,
                    id,
                } => eprintln!(
                    "notation spanners {} and {} share stable id '{}'",
                    first + 1,
                    duplicate + 1,
                    id
                ),
                acorde_core::ValidationError::InvalidSpannerEndpoint {
                    index,
                    id,
                    kind,
                    endpoint,
                    address,
                } => eprintln!(
                    "notation spanner {} ('{}', {:?}) has a missing {:?} endpoint at {}:{}:{}:{}:{}",
                    index + 1,
                    id,
                    kind,
                    endpoint,
                    address.part + 1,
                    address.staff + 1,
                    address.measure + 1,
                    address.voice + 1,
                    address.note + 1
                ),
            }
        }
        std::process::exit(1);
    }
}

// ── extract ───────────────────────────────────────────────────────────────────

#[allow(clippy::too_many_arguments)]
fn cmd_tab_position(
    input: &Path,
    output: &Path,
    part: usize,
    staff: usize,
    measure: usize,
    voice: usize,
    note: usize,
    string: Option<u8>,
    fret: Option<u8>,
    clear: bool,
) -> Result<(), String> {
    let mut score = parse_score(input)?;
    let position = if clear {
        None
    } else {
        let string = string.ok_or("--string is required unless --clear is used")?;
        let fret = fret.ok_or("--fret is required unless --clear is used")?;
        if string == 0 {
            return Err("--string is one-based and must be at least 1".to_string());
        }
        Some(TabPosition { string, fret })
    };
    let command = Command::SetTabPosition(SetTabPositionCmd {
        part_index: part,
        staff_index: staff,
        measure_index: measure,
        voice,
        note_index: note,
        position,
    });
    let mut engine = ScoreEngine::new();
    engine
        .try_replace_score(score)
        .map_err(|e| format!("cannot load score: {e}"))?;
    engine
        .apply(command)
        .map_err(|e| format!("cannot edit score: {e}"))?;
    score = engine.score;
    write_score(&score, output)?;
    println!("updated tablature position in '{}'", output.display());
    Ok(())
}

fn cmd_auto_tab(input: &Path, output: &Path) -> Result<(), String> {
    let mut score = parse_score(input)?;
    let assigned = acorde_core::optimize_tablature_positions(&mut score);
    write_score(&score, output)?;
    println!(
        "assigned optimized tablature positions for {} note(s) to '{}'",
        assigned,
        output.display()
    );
    Ok(())
}

#[derive(Debug, Serialize)]
struct AutoTabReport {
    assigned_notes: usize,
    chord_count: usize,
    positioned_notes: usize,
    unpositioned_notes: usize,
    total_fret: u32,
    maximum_fret: u8,
    output: String,
}

fn cmd_auto_tab_report(input: &Path, output: &Path) -> Result<(), String> {
    let mut score = parse_score(input)?;
    let assigned_notes = acorde_core::optimize_tablature_positions(&mut score);
    let mut report = AutoTabReport {
        assigned_notes,
        chord_count: 0,
        positioned_notes: 0,
        unpositioned_notes: 0,
        total_fret: 0,
        maximum_fret: 0,
        output: output.display().to_string(),
    };
    for part in &score.parts {
        for staff in &part.staves {
            if staff.tablature.is_none() {
                continue;
            }
            for measure in &staff.measures {
                for voice in &measure.voices {
                    for note in voice {
                        if note.is_rest || note.pitches.is_empty() {
                            continue;
                        }
                        report.chord_count += if note.pitches.len() > 1 { 1 } else { 0 };
                        let positions = if !note.tab_positions.is_empty() {
                            note.tab_positions.as_slice()
                        } else {
                            note.tab_position.as_slice()
                        };
                        if positions.is_empty() {
                            report.unpositioned_notes += 1;
                        } else {
                            report.positioned_notes += 1;
                            for position in positions {
                                report.total_fret += u32::from(position.fret);
                                report.maximum_fret = report.maximum_fret.max(position.fret);
                            }
                        }
                    }
                }
            }
        }
    }
    write_score(&score, output)?;
    println!(
        "{}",
        serde_json::to_string_pretty(&report)
            .map_err(|e| format!("tablature report serialization failed: {e}"))?
    );
    Ok(())
}

fn cmd_tab_performance_report(
    input: &Path,
    bpm: Option<u16>,
    fail_on_diagnostics: bool,
) -> Result<(), String> {
    let score = parse_score(input)?;
    let options = PlaybackOptions {
        bpm_override: bpm,
        ..PlaybackOptions::default()
    };
    let report = acorde_core::project_tablature_performance(&score, &options)
        .map_err(|e| format!("tablature performance projection failed: {e}"))?;
    println!(
        "{}",
        serde_json::to_string_pretty(&report)
            .map_err(|e| format!("tablature performance report serialization failed: {e}"))?
    );
    if fail_on_diagnostics && !report.diagnostics.is_empty() {
        return Err(format!(
            "tablature performance report found {} diagnostic(s)",
            report.diagnostics.len()
        ));
    }
    Ok(())
}

fn cmd_playback_report(
    input: &Path,
    bpm: Option<u16>,
    loop_start: Option<usize>,
    loop_end: Option<usize>,
) -> Result<(), String> {
    let score = parse_score(input)?;
    let events = playback_report_events(&score, bpm, loop_start, loop_end)?;
    println!(
        "{}",
        serde_json::to_string_pretty(&events)
            .map_err(|e| format!("playback report serialization failed: {e}"))?
    );
    Ok(())
}

fn playback_report_events(
    score: &Score,
    bpm: Option<u16>,
    loop_start: Option<usize>,
    loop_end: Option<usize>,
) -> Result<Vec<acorde_core::PlaybackEvent>, String> {
    if let (Some(start), Some(end)) = (loop_start, loop_end) {
        if start > end {
            return Err("--loop-start must not exceed --loop-end".to_string());
        }
    }
    let options = PlaybackOptions {
        bpm_override: bpm,
        loop_region: loop_start.zip(loop_end),
        ..PlaybackOptions::default()
    };
    acorde_core::to_playback_events_bounded(score, &options)
        .map_err(|e| format!("playback report generation failed: {e}"))
}

fn read_playback_events(path: &Path) -> Result<Vec<acorde_core::PlaybackEvent>, String> {
    let metadata =
        std::fs::metadata(path).map_err(|e| format!("cannot inspect '{}': {e}", path.display()))?;
    if metadata.len() > MAX_PLAYBACK_JSON_BYTES as u64 {
        return Err(format!(
            "playback event JSON '{}' exceeds {} bytes",
            path.display(),
            MAX_PLAYBACK_JSON_BYTES
        ));
    }
    let data = std::fs::read(path).map_err(|e| format!("cannot read '{}': {e}", path.display()))?;
    if data.len() > MAX_PLAYBACK_JSON_BYTES {
        return Err(format!(
            "playback event JSON '{}' exceeds {} bytes",
            path.display(),
            MAX_PLAYBACK_JSON_BYTES
        ));
    }
    let text = String::from_utf8(data).map_err(|e| {
        format!(
            "invalid UTF-8 in playback event JSON '{}': {e}",
            path.display()
        )
    })?;
    serde_json::from_str(&text)
        .map_err(|e| format!("invalid playback event JSON '{}': {e}", path.display()))
}

fn cmd_playback_compare(
    expected_path: &Path,
    actual_path: &Path,
    start_tolerance: f64,
    duration_tolerance: f64,
    fail_on_mismatch: bool,
) -> Result<(), String> {
    let expected = read_playback_events(expected_path)?;
    let actual = read_playback_events(actual_path)?;
    let report =
        playback_comparison_report(&expected, &actual, start_tolerance, duration_tolerance)?;
    println!(
        "{}",
        serde_json::to_string_pretty(&report)
            .map_err(|e| format!("playback comparison serialization failed: {e}"))?
    );
    if fail_on_mismatch && !report.within_tolerance {
        return Err(format!(
            "playback comparison found {} mismatch(es)",
            report.mismatches.len()
        ));
    }
    Ok(())
}

fn playback_comparison_report(
    expected: &[acorde_core::PlaybackEvent],
    actual: &[acorde_core::PlaybackEvent],
    start_tolerance: f64,
    duration_tolerance: f64,
) -> Result<acorde_core::PlaybackTimingReport, String> {
    let tolerance = acorde_core::PlaybackTimingTolerance {
        start_secs: start_tolerance,
        duration_secs: duration_tolerance,
    };
    acorde_core::compare_playback_timing(expected, actual, &tolerance)
        .map_err(|e| format!("playback comparison failed: {e}"))
}

#[derive(Debug, Serialize)]
struct FingeringReportEntry {
    part: usize,
    staff: usize,
    measure: usize,
    voice: usize,
    note: usize,
    candidates: Vec<u8>,
    selected: Option<u8>,
}

fn parse_fingering_policy(value: &str) -> Result<FingeringSelectionPolicy, String> {
    match value {
        "source-order" | "source" => Ok(FingeringSelectionPolicy::SourceOrder),
        "lowest" | "lowest-number" => Ok(FingeringSelectionPolicy::LowestNumber),
        "highest" | "highest-number" => Ok(FingeringSelectionPolicy::HighestNumber),
        _ => Err(format!(
            "unknown fingering policy '{value}'; expected source-order, lowest, or highest"
        )),
    }
}

fn cmd_fingering_report(input: &Path, policy: &str) -> Result<(), String> {
    let score = parse_score(input)?;
    let policy = parse_fingering_policy(policy)?;
    let mut entries = Vec::new();
    for (part_index, part) in score.parts.iter().enumerate() {
        for (staff_index, staff) in part.staves.iter().enumerate() {
            for (measure_index, measure) in staff.measures.iter().enumerate() {
                for (voice_index, voice) in measure.voices.iter().enumerate() {
                    for (note_index, note) in voice.iter().enumerate() {
                        let candidates = if note.fingerings.is_empty() {
                            note.fingering.into_iter().collect()
                        } else {
                            note.fingerings.clone()
                        };
                        if candidates.is_empty() {
                            continue;
                        }
                        entries.push(FingeringReportEntry {
                            part: part_index,
                            staff: staff_index,
                            measure: measure_index,
                            voice: voice_index,
                            note: note_index,
                            candidates,
                            selected: note.select_fingering(policy),
                        });
                    }
                }
            }
        }
    }
    println!(
        "{}",
        serde_json::to_string_pretty(&entries)
            .map_err(|e| format!("fingering report serialization failed: {e}"))?
    );
    Ok(())
}

fn cmd_extract(input: &Path, output: &Path, part_index: usize) -> Result<(), String> {
    let score = parse_score(input)?;
    let extracted = score.extract_part(part_index).ok_or_else(|| {
        format!(
            "part index {} out of range (score has {} part(s))",
            part_index,
            score.parts.len()
        )
    })?;
    write_score(&extracted, output)?;
    println!("extracted part {} to '{}'", part_index, output.display());
    Ok(())
}

fn cmd_transpose(input: &Path, output: &Path, semitones: i8) -> Result<(), String> {
    let score = parse_score(input)?;
    let transposed = acorde_core::transpose(&score, semitones);
    write_score(&transposed, output)?;
    println!(
        "transposed {} semitone(s) to '{}'",
        semitones,
        output.display()
    );
    Ok(())
}

fn cmd_normalize(input: &Path, output: &Path) -> Result<(), String> {
    let score = parse_score(input)?;
    let validation = acorde_core::validate(&score);
    if !validation.errors.is_empty() {
        return Err(format!(
            "cannot normalize structurally invalid score: {} error(s)",
            validation.errors.len()
        ));
    }
    write_score(&score, output)?;
    println!("normalized '{}' to '{}'", input.display(), output.display());
    Ok(())
}

#[derive(Debug, Serialize)]
struct ExportReportSummary {
    schema_version: u32,
    format: String,
    output_path: String,
    byte_count: usize,
    warning_count: usize,
    error_count: usize,
    loss_count: usize,
    diagnostics: Vec<acorde_io::Diagnostic>,
}

fn cmd_export_report(input: &Path, output: &Path) -> Result<(), String> {
    let score = parse_score(input)?;
    let ext = output
        .extension()
        .and_then(|e| e.to_str())
        .unwrap_or("")
        .to_ascii_lowercase();
    let (format, bytes, diagnostics, schema_version) = match ext.as_str() {
        "xml" | "musicxml" => {
            let report =
                acorde_io::serialize_musicxml_with_report(&score).map_err(|e| e.to_string())?;
            (
                report.format,
                report.output.into_bytes(),
                report.diagnostics,
                report.schema_version,
            )
        }
        "mid" | "midi" => {
            let report =
                acorde_io::serialize_midi_with_report(&score).map_err(|e| e.to_string())?;
            (
                report.format,
                report.output,
                report.diagnostics,
                report.schema_version,
            )
        }
        "abc" => {
            let report = acorde_io::serialize_abc_with_report(&score).map_err(|e| e.to_string())?;
            (
                report.format,
                report.output.into_bytes(),
                report.diagnostics,
                report.schema_version,
            )
        }
        "mei" => {
            let report = acorde_io::serialize_mei_with_report(&score).map_err(|e| e.to_string())?;
            (
                report.format,
                report.output.into_bytes(),
                report.diagnostics,
                report.schema_version,
            )
        }
        "mscx" => {
            let report =
                acorde_io::serialize_mscx_with_report(&score).map_err(|e| e.to_string())?;
            (
                report.format,
                report.output.into_bytes(),
                report.diagnostics,
                report.schema_version,
            )
        }
        "mscz" => {
            let report =
                acorde_io::serialize_mscz_with_report(&score).map_err(|e| e.to_string())?;
            (
                report.format,
                report.output,
                report.diagnostics,
                report.schema_version,
            )
        }
        other => return Err(format!("unsupported output format: '.{other}'")),
    };
    let byte_count = bytes.len();
    std::fs::write(output, bytes)
        .map_err(|e| format!("cannot write '{}': {e}", output.display()))?;
    let summary = ExportReportSummary {
        schema_version,
        format,
        output_path: output.display().to_string(),
        warning_count: diagnostics
            .iter()
            .filter(|d| d.severity == acorde_io::DiagnosticSeverity::Warning)
            .count(),
        error_count: diagnostics
            .iter()
            .filter(|d| d.severity == acorde_io::DiagnosticSeverity::Error)
            .count(),
        loss_count: diagnostics.iter().filter(|d| d.is_loss()).count(),
        diagnostics,
        byte_count,
    };
    println!(
        "{}",
        serde_json::to_string_pretty(&summary)
            .map_err(|e| format!("report serialization failed: {e}"))?
    );
    Ok(())
}

/// Version of the machine-readable compatibility-report envelope.
const COMPATIBILITY_REPORT_CONTRACT_VERSION: u16 = 1;

#[derive(Debug, Serialize)]
struct CompatibilityReport {
    contract_version: u16,
    tool_version: String,
    schema_version: u32,
    source_format: String,
    candidate_format: String,
    source_path: String,
    candidate_path: String,
    /// Stable local evidence identifier for the exact source bytes. This is not a
    /// cryptographic publication hash.
    source_fingerprint: String,
    /// Stable local evidence identifier for the exact candidate bytes. This is not a
    /// cryptographic publication hash.
    candidate_fingerprint: String,
    change_count: usize,
    semantic_equivalent: bool,
    analysis_changed_categories: Vec<acorde_analysis::AnalysisCategory>,
    analysis_equivalent: bool,
    lossless: bool,
    changes: Vec<acorde_core::ScoreChange>,
    source_warning_count: usize,
    source_error_count: usize,
    source_loss_count: usize,
    source_diagnostics: Vec<acorde_io::Diagnostic>,
    candidate_warning_count: usize,
    candidate_error_count: usize,
    candidate_loss_count: usize,
    candidate_diagnostics: Vec<acorde_io::Diagnostic>,
}

fn cmd_compatibility_report(
    source: &Path,
    candidate: &Path,
    fail_on_differences: bool,
    fail_on_loss: bool,
) -> Result<(), String> {
    let report = build_compatibility_report(source, candidate)?;
    println!(
        "{}",
        serde_json::to_string_pretty(&report)
            .map_err(|e| format!("compatibility report serialization failed: {e}"))?
    );
    if fail_on_differences && (!report.semantic_equivalent || !report.analysis_equivalent) {
        return Err(format!(
            "compatibility report found {} semantic difference(s) and {} analysis category change(s)",
            report.change_count,
            report.analysis_changed_categories.len()
        ));
    }
    if fail_on_loss && report.source_loss_count + report.candidate_loss_count > 0 {
        return Err(format!(
            "compatibility report found {} information-loss diagnostic(s)",
            report.source_loss_count + report.candidate_loss_count
        ));
    }
    Ok(())
}

fn build_compatibility_report(
    source: &Path,
    candidate: &Path,
) -> Result<CompatibilityReport, String> {
    let source_fingerprint = file_fingerprint(source)?;
    let candidate_fingerprint = file_fingerprint(candidate)?;
    let source_report = parse_report(source)?;
    let candidate_report = parse_report(candidate)?;
    let changes = acorde_core::diff(&source_report.score, &candidate_report.score);
    let source_analysis = acorde_analysis::analyze_score(&source_report.score);
    let candidate_analysis = acorde_analysis::analyze_score(&candidate_report.score);
    let analysis_diff = acorde_analysis::diff_analysis(&source_analysis, &candidate_analysis);
    let analysis_equivalent = analysis_diff.is_empty();
    let analysis_changed_categories = analysis_diff.changed_categories;
    Ok(CompatibilityReport {
        contract_version: COMPATIBILITY_REPORT_CONTRACT_VERSION,
        tool_version: env!("CARGO_PKG_VERSION").to_string(),
        schema_version: source_report.schema_version,
        source_format: source_report.format.clone(),
        candidate_format: candidate_report.format.clone(),
        source_path: source.display().to_string(),
        candidate_path: candidate.display().to_string(),
        source_fingerprint,
        candidate_fingerprint,
        change_count: changes.len(),
        semantic_equivalent: changes.is_empty(),
        analysis_changed_categories,
        analysis_equivalent,
        lossless: changes.is_empty()
            && source_report.loss_count() + candidate_report.loss_count() == 0,
        changes,
        source_warning_count: source_report.warning_count(),
        source_error_count: source_report.error_count(),
        source_loss_count: source_report.loss_count(),
        source_diagnostics: source_report.diagnostics,
        candidate_warning_count: candidate_report.warning_count(),
        candidate_error_count: candidate_report.error_count(),
        candidate_loss_count: candidate_report.loss_count(),
        candidate_diagnostics: candidate_report.diagnostics,
    })
}

fn file_fingerprint(path: &Path) -> Result<String, String> {
    let bytes =
        std::fs::read(path).map_err(|e| format!("cannot read '{}': {e}", path.display()))?;
    Ok(bytes_fingerprint(&bytes))
}

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

    fn fixture(name: &str) -> PathBuf {
        Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/fixtures")
            .join(name)
    }

    #[test]
    fn playback_report_is_deterministic_and_respects_measure_range() {
        let score = parse_score(&fixture("simple.musicxml")).expect("fixture parses");
        let all =
            playback_report_events(&score, Some(120), None, None).expect("full report succeeds");
        let partial = playback_report_events(&score, Some(120), Some(0), Some(0))
            .expect("partial report succeeds");
        let repeated = playback_report_events(&score, Some(120), None, None)
            .expect("repeated report succeeds");
        assert_eq!(all, repeated);
        assert!(!all.is_empty());
        assert!(!partial.is_empty());
        assert!(partial.len() <= all.len());
        assert!(partial.iter().all(|event| event.time_beats >= 0.0));
    }

    #[test]
    fn playback_report_rejects_reversed_measure_range() {
        let score = parse_score(&fixture("simple.musicxml")).expect("fixture parses");
        let error = playback_report_events(&score, None, Some(1), Some(0))
            .expect_err("reversed range must fail");
        assert!(error.contains("--loop-start must not exceed --loop-end"));
    }

    #[test]
    fn render_command_writes_deterministic_interactive_svg() {
        let output =
            std::env::temp_dir().join(format!("acorde-cli-render-{}.svg", std::process::id()));
        cmd_render(&fixture("simple.musicxml"), &output, 900.0, 24.0, 4, true)
            .expect("render command succeeds");
        let svg = std::fs::read_to_string(&output).expect("render output exists");
        assert!(svg.starts_with("<svg"));
        assert!(svg.contains("data-note-addr"));
        std::fs::remove_file(output).expect("temporary render output is removable");
    }

    #[test]
    fn convert_path_returns_export_loss_diagnostics() {
        let import = parse_report(&fixture("interchange_harm_analysis.mei"))
            .expect("MEI fixture report succeeds");
        let output = std::env::temp_dir().join(format!(
            "acorde-cli-convert-diagnostics-{}.musicxml",
            std::process::id()
        ));
        let diagnostics =
            write_score_with_report(&import.score, &output).expect("MusicXML conversion succeeds");
        assert!(diagnostics
            .iter()
            .any(|diagnostic| diagnostic.code == "musicxml.export-unsupported-mei-harmony-type"));
        std::fs::remove_file(output).expect("temporary conversion output is removable");
    }

    #[test]
    fn render_report_preserves_import_and_renderer_boundaries() {
        let output = std::env::temp_dir().join(format!(
            "acorde-cli-render-report-{}.svg",
            std::process::id()
        ));
        let report =
            render_report_summary(&fixture("simple.musicxml"), &output, 900.0, 24.0, 4, true)
                .expect("render report succeeds");
        assert_eq!(report.render_report_schema_version, 1);
        assert_eq!(report.input_format, "musicxml");
        assert_eq!(report.import_warning_count, 0);
        assert_eq!(report.import_error_count, 0);
        assert_eq!(report.import_loss_count, 0);
        assert!(report.import_diagnostics.is_empty());
        assert!(report.renderer_issues.is_empty());
        assert!(report.svg_byte_count > 0);
        assert!(report.svg_fingerprint.is_some());
        std::fs::remove_file(output).expect("temporary render report output is removable");
    }

    #[test]
    fn render_report_fingerprint_is_stable_for_same_input_and_options() {
        let first_output = std::env::temp_dir().join(format!(
            "acorde-cli-render-report-fingerprint-first-{}.svg",
            std::process::id()
        ));
        let second_output = std::env::temp_dir().join(format!(
            "acorde-cli-render-report-fingerprint-second-{}.svg",
            std::process::id()
        ));
        let first = render_report_summary(
            &fixture("simple.musicxml"),
            &first_output,
            900.0,
            24.0,
            4,
            true,
        )
        .expect("first render report succeeds");
        let second = render_report_summary(
            &fixture("simple.musicxml"),
            &second_output,
            900.0,
            24.0,
            4,
            true,
        )
        .expect("second render report succeeds");
        assert_eq!(first.svg_byte_count, second.svg_byte_count);
        assert_eq!(first.svg_fingerprint, second.svg_fingerprint);
        std::fs::remove_file(first_output).expect("first temporary output is removable");
        std::fs::remove_file(second_output).expect("second temporary output is removable");
    }

    #[test]
    fn render_report_retains_rejected_renderer_diagnostics() {
        let output = std::env::temp_dir().join(format!(
            "acorde-cli-render-report-rejected-{}.svg",
            std::process::id()
        ));
        let report = render_report_summary(
            &fixture("render_preflight_unsupported.musicxml"),
            &output,
            900.0,
            24.0,
            4,
            true,
        )
        .expect("diagnostic report succeeds even when rendering is rejected");
        assert!(!report.rendered);
        assert_eq!(report.svg_byte_count, 0);
        assert!(report.render_error.is_some());
        assert!(!report.renderer_issues.is_empty());
        assert!(!output.exists());
    }

    #[test]
    fn render_report_covers_declared_local_input_formats() {
        let cases = [
            ("simple.musicxml", "musicxml"),
            ("sample.abc", "abc"),
            ("interchange_subset.mei", "mei"),
            ("interchange_subset.mscx", "mscx"),
            ("4_steps_in_31-et_on_c.mid", "midi"),
        ];
        for (index, (name, format)) in cases.iter().enumerate() {
            let output = std::env::temp_dir().join(format!(
                "acorde-cli-render-format-{}-{}.svg",
                std::process::id(),
                index
            ));
            let report = render_report_summary(&fixture(name), &output, 900.0, 24.0, 4, true)
                .unwrap_or_else(|error| panic!("{name} report failed: {error}"));
            assert_eq!(report.input_format, *format);
            assert!(report.rendered, "{name} should render: {report:?}");
            assert!(report.render_error.is_none());
            assert!(report.svg_byte_count > 0);
            std::fs::remove_file(output).expect("temporary format output is removable");
        }
    }

    #[test]
    fn playback_compare_reports_tolerance_and_rejects_invalid_tolerance() {
        let score = parse_score(&fixture("simple.musicxml")).expect("fixture parses");
        let expected = playback_report_events(&score, Some(120), None, None)
            .expect("expected schedule succeeds");
        let mut actual = expected.clone();
        actual[0].time_secs += 0.01;
        let report = playback_comparison_report(&expected, &actual, 0.005, 0.005)
            .expect("comparison succeeds");
        assert!(!report.within_tolerance);
        assert_eq!(report.matched_events, expected.len() - 1);
        assert!(playback_comparison_report(&expected, &actual, -0.001, 0.005).is_err());
    }

    #[test]
    fn compatibility_report_records_tool_and_input_evidence() {
        let input = fixture("simple.musicxml");
        let report = build_compatibility_report(&input, &input)
            .expect("identical fixture compatibility report succeeds");
        assert_eq!(
            report.contract_version,
            COMPATIBILITY_REPORT_CONTRACT_VERSION
        );
        assert_eq!(report.tool_version, env!("CARGO_PKG_VERSION"));
        assert!(report.source_fingerprint.starts_with("fnv1a64-"));
        assert_eq!(report.source_fingerprint, report.candidate_fingerprint);
        assert!(report.semantic_equivalent);
    }

    #[test]
    fn print_report_config_preserves_preset_and_publication_policies() {
        let config = build_print_config(&PrintReportOptions {
            preset: PrintPresetArg::LetterPart,
            part: Some(2),
            measures_per_system: 3,
            systems_per_page: Some(4),
            title_page: true,
            running_title: Some("Suite"),
            header_text: Some("Header"),
            footer_text: Some("Footer"),
            page_number_in_footer: true,
            show_part_names: false,
            fail_on_issues: false,
            scale: 1.1,
            first_system_measures: Some(2),
            final_page_policy: PrintFinalPagePolicyArg::Balance,
            notation_break_policy: PrintNotationBreakPolicyArg::KeepVoltaTogether,
            pickup_policy: PrintPickupPolicyArg::Preserve,
        })
        .expect("print config succeeds");
        assert_eq!(config.paper_size, acorde_layout::PaperSize::Letter);
        assert_eq!(
            config.part_layout,
            acorde_layout::PartLayoutPolicy::ExtractedPart { part_index: 2 }
        );
        assert_eq!(config.measures_per_system, 3);
        assert_eq!(config.systems_per_page, Some(4));
        assert_eq!(config.scale, 1.1);
        assert_eq!(config.first_system_measures, Some(2));
        assert_eq!(
            config.final_page_policy,
            acorde_layout::FinalPagePolicy::Balance
        );
        assert_eq!(
            config.notation_break_policy,
            acorde_layout::NotationBreakPolicy::KeepVoltaTogether
        );
        assert_eq!(config.pickup_policy, acorde_layout::PickupPolicy::Preserve);
        assert!(config.publication.title_page);
        assert_eq!(config.publication.running_title.as_deref(), Some("Suite"));
        assert_eq!(config.publication.header_text.as_deref(), Some("Header"));
        assert_eq!(config.publication.footer_text.as_deref(), Some("Footer"));
        assert!(config.publication.page_number_in_footer);
        assert!(!config.publication.show_part_names);
    }

    #[test]
    fn print_report_config_rejects_part_on_full_score_preset() {
        let error = build_print_config(&PrintReportOptions {
            preset: PrintPresetArg::A4Score,
            part: Some(0),
            measures_per_system: 4,
            systems_per_page: None,
            title_page: false,
            running_title: None,
            header_text: None,
            footer_text: None,
            page_number_in_footer: false,
            show_part_names: true,
            fail_on_issues: false,
            scale: 1.0,
            first_system_measures: None,
            final_page_policy: PrintFinalPagePolicyArg::AllowSingleSystem,
            notation_break_policy: PrintNotationBreakPolicyArg::Preserve,
            pickup_policy: PrintPickupPolicyArg::Auto,
        })
        .expect_err("full score must reject part selection");
        assert!(error.contains("requires an extracted-part preset"));
    }
}