acorde-cli 1.2.20

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
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
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 MAX_OMR_REPORT_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,
    },
    /// Recognize the supported printed-PNG subset and write a reviewed MuseScore .mscz draft
    Omr {
        /// Input high-contrast PNG score image
        input: PathBuf,
        /// Output MuseScore .mscz file; not written when review diagnostics are present
        output: PathBuf,
        /// Minimum proposal confidence required for automatic application
        #[arg(long, default_value_t = 0.9)]
        minimum_confidence: f32,
        /// Luminance at or below which an input pixel is treated as dark
        #[arg(long, default_value_t = 160)]
        darkness_threshold: u8,
        /// Required dark-pixel fraction for one detected staff line
        #[arg(long, default_value_t = 0.35)]
        minimum_staff_line_coverage: f32,
        /// Meter numerator supplied by the caller; not inferred from image pixels
        #[arg(long, default_value_t = 4)]
        beats_per_measure: u8,
        /// Meter denominator supplied by the caller; must be a power of two
        #[arg(long, default_value_t = 4)]
        beat_unit: u8,
        /// Optional JSON recognition and proposal-diagnostic report path
        #[arg(long)]
        report: Option<PathBuf>,
    },
    /// Evaluate a bounded OMR PNG recognition result against a reference score
    OmrEvaluate {
        /// Input high-contrast PNG score image
        input: PathBuf,
        /// Reference score in any supported input format, normally MSCZ
        expected: PathBuf,
        /// Minimum proposal confidence required before comparison
        #[arg(long, default_value_t = 0.9)]
        minimum_confidence: f32,
        /// Luminance at or below which an input pixel is treated as dark
        #[arg(long, default_value_t = 160)]
        darkness_threshold: u8,
        /// Required dark-pixel fraction for one detected staff line
        #[arg(long, default_value_t = 0.35)]
        minimum_staff_line_coverage: f32,
        /// Meter numerator supplied by the caller; not inferred from image pixels
        #[arg(long, default_value_t = 4)]
        beats_per_measure: u8,
        /// Meter denominator supplied by the caller; must be a power of two
        #[arg(long, default_value_t = 4)]
        beat_unit: u8,
        /// Optional JSON evaluation report path
        #[arg(long)]
        report: Option<PathBuf>,
    },
    /// Apply a reviewable OMR report JSON and write an MSCZ draft only when it is ready
    OmrApplyReport {
        /// JSON-serialized acorde-omr RecognitionReport from a host or provider
        input: PathBuf,
        /// Output MuseScore .mscz file; not written when review diagnostics are present
        output: PathBuf,
        /// Minimum proposal confidence required for automatic application
        #[arg(long, default_value_t = 0.9)]
        minimum_confidence: f32,
        /// Optional JSON application report path
        #[arg(long)]
        report: Option<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::Omr {
            input,
            output,
            minimum_confidence,
            darkness_threshold,
            minimum_staff_line_coverage,
            beats_per_measure,
            beat_unit,
            report,
        } => cmd_omr(
            input,
            output,
            *minimum_confidence,
            acorde_omr::RecognitionConfig {
                time_signature: acorde_core::TimeSignature {
                    numerator: *beats_per_measure,
                    denominator: *beat_unit,
                },
                darkness_threshold: *darkness_threshold,
                minimum_staff_line_coverage: *minimum_staff_line_coverage,
                ..acorde_omr::RecognitionConfig::default()
            },
            report.as_deref(),
        ),
        Commands::OmrEvaluate {
            input,
            expected,
            minimum_confidence,
            darkness_threshold,
            minimum_staff_line_coverage,
            beats_per_measure,
            beat_unit,
            report,
        } => cmd_omr_evaluate(
            input,
            expected,
            *minimum_confidence,
            acorde_omr::RecognitionConfig {
                time_signature: acorde_core::TimeSignature {
                    numerator: *beats_per_measure,
                    denominator: *beat_unit,
                },
                darkness_threshold: *darkness_threshold,
                minimum_staff_line_coverage: *minimum_staff_line_coverage,
                ..acorde_omr::RecognitionConfig::default()
            },
            report.as_deref(),
        ),
        Commands::OmrApplyReport {
            input,
            output,
            minimum_confidence,
            report,
        } => cmd_omr_apply_report(input, output, *minimum_confidence, report.as_deref()),
        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,
        staff_gap: 10.0,
        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,
        staff_gap: 10.0,
        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(())
}

#[derive(Debug, Serialize)]
struct OmrCliReport {
    contract_version: u32,
    source_path: String,
    output_path: String,
    recognized_systems: Vec<acorde_omr::DetectedStaffSystem>,
    recognition_diagnostics: Vec<acorde_omr::RecognitionDiagnostic>,
    proposal_diagnostics: Vec<acorde_core::OmrDiagnostic>,
    command_count: usize,
    ready: bool,
}

/// A machine-readable OMR outcome when image decoding or staff detection cannot produce a
/// proposal. This deliberately contains no partial score data: callers must not mistake a failed
/// image boundary for an editable draft.
#[derive(Debug, Serialize)]
struct OmrCliFailureReport {
    contract_version: u32,
    source_path: String,
    output_path: String,
    recognition_error: String,
    ready: bool,
}

/// A reproducible, score-level observation for one OMR image/reference pair.
///
/// This is deliberately an observation rather than an accuracy percentage: a caller must keep
/// the source image set, reference scores, and inclusion rules outside the CLI contract.
#[derive(Debug, Serialize)]
struct OmrEvaluationReport {
    contract_version: u32,
    source_path: String,
    expected_path: String,
    recognized_systems: Vec<acorde_omr::DetectedStaffSystem>,
    recognition_diagnostics: Vec<acorde_omr::RecognitionDiagnostic>,
    proposal_diagnostics: Vec<acorde_core::OmrDiagnostic>,
    command_count: usize,
    ready: bool,
    compared: bool,
    recognition_error: Option<String>,
    expected_statistics: Option<acorde_core::ScoreStats>,
    recognized_statistics: Option<acorde_core::ScoreStats>,
    semantic_change_count: Option<usize>,
    semantic_equivalent: Option<bool>,
}

fn write_omr_failure_report(
    input: &Path,
    output: &Path,
    report_path: Option<&Path>,
    recognition_error: &str,
) -> Result<(), String> {
    let Some(path) = report_path else {
        return Ok(());
    };
    let report = OmrCliFailureReport {
        contract_version: acorde_core::OMR_PROPOSAL_CONTRACT_VERSION,
        source_path: input.display().to_string(),
        output_path: output.display().to_string(),
        recognition_error: recognition_error.to_string(),
        ready: false,
    };
    let report_json = serde_json::to_string_pretty(&report)
        .map_err(|error| format!("cannot serialize OMR failure report: {error}"))?;
    std::fs::write(path, report_json)
        .map_err(|error| format!("cannot write '{}': {error}", path.display()))
}

fn cmd_omr(
    input: &Path,
    output: &Path,
    minimum_confidence: f32,
    recognition_config: acorde_omr::RecognitionConfig,
    report_path: Option<&Path>,
) -> Result<(), String> {
    let output_is_mscz = output
        .extension()
        .and_then(|extension| extension.to_str())
        .is_some_and(|extension| extension.eq_ignore_ascii_case("mscz"));
    if !output_is_mscz {
        return Err("OMR output must use the .mscz extension".to_string());
    }
    let image_size = std::fs::metadata(input)
        .map_err(|error| format!("cannot inspect '{}': {error}", input.display()))?
        .len();
    if image_size > acorde_omr::MAX_PNG_BYTES as u64 {
        return Err(format!(
            "image exceeds the {}-byte OMR input limit",
            acorde_omr::MAX_PNG_BYTES
        ));
    }
    let image = std::fs::read(input)
        .map_err(|error| format!("cannot read '{}': {error}", input.display()))?;
    let recognition = match acorde_omr::recognize_png(&image, &recognition_config) {
        Ok(recognition) => recognition,
        Err(error) => {
            let message = error.to_string();
            write_omr_failure_report(input, output, report_path, &message)?;
            return Err(format!("cannot recognize '{}': {message}", input.display()));
        }
    };
    let plan = recognition.command_plan(minimum_confidence);
    let ready = plan.is_ready() && recognition.diagnostics.is_empty();
    let output_report = OmrCliReport {
        contract_version: acorde_core::OMR_PROPOSAL_CONTRACT_VERSION,
        source_path: input.display().to_string(),
        output_path: output.display().to_string(),
        recognized_systems: recognition.systems.clone(),
        recognition_diagnostics: recognition.diagnostics.clone(),
        proposal_diagnostics: plan.diagnostics.clone(),
        command_count: plan.commands.len(),
        ready,
    };
    let report_json = serde_json::to_string_pretty(&output_report)
        .map_err(|error| format!("cannot serialize OMR report: {error}"))?;
    if let Some(path) = report_path {
        std::fs::write(path, &report_json)
            .map_err(|error| format!("cannot write '{}': {error}", path.display()))?;
    }
    if !ready {
        println!("{report_json}");
        return Err("OMR result requires review; no .mscz file was written".to_string());
    }
    let mut engine = ScoreEngine::new();
    engine.replace_score(recognition.draft);
    engine
        .batch_apply_labeled(plan.commands, "ApplyOMR")
        .map_err(|error| format!("cannot apply OMR proposal: {error}"))?;
    write_score(&engine.score, output)?;
    println!("{report_json}");
    println!("wrote '{}'", output.display());
    Ok(())
}

fn cmd_omr_apply_report(
    input: &Path,
    output: &Path,
    minimum_confidence: f32,
    report_path: Option<&Path>,
) -> Result<(), String> {
    let output_is_mscz = output
        .extension()
        .and_then(|extension| extension.to_str())
        .is_some_and(|extension| extension.eq_ignore_ascii_case("mscz"));
    if !output_is_mscz {
        return Err("OMR output must use the .mscz extension".to_string());
    }
    let report_size = std::fs::metadata(input)
        .map_err(|error| format!("cannot inspect '{}': {error}", input.display()))?
        .len();
    if report_size > MAX_OMR_REPORT_BYTES as u64 {
        return Err(format!(
            "OMR report exceeds the {}-byte input limit",
            MAX_OMR_REPORT_BYTES
        ));
    }
    let source = std::fs::read(input)
        .map_err(|error| format!("cannot read '{}': {error}", input.display()))?;
    let recognition: acorde_omr::RecognitionReport = match serde_json::from_slice(&source) {
        Ok(recognition) => recognition,
        Err(error) => {
            let message = format!("cannot parse OMR report: {error}");
            write_omr_failure_report(input, output, report_path, &message)?;
            return Err(format!("{message} in '{}'", input.display()));
        }
    };
    let plan = recognition.command_plan(minimum_confidence);
    let ready = plan.is_ready() && recognition.diagnostics.is_empty();
    let output_report = OmrCliReport {
        contract_version: acorde_core::OMR_PROPOSAL_CONTRACT_VERSION,
        source_path: input.display().to_string(),
        output_path: output.display().to_string(),
        recognized_systems: recognition.systems.clone(),
        recognition_diagnostics: recognition.diagnostics.clone(),
        proposal_diagnostics: plan.diagnostics.clone(),
        command_count: plan.commands.len(),
        ready,
    };
    let report_json = serde_json::to_string_pretty(&output_report)
        .map_err(|error| format!("cannot serialize OMR application report: {error}"))?;
    if let Some(path) = report_path {
        std::fs::write(path, &report_json)
            .map_err(|error| format!("cannot write '{}': {error}", path.display()))?;
    }
    if !ready {
        println!("{report_json}");
        return Err("OMR report requires review; no .mscz file was written".to_string());
    }
    let mut engine = ScoreEngine::new();
    engine.replace_score(recognition.draft);
    engine
        .batch_apply_labeled(plan.commands, "ApplyOMR")
        .map_err(|error| format!("cannot apply OMR proposal: {error}"))?;
    write_score(&engine.score, output)?;
    println!("{report_json}");
    println!("wrote '{}'", output.display());
    Ok(())
}

fn write_omr_evaluation_report(
    report_path: Option<&Path>,
    report: &OmrEvaluationReport,
) -> Result<String, String> {
    let report_json = serde_json::to_string_pretty(report)
        .map_err(|error| format!("cannot serialize OMR evaluation report: {error}"))?;
    if let Some(path) = report_path {
        std::fs::write(path, &report_json)
            .map_err(|error| format!("cannot write '{}': {error}", path.display()))?;
    }
    Ok(report_json)
}

fn cmd_omr_evaluate(
    input: &Path,
    expected: &Path,
    minimum_confidence: f32,
    recognition_config: acorde_omr::RecognitionConfig,
    report_path: Option<&Path>,
) -> Result<(), String> {
    let image_size = std::fs::metadata(input)
        .map_err(|error| format!("cannot inspect '{}': {error}", input.display()))?
        .len();
    if image_size > acorde_omr::MAX_PNG_BYTES as u64 {
        return Err(format!(
            "image exceeds the {}-byte OMR input limit",
            acorde_omr::MAX_PNG_BYTES
        ));
    }
    let image = std::fs::read(input)
        .map_err(|error| format!("cannot read '{}': {error}", input.display()))?;
    let recognition = match acorde_omr::recognize_png(&image, &recognition_config) {
        Ok(recognition) => recognition,
        Err(error) => {
            let report = OmrEvaluationReport {
                contract_version: acorde_core::OMR_PROPOSAL_CONTRACT_VERSION,
                source_path: input.display().to_string(),
                expected_path: expected.display().to_string(),
                recognized_systems: Vec::new(),
                recognition_diagnostics: Vec::new(),
                proposal_diagnostics: Vec::new(),
                command_count: 0,
                ready: false,
                compared: false,
                recognition_error: Some(error.to_string()),
                expected_statistics: None,
                recognized_statistics: None,
                semantic_change_count: None,
                semantic_equivalent: None,
            };
            let report_json = write_omr_evaluation_report(report_path, &report)?;
            println!("{report_json}");
            return Err(format!("cannot recognize '{}': {error}", input.display()));
        }
    };

    let plan = recognition.command_plan(minimum_confidence);
    let ready = plan.is_ready() && recognition.diagnostics.is_empty();
    if !ready {
        let report = OmrEvaluationReport {
            contract_version: acorde_core::OMR_PROPOSAL_CONTRACT_VERSION,
            source_path: input.display().to_string(),
            expected_path: expected.display().to_string(),
            recognized_systems: recognition.systems,
            recognition_diagnostics: recognition.diagnostics,
            proposal_diagnostics: plan.diagnostics,
            command_count: plan.commands.len(),
            ready: false,
            compared: false,
            recognition_error: None,
            expected_statistics: None,
            recognized_statistics: None,
            semantic_change_count: None,
            semantic_equivalent: None,
        };
        let report_json = write_omr_evaluation_report(report_path, &report)?;
        println!("{report_json}");
        return Err("OMR result requires review; no score comparison was made".to_string());
    }

    let command_count = plan.commands.len();
    let expected_score = parse_score(expected)?;
    let mut engine = ScoreEngine::new();
    engine.replace_score(recognition.draft);
    engine
        .batch_apply_labeled(plan.commands, "ApplyOMR")
        .map_err(|error| format!("cannot apply OMR proposal: {error}"))?;
    let changes = acorde_core::diff(&expected_score, &engine.score);
    let equivalent = changes.is_empty();
    let report = OmrEvaluationReport {
        contract_version: acorde_core::OMR_PROPOSAL_CONTRACT_VERSION,
        source_path: input.display().to_string(),
        expected_path: expected.display().to_string(),
        recognized_systems: recognition.systems,
        recognition_diagnostics: recognition.diagnostics,
        proposal_diagnostics: plan.diagnostics,
        command_count,
        ready: true,
        compared: true,
        recognition_error: None,
        expected_statistics: Some(expected_score.statistics()),
        recognized_statistics: Some(engine.score.statistics()),
        semantic_change_count: Some(changes.len()),
        semantic_equivalent: Some(equivalent),
    };
    let report_json = write_omr_evaluation_report(report_path, &report)?;
    println!("{report_json}");
    if equivalent {
        Ok(())
    } else {
        Err("OMR recognition differs from the reference score".to_string())
    }
}

// ── 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
            ),
            acorde_core::ValidationWarning::OutOfRange {
                part_index,
                staff_index,
                measure_index,
                note_index,
                pitch_midi,
                instrument_range,
            } => eprintln!(
                "warning: 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
            ),
        }
    }
    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)
        && 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::*;
    use std::process::Command as ProcessCommand;

    fn set_black(pixels: &mut [u8], width: u32, x: u32, y: u32) {
        pixels[y as usize * width as usize + x as usize] = 0;
    }

    fn write_synthetic_omr_png(path: &Path) {
        let (width, height) = (240, 100);
        let mut pixels = vec![255; width as usize * height as usize];
        for y in [30, 40, 50, 60, 70] {
            for x in 10..=230 {
                set_black(&mut pixels, width, x, y);
            }
        }
        for x in [10, 120, 230] {
            for y in 30..=70 {
                set_black(&mut pixels, width, x, y);
            }
        }
        for (center_x, center_y) in [(65, 55), (175, 55)] {
            for y in center_y - 3..=center_y + 3 {
                for x in center_x - 5..=center_x + 5 {
                    let dx = x as i32 - center_x as i32;
                    let dy = y as i32 - center_y as i32;
                    if dx * dx * 2 + dy * dy * 5 <= 45 {
                        set_black(&mut pixels, width, x, y);
                    }
                }
            }
        }
        let file = std::fs::File::create(path).expect("temporary PNG is writable");
        let mut encoder = png::Encoder::new(file, width, height);
        encoder.set_color(png::ColorType::Grayscale);
        encoder.set_depth(png::BitDepth::Eight);
        let mut writer = encoder.write_header().expect("PNG header is writable");
        writer
            .write_image_data(&pixels)
            .expect("PNG image data is writable");
    }

    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 omr_command_writes_a_reparsable_mscz_only_when_the_plan_is_ready() {
        let stem = format!("acorde-cli-omr-{}", std::process::id());
        let input = std::env::temp_dir().join(format!("{stem}.png"));
        let output = std::env::temp_dir().join(format!("{stem}.mscz"));
        let report = std::env::temp_dir().join(format!("{stem}.json"));
        write_synthetic_omr_png(&input);
        cmd_omr(
            &input,
            &output,
            0.9,
            acorde_omr::RecognitionConfig::default(),
            Some(&report),
        )
        .expect("OMR conversion succeeds");
        let reparsed = acorde_io::parse_mscz(&std::fs::read(&output).expect("MSCZ exists"))
            .expect("OMR MSCZ reparses");
        assert_eq!(reparsed.parts[0].staves[0].measures.len(), 2);
        let report_json = std::fs::read_to_string(&report).expect("OMR report exists");
        assert!(report_json.contains("\"ready\": true"));
        std::fs::remove_file(input).expect("temporary PNG is removable");
        std::fs::remove_file(output).expect("temporary MSCZ is removable");
        std::fs::remove_file(report).expect("temporary report is removable");
    }

    #[test]
    fn omr_command_writes_a_failure_report_without_writing_mscz() {
        let stem = format!("acorde-cli-omr-failure-{}", std::process::id());
        let input = std::env::temp_dir().join(format!("{stem}.png"));
        let output = std::env::temp_dir().join(format!("{stem}.mscz"));
        let report = std::env::temp_dir().join(format!("{stem}.json"));
        let file = std::fs::File::create(&input).expect("temporary PNG is writable");
        let mut encoder = png::Encoder::new(file, 16, 16);
        encoder.set_color(png::ColorType::Grayscale);
        encoder.set_depth(png::BitDepth::Eight);
        let mut writer = encoder.write_header().expect("PNG header is writable");
        writer
            .write_image_data(&vec![255; 16 * 16])
            .expect("PNG image data is writable");
        drop(writer);

        let error = cmd_omr(
            &input,
            &output,
            0.9,
            acorde_omr::RecognitionConfig::default(),
            Some(&report),
        )
        .expect_err("staff-free image must be rejected");
        assert!(error.contains("no five-line staff"), "{error}");
        assert!(!output.exists());
        let report_json = std::fs::read_to_string(&report).expect("failure report exists");
        assert!(report_json.contains("\"ready\": false"));
        assert!(report_json.contains("\"recognition_error\""));
        std::fs::remove_file(input).expect("temporary PNG is removable");
        std::fs::remove_file(report).expect("temporary report is removable");
    }

    #[test]
    fn omr_evaluate_compares_an_accepted_image_with_a_reference_mscz() {
        let stem = format!("acorde-cli-omr-evaluate-{}", std::process::id());
        let input = std::env::temp_dir().join(format!("{stem}.png"));
        let expected = std::env::temp_dir().join(format!("{stem}.mscz"));
        let conversion_report = std::env::temp_dir().join(format!("{stem}-conversion.json"));
        let evaluation_report = std::env::temp_dir().join(format!("{stem}-evaluation.json"));
        write_synthetic_omr_png(&input);
        cmd_omr(
            &input,
            &expected,
            0.9,
            acorde_omr::RecognitionConfig::default(),
            Some(&conversion_report),
        )
        .expect("synthetic OMR conversion succeeds");

        cmd_omr_evaluate(
            &input,
            &expected,
            0.9,
            acorde_omr::RecognitionConfig::default(),
            Some(&evaluation_report),
        )
        .expect("same image and reference are equivalent");
        let report_json =
            std::fs::read_to_string(&evaluation_report).expect("evaluation report exists");
        assert!(report_json.contains("\"compared\": true"));
        assert!(report_json.contains("\"semantic_equivalent\": true"));

        std::fs::remove_file(input).expect("temporary PNG is removable");
        std::fs::remove_file(expected).expect("temporary MSCZ is removable");
        std::fs::remove_file(conversion_report).expect("temporary conversion report is removable");
        std::fs::remove_file(evaluation_report).expect("temporary evaluation report is removable");
    }

    #[test]
    fn omr_apply_report_writes_a_reparsable_mscz_for_a_ready_provider_report() {
        let stem = format!("acorde-cli-omr-apply-report-{}", std::process::id());
        let input = std::env::temp_dir().join(format!("{stem}.png"));
        let provider_report = std::env::temp_dir().join(format!("{stem}-provider.json"));
        let output = std::env::temp_dir().join(format!("{stem}.mscz"));
        let application_report = std::env::temp_dir().join(format!("{stem}-application.json"));
        write_synthetic_omr_png(&input);
        let recognition = acorde_omr::recognize_png(
            &std::fs::read(&input).expect("synthetic PNG is readable"),
            &acorde_omr::RecognitionConfig::default(),
        )
        .expect("synthetic PNG is recognized");
        std::fs::write(
            &provider_report,
            serde_json::to_vec(&recognition).expect("recognition report serializes"),
        )
        .expect("provider report is writable");

        cmd_omr_apply_report(&provider_report, &output, 0.9, Some(&application_report))
            .expect("ready provider report applies");
        acorde_io::parse_mscz(&std::fs::read(&output).expect("MSCZ exists"))
            .expect("provider-applied MSCZ reparses");
        let report_json =
            std::fs::read_to_string(&application_report).expect("application report exists");
        assert!(report_json.contains("\"ready\": true"));

        std::fs::remove_file(input).expect("temporary PNG is removable");
        std::fs::remove_file(provider_report).expect("temporary provider report is removable");
        std::fs::remove_file(output).expect("temporary MSCZ is removable");
        std::fs::remove_file(application_report)
            .expect("temporary application report is removable");
    }

    #[test]
    fn omr_apply_report_records_malformed_json_without_writing_mscz() {
        let stem = format!("acorde-cli-omr-apply-report-invalid-{}", std::process::id());
        let input = std::env::temp_dir().join(format!("{stem}.json"));
        let output = std::env::temp_dir().join(format!("{stem}.mscz"));
        let report = std::env::temp_dir().join(format!("{stem}-application.json"));
        std::fs::write(&input, b"not a recognition report").expect("invalid report is writable");

        let error = cmd_omr_apply_report(&input, &output, 0.9, Some(&report))
            .expect_err("malformed provider report must be rejected");
        assert!(error.contains("cannot parse OMR report"), "{error}");
        assert!(!output.exists());
        let report_json = std::fs::read_to_string(&report).expect("failure report exists");
        assert!(report_json.contains("\"ready\": false"));
        assert!(report_json.contains("\"recognition_error\""));

        std::fs::remove_file(input).expect("temporary input is removable");
        std::fs::remove_file(report).expect("temporary application report is removable");
    }

    #[test]
    #[ignore = "requires MuseScore Studio; set ACORDE_MUSESCORE_BIN to its mscore executable"]
    fn omr_output_reopens_in_musescore_and_exports_parseable_musicxml() {
        let musescore = std::env::var_os("ACORDE_MUSESCORE_BIN")
            .map(PathBuf::from)
            .expect("set ACORDE_MUSESCORE_BIN to the MuseScore mscore executable");
        let stem = format!("acorde-cli-omr-musescore-{}", std::process::id());
        let input = std::env::temp_dir().join(format!("{stem}.png"));
        let mscz = std::env::temp_dir().join(format!("{stem}.mscz"));
        let omr_report = std::env::temp_dir().join(format!("{stem}-omr.json"));
        let musicxml = std::env::temp_dir().join(format!("{stem}.musicxml"));
        let muse_home = std::env::temp_dir().join(format!("{stem}-musescore-home"));
        std::fs::create_dir_all(&muse_home).expect("isolated MuseScore home is writable");
        write_synthetic_omr_png(&input);
        cmd_omr(
            &input,
            &mscz,
            0.9,
            acorde_omr::RecognitionConfig::default(),
            Some(&omr_report),
        )
        .expect("synthetic OMR conversion succeeds");

        let status = ProcessCommand::new(&musescore)
            .arg("-F")
            .arg("-o")
            .arg(&musicxml)
            .arg(&mscz)
            .env("HOME", &muse_home)
            .env("XDG_CONFIG_HOME", &muse_home)
            .env("XDG_DATA_HOME", &muse_home)
            .status()
            .expect("MuseScore process starts");
        let reparsed = status.success().then(|| parse_score(&musicxml));

        std::fs::remove_file(input).expect("temporary PNG is removable");
        std::fs::remove_file(mscz).expect("temporary MSCZ is removable");
        std::fs::remove_file(omr_report).expect("temporary OMR report is removable");
        if musicxml.exists() {
            std::fs::remove_file(&musicxml).expect("temporary MusicXML is removable");
        }
        std::fs::remove_dir_all(muse_home).expect("isolated MuseScore home is removable");
        assert!(status.success(), "MuseScore exited with {status}");
        let reparsed = reparsed
            .expect("MuseScore must produce a reparseable output on success")
            .expect("MuseScore MusicXML output reparses");
        assert_eq!(reparsed.parts[0].staves[0].measures.len(), 2);
    }

    #[test]
    fn omr_evaluate_records_a_withheld_image_without_comparing_the_reference() {
        let stem = format!("acorde-cli-omr-evaluate-withheld-{}", std::process::id());
        let input = std::env::temp_dir().join(format!("{stem}.png"));
        let absent_reference = std::env::temp_dir().join(format!("{stem}-missing.mscz"));
        let report = std::env::temp_dir().join(format!("{stem}.json"));
        let file = std::fs::File::create(&input).expect("temporary PNG is writable");
        let mut encoder = png::Encoder::new(file, 16, 16);
        encoder.set_color(png::ColorType::Grayscale);
        encoder.set_depth(png::BitDepth::Eight);
        let mut writer = encoder.write_header().expect("PNG header is writable");
        writer
            .write_image_data(&vec![255; 16 * 16])
            .expect("PNG image data is writable");
        drop(writer);

        let error = cmd_omr_evaluate(
            &input,
            &absent_reference,
            0.9,
            acorde_omr::RecognitionConfig::default(),
            Some(&report),
        )
        .expect_err("staff-free image must be withheld before reference parsing");
        assert!(error.contains("no five-line staff"), "{error}");
        let report_json = std::fs::read_to_string(&report).expect("withheld report exists");
        assert!(report_json.contains("\"ready\": false"));
        assert!(report_json.contains("\"compared\": false"));
        assert!(report_json.contains("\"recognition_error\""));

        std::fs::remove_file(input).expect("temporary PNG is removable");
        std::fs::remove_file(report).expect("temporary report is removable");
    }

    #[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"));
    }
}