chordsketch-chordpro 0.5.0

ChordPro parser, AST, and transforms
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
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
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
//! Parser that transforms a token stream into a ChordPro AST.
//!
//! The parser accepts the flat token sequence produced by [`crate::Lexer`] and
//! builds a [`Song`] AST. Each source line is classified as a directive, a
//! lyrics line (with optional inline chord annotations), an empty line, or a
//! comment (from `{comment}`, `{comment_italic}`, `{comment_box}` directives,
//! or file-level `#` comment lines).
//!
//! # Directive Classification
//!
//! Directives are classified into typed variants via [`DirectiveKind`]. The
//! parser resolves short aliases (e.g., `t` → `title`, `soc` →
//! `start_of_chorus`) and normalizes names to their canonical lowercase form.
//! Metadata directives automatically populate the [`Song::metadata`] fields.
//!
//! # Convenience Function
//!
//! The [`parse`] function combines lexing and parsing into a single step:
//!
//! ```
//! use chordsketch_chordpro::parser::parse;
//!
//! let song = parse("{title: Hello}\n[Am]World").unwrap();
//! assert_eq!(song.metadata.title.as_deref(), Some("Hello"));
//! assert_eq!(song.lines.len(), 2);
//! ```
//!
//! # Error Handling
//!
//! The parser returns [`ParseError`] when the token stream contains structural
//! problems such as unclosed directives, unclosed chords, or empty directives.

use crate::Lexer;
use crate::ast::{
    Chord, CommentStyle, Directive, DirectiveKind, ImageAttributes, Line, LyricsLine,
    LyricsSegment, Song,
};
use crate::inline_markup;
use crate::token::{Position, Span, Token, TokenKind};

// ---------------------------------------------------------------------------
// ParseError
// ---------------------------------------------------------------------------

/// An error encountered during parsing.
///
/// Each error carries a human-readable message and the [`Span`] in the source
/// text where the problem was detected.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
    /// A description of what went wrong.
    pub message: String,
    /// The location in the source text where the error was detected.
    pub span: Span,
}

impl ParseError {
    /// Creates a new `ParseError` with the given message and span.
    fn new(message: impl Into<String>, span: Span) -> Self {
        Self {
            message: message.into(),
            span,
        }
    }

    /// Returns the 1-based line number where the error was detected.
    #[must_use]
    pub fn line(&self) -> usize {
        self.span.start.line
    }

    /// Returns the 1-based column number where the error was detected.
    #[must_use]
    pub fn column(&self) -> usize {
        self.span.start.column
    }
}

impl core::fmt::Display for ParseError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "parse error at line {}, column {}: {}",
            self.span.start.line, self.span.start.column, self.message
        )
    }
}

impl std::error::Error for ParseError {}

// ---------------------------------------------------------------------------
// ParseResult
// ---------------------------------------------------------------------------

/// The result of a lenient parse, containing a partial AST and any errors.
///
/// When using [`Parser::parse_lenient`] or [`parse_lenient`], the parser
/// recovers from errors by skipping problematic lines and continuing.
/// The `song` field contains all successfully parsed lines, and `errors`
/// contains all problems encountered.
///
/// # Examples
///
/// ```
/// use chordsketch_chordpro::parser::parse_lenient;
///
/// let result = parse_lenient("{title: Test}\n[Am\nHello world");
/// assert_eq!(result.song.metadata.title.as_deref(), Some("Test"));
/// assert_eq!(result.errors.len(), 1); // unclosed chord on line 2
/// assert_eq!(result.song.lines.len(), 2); // title directive + lyrics (error line skipped)
/// ```
#[derive(Debug, Clone)]
pub struct ParseResult {
    /// The partial AST with all successfully parsed lines.
    pub song: Song,
    /// All errors encountered during parsing.
    pub errors: Vec<ParseError>,
}

impl ParseResult {
    /// Returns `true` if no errors were encountered.
    #[must_use]
    pub fn is_ok(&self) -> bool {
        self.errors.is_empty()
    }

    /// Returns `true` if any errors were encountered.
    #[must_use]
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }
}

// ---------------------------------------------------------------------------
// Parser
// ---------------------------------------------------------------------------

/// A parser that transforms a token stream into a [`Song`] AST.
///
/// The parser is created from a `Vec<Token>` (typically produced by
/// [`Lexer::tokenize`]) and consumes tokens one at a time, building up the
/// AST line by line.
pub struct Parser {
    /// The token stream to consume.
    tokens: Vec<Token>,
    /// Current index into `tokens`.
    pos: usize,
    /// When inside a verbatim section (tab, grid, ABC, Lilypond, SVG, textblock),
    /// this holds the end-directive name that will close the section.
    /// Lines inside verbatim sections are treated as plain text (no chord parsing).
    verbatim_end: Option<String>,
}

impl Parser {
    /// Creates a new parser for the given token stream.
    ///
    /// Prefer [`Parser::try_new`] when the token vector may come from
    /// untrusted or indirect sources — it returns `Err` instead of
    /// panicking on an empty vector.
    ///
    /// # Panics
    ///
    /// Panics if `tokens` is empty. The lexer always appends an
    /// [`Eof`](crate::token::TokenKind::Eof) token, so a well-formed
    /// token stream is never empty, and reaching this panic indicates
    /// a caller bug rather than a user-facing input error.
    #[must_use]
    pub fn new(tokens: Vec<Token>) -> Self {
        Self::try_new(tokens).expect("token list must contain at least an Eof token")
    }

    /// Creates a new parser for the given token stream, returning an
    /// error if the stream is empty.
    ///
    /// This is the non-panicking counterpart of [`Parser::new`]. The
    /// lexer always appends an [`Eof`](crate::token::TokenKind::Eof)
    /// token, so a well-formed token stream is never empty; this entry
    /// point surfaces the violation as a `ParseError` instead of a panic,
    /// so callers that construct token vectors by hand (e.g. LSP or
    /// fuzzing harnesses) can recover without aborting.
    ///
    /// # Errors
    ///
    /// Returns a `ParseError` located at line 1, column 1 if `tokens`
    /// is empty.
    #[must_use = "callers must handle the empty-token error"]
    pub fn try_new(tokens: Vec<Token>) -> Result<Self, ParseError> {
        if tokens.is_empty() {
            return Err(ParseError::new(
                "empty token list — expected at least an Eof token",
                Span::new(Position::new(1, 1), Position::new(1, 1)),
            ));
        }
        Ok(Self {
            tokens,
            pos: 0,
            verbatim_end: None,
        })
    }

    /// Parses the token stream and returns a [`Song`] AST.
    ///
    /// Metadata directives (`{title}`, `{artist}`, etc.) automatically
    /// populate [`Song::metadata`]. Comment directives are converted to
    /// [`Line::Comment`] with the appropriate [`CommentStyle`].
    ///
    /// Returns a [`ParseError`] on the first structural problem encountered
    /// (e.g., unclosed directives or chords). Use [`parse_lenient`] to
    /// collect all errors and obtain a partial AST.
    #[must_use = "callers must handle the parse result"]
    pub fn parse(mut self) -> Result<Song, ParseError> {
        let mut song = Song::new();

        while !self.is_at_end() {
            let line = self.parse_line()?;

            // If this is a metadata directive without a selector, populate
            // the Song's metadata. Selector-bearing directives are deferred
            // to filter_song(), which re-derives metadata after filtering.
            if let Line::Directive(ref directive) = line {
                if directive.selector.is_none() {
                    Self::populate_metadata(&mut song.metadata, directive);
                }
            }

            song.lines.push(line);
        }

        song.apply_define_displays();
        Ok(song)
    }

    /// Parses the token stream leniently, collecting all errors.
    ///
    /// Unlike [`parse`], this method does not stop at the first error.
    /// When a line cannot be parsed, the error is recorded and the parser
    /// skips to the next line to continue. The returned [`ParseResult`]
    /// contains the partial AST (all successfully parsed lines) and a
    /// list of all errors encountered.
    #[must_use = "callers must handle the parse result"]
    pub fn parse_lenient(self) -> ParseResult {
        self.parse_lenient_limited(0)
    }

    /// Like [`parse_lenient`](Self::parse_lenient), but stops collecting errors
    /// after `max_errors` have been recorded. Set to `0` to disable the limit.
    #[must_use = "callers must handle the parse result"]
    pub fn parse_lenient_limited(mut self, max_errors: usize) -> ParseResult {
        let mut song = Song::new();
        let mut errors = Vec::new();

        while !self.is_at_end() {
            match self.parse_line() {
                Ok(line) => {
                    if let Line::Directive(ref directive) = line {
                        if directive.selector.is_none() {
                            Self::populate_metadata(&mut song.metadata, directive);
                        }
                    }
                    song.lines.push(line);
                }
                Err(e) => {
                    if max_errors == 0 || errors.len() < max_errors {
                        errors.push(e);
                    }
                    // Skip to the next line to recover.
                    self.skip_to_next_line();
                }
            }
        }

        song.apply_define_displays();
        ParseResult { song, errors }
    }

    /// Advances past all tokens until the next Newline or Eof,
    /// then consumes the Newline if present. Used for error recovery.
    fn skip_to_next_line(&mut self) {
        while !self.is_at_end() {
            if self.peek_kind() == &TokenKind::Newline {
                self.advance();
                return;
            }
            self.advance();
        }
    }

    // -- Metadata population ------------------------------------------------

    /// Maximum number of entries per multi-value metadata field (e.g.,
    /// subtitles, artists). Entries beyond this limit are silently dropped
    /// to prevent resource exhaustion from maliciously crafted input.
    const MAX_METADATA_ENTRIES: usize = 1000;

    /// Push a value onto a multi-value metadata field if the cap has not
    /// been reached.
    fn push_if_under_cap<T>(vec: &mut Vec<T>, value: T) {
        if vec.len() < Self::MAX_METADATA_ENTRIES {
            vec.push(value);
        }
    }

    /// Populate metadata fields from a directive's kind and value.
    ///
    /// This is called during parsing for unselectored directives, and again
    /// by [`SelectorContext::filter_song`](crate::selector::SelectorContext::filter_song)
    /// after filtering to re-derive metadata from matching selector-bearing directives.
    pub fn populate_metadata(metadata: &mut crate::ast::Metadata, directive: &Directive) {
        let value = match directive.value.as_deref() {
            Some(v) => v.to_string(),
            None => return, // Metadata directives without values are no-ops.
        };

        match directive.kind {
            DirectiveKind::Title => {
                metadata.title = Some(value);
            }
            DirectiveKind::Subtitle => {
                Self::push_if_under_cap(&mut metadata.subtitles, value);
            }
            DirectiveKind::Artist => {
                Self::push_if_under_cap(&mut metadata.artists, value);
            }
            DirectiveKind::Composer => {
                Self::push_if_under_cap(&mut metadata.composers, value);
            }
            DirectiveKind::Lyricist => {
                Self::push_if_under_cap(&mut metadata.lyricists, value);
            }
            DirectiveKind::Album => {
                metadata.album = Some(value);
            }
            DirectiveKind::Year => {
                metadata.year = Some(value);
            }
            DirectiveKind::Key => {
                Self::push_if_under_cap(&mut metadata.keys, value.clone());
                metadata.key = Some(value);
            }
            DirectiveKind::Tempo => {
                Self::push_if_under_cap(&mut metadata.tempos, value.clone());
                metadata.tempo = Some(value);
            }
            DirectiveKind::Time => {
                Self::push_if_under_cap(&mut metadata.times, value.clone());
                metadata.time = Some(value);
            }
            DirectiveKind::Capo => {
                metadata.capo = Some(value);
            }
            DirectiveKind::SortTitle => {
                metadata.sort_title = Some(value);
            }
            DirectiveKind::SortArtist => {
                metadata.sort_artist = Some(value);
            }
            DirectiveKind::Arranger => {
                Self::push_if_under_cap(&mut metadata.arrangers, value);
            }
            DirectiveKind::Copyright => {
                metadata.copyright = Some(value);
            }
            DirectiveKind::Duration => {
                metadata.duration = Some(value);
            }
            DirectiveKind::Tag => {
                Self::push_if_under_cap(&mut metadata.tags, value);
            }
            DirectiveKind::Meta(ref key) => match key.to_ascii_lowercase().as_str() {
                "title" | "t" => metadata.title = Some(value),
                "subtitle" | "st" => Self::push_if_under_cap(&mut metadata.subtitles, value),
                "artist" => Self::push_if_under_cap(&mut metadata.artists, value),
                "composer" => Self::push_if_under_cap(&mut metadata.composers, value),
                "lyricist" => Self::push_if_under_cap(&mut metadata.lyricists, value),
                "album" => metadata.album = Some(value),
                "year" => metadata.year = Some(value),
                "key" => {
                    Self::push_if_under_cap(&mut metadata.keys, value.clone());
                    metadata.key = Some(value);
                }
                "tempo" => {
                    Self::push_if_under_cap(&mut metadata.tempos, value.clone());
                    metadata.tempo = Some(value);
                }
                "time" => {
                    Self::push_if_under_cap(&mut metadata.times, value.clone());
                    metadata.time = Some(value);
                }
                "capo" => metadata.capo = Some(value),
                "sorttitle" => metadata.sort_title = Some(value),
                "sortartist" => metadata.sort_artist = Some(value),
                "arranger" => Self::push_if_under_cap(&mut metadata.arrangers, value),
                "copyright" => metadata.copyright = Some(value),
                "duration" => metadata.duration = Some(value),
                "tag" => Self::push_if_under_cap(&mut metadata.tags, value),
                _ => Self::push_if_under_cap(&mut metadata.custom, (key.clone(), value)),
            },
            DirectiveKind::Unknown(ref name) => {
                Self::push_if_under_cap(&mut metadata.custom, (name.clone(), value));
            }
            _ => {}
        }
    }

    // -- Token navigation ---------------------------------------------------

    /// Returns `true` when all meaningful tokens have been consumed.
    fn is_at_end(&self) -> bool {
        self.pos >= self.tokens.len() || self.peek_kind() == &TokenKind::Eof
    }

    /// Returns a reference to the current token's kind without advancing.
    fn peek_kind(&self) -> &TokenKind {
        self.tokens
            .get(self.pos)
            .map(|t| &t.kind)
            .unwrap_or(&TokenKind::Eof)
    }

    /// Returns a reference to the current token without advancing.
    fn peek(&self) -> &Token {
        // SAFETY: the caller ensures we are not past the end. The last token
        // is always Eof, so indexing is safe as long as `pos < tokens.len()`.
        &self.tokens[self.pos]
    }

    /// Advances past the current token and returns it.
    fn advance(&mut self) -> &Token {
        let tok = &self.tokens[self.pos];
        self.pos += 1;
        tok
    }

    // -- Line parsing -------------------------------------------------------

    /// Parses a single line (up to and including the next Newline or Eof).
    fn parse_line(&mut self) -> Result<Line, ParseError> {
        let in_verbatim = self.verbatim_end.is_some();

        match self.peek_kind() {
            // An empty line: just a Newline token.
            TokenKind::Newline => {
                self.advance();
                Ok(Line::Empty)
            }
            // A directive line: starts with `{`.
            TokenKind::DirectiveOpen => {
                // Inside a verbatim section: only the matching end directive
                // is parsed; everything else is verbatim text.
                if in_verbatim && !self.is_verbatim_end_ahead() {
                    return self.parse_verbatim_line();
                }
                let line = self.parse_directive_line()?;
                // Track verbatim section state.
                if let Line::Directive(ref d) = line {
                    if let Some(end_name) = Self::verbatim_end_for(&d.kind) {
                        self.verbatim_end = Some(end_name);
                    } else if d.kind.is_section_end() && in_verbatim {
                        self.verbatim_end = None;
                    }
                }
                Ok(line)
            }
            // Inside a verbatim section: treat as plain text (no chord parsing).
            _ if in_verbatim => self.parse_verbatim_line(),
            // File-level `#` comment: first text token starts with `#` at
            // column 1 (no leading whitespace). The ChordPro spec says "a line
            // starting with `#`", which means `#` must be the first character.
            TokenKind::Text(t) if t.starts_with('#') => self.parse_hash_comment_line(),
            // Anything else: a lyrics line.
            _ => self.parse_lyrics_line(),
        }
    }

    /// Returns the end-directive name for section types that use verbatim
    /// content (tab, grid, ABC, Lilypond, SVG, textblock). Returns `None` for
    /// sections that parse chords normally (chorus, verse, bridge, custom).
    fn verbatim_end_for(kind: &DirectiveKind) -> Option<String> {
        match kind {
            DirectiveKind::StartOfTab => Some("end_of_tab".to_string()),
            DirectiveKind::StartOfGrid => Some("end_of_grid".to_string()),
            DirectiveKind::StartOfAbc => Some("end_of_abc".to_string()),
            DirectiveKind::StartOfLy => Some("end_of_ly".to_string()),
            DirectiveKind::StartOfSvg => Some("end_of_svg".to_string()),
            DirectiveKind::StartOfTextblock => Some("end_of_textblock".to_string()),
            DirectiveKind::StartOfMusicxml => Some("end_of_musicxml".to_string()),
            _ => None,
        }
    }

    /// Peeks ahead to check if the current `{` starts the end directive
    /// that closes the current verbatim section. This allows the parser
    /// to exit verbatim mode.
    ///
    /// Only checks the next token after `DirectiveOpen` for the directive
    /// name text; the full directive structure (including `DirectiveClose`)
    /// is validated later by `parse_directive_line`.
    fn is_verbatim_end_ahead(&self) -> bool {
        if let Some(ref end_name) = self.verbatim_end {
            if self.pos + 1 < self.tokens.len() {
                if let TokenKind::Text(ref text) = self.tokens[self.pos + 1].kind {
                    let trimmed = text.trim().to_ascii_lowercase();
                    // Check full name
                    if trimmed == *end_name {
                        return true;
                    }
                    // Check short aliases
                    return match end_name.as_str() {
                        "end_of_tab" => trimmed == "eot",
                        "end_of_grid" => trimmed == "eog",
                        _ => false,
                    };
                }
            }
        }
        false
    }

    /// Parses a verbatim text line (used inside tab, grid, and delegate environment sections).
    ///
    /// All tokens until the next Newline/Eof are collected as plain text,
    /// with no chord bracket interpretation. The result is a lyrics line
    /// with a single text-only segment.
    fn parse_verbatim_line(&mut self) -> Result<Line, ParseError> {
        let text = self.collect_raw_line();

        // Consume the newline.
        if self.peek_kind() == &TokenKind::Newline {
            self.advance();
        }

        if text.is_empty() {
            Ok(Line::Empty)
        } else {
            Ok(Line::Lyrics(LyricsLine {
                segments: vec![LyricsSegment::text_only(text)],
            }))
        }
    }

    /// Parses a file-level `#` comment line and emits
    /// `Line::Comment(CommentStyle::Normal, text)`.
    ///
    /// The leading `#` is stripped; one immediately-following space is also
    /// stripped so that `# My comment` produces `"My comment"` rather than
    /// `" My comment"`. Inline chord brackets and directive delimiters are
    /// consumed as literal characters (they lose their structural meaning inside
    /// a source comment).
    fn parse_hash_comment_line(&mut self) -> Result<Line, ParseError> {
        let raw = self.collect_raw_line();

        // Consume the trailing newline.
        if self.peek_kind() == &TokenKind::Newline {
            self.advance();
        }

        // The dispatch guard in `parse_line` (`t.starts_with('#')`) guarantees
        // `raw` starts with `#` today. Use `unwrap_or` rather than `expect` so
        // that a future caller re-using this function without that guard
        // degrades to treating the whole line as the comment body instead of
        // panicking on otherwise valid input. The `debug_assert!` surfaces a
        // contract violation loudly in debug builds while still allowing the
        // release-build fallback above.
        debug_assert!(
            raw.starts_with('#'),
            "parse_hash_comment_line called without '#' prefix"
        );
        let after_hash = raw.strip_prefix('#').unwrap_or(raw.as_str());
        let text = after_hash.strip_prefix(' ').unwrap_or(after_hash);

        Ok(Line::Comment(CommentStyle::Normal, text.to_string()))
    }

    /// Collects all tokens on the current line (up to but not including the
    /// trailing `Newline` or `Eof`) into a `String`, mapping structural tokens
    /// (`[`, `]`, `{`, `}`, `:`) back to their literal characters.
    ///
    /// Does **not** consume the trailing `Newline`; the caller is responsible
    /// for advancing past it.
    fn collect_raw_line(&mut self) -> String {
        let mut raw = String::new();
        loop {
            match self.peek_kind() {
                TokenKind::Newline | TokenKind::Eof => break,
                TokenKind::Text(t) => {
                    raw.push_str(t);
                    self.advance();
                }
                TokenKind::ChordOpen => {
                    raw.push('[');
                    self.advance();
                }
                TokenKind::ChordClose => {
                    raw.push(']');
                    self.advance();
                }
                TokenKind::DirectiveOpen => {
                    raw.push('{');
                    self.advance();
                }
                TokenKind::DirectiveClose => {
                    raw.push('}');
                    self.advance();
                }
                TokenKind::Colon => {
                    raw.push(':');
                    self.advance();
                }
            }
        }
        raw
    }

    // -- Directive parsing --------------------------------------------------

    /// Parses a directive line: `{name}` or `{name: value}`.
    ///
    /// After parsing the directive itself, consumes the trailing Newline (or
    /// verifies Eof). Comment directives (`comment`, `comment_italic`,
    /// `comment_box`) are converted to [`Line::Comment`].
    fn parse_directive_line(&mut self) -> Result<Line, ParseError> {
        let open_span = self.peek().span;
        self.advance(); // consume DirectiveOpen

        // Collect the directive name.
        let name = self.parse_directive_name(&open_span)?;

        // Check for a colon (indicates a value follows).
        let value = if self.peek_kind() == &TokenKind::Colon {
            self.advance(); // consume Colon
            Some(self.parse_directive_value())
        } else {
            None
        };

        // Expect the closing brace.
        if self.peek_kind() != &TokenKind::DirectiveClose {
            let span = self.peek().span;
            return Err(ParseError::new("unclosed directive: expected `}`", span));
        }
        self.advance();

        // Consume trailing newline if present.
        if self.peek_kind() == &TokenKind::Newline {
            self.advance();
        }

        // Trim whitespace from name and value.
        let raw_name = name.trim().to_string();
        let mut value = value.map(|v| v.trim().to_string());

        // Inline attribute form (`{start_of_grid shape="..."}`).
        // The ChordPro spec lets directives carry attributes via
        // whitespace separation when no `:` is present —
        // `{start_of_grid shape="L+MxB+R"}` is the documented
        // grid-shape syntax, and `{image src="..." width=64}` is
        // sometimes written without the colon too.
        //
        // Splitting at the first whitespace recovers the
        // attribute portion as the directive's `value`, but only
        // when the prefix is a SPECIFIC named directive (e.g.
        // `start_of_grid`). Custom-section directives
        // (`start_of_foo bar` → `StartOfSection("foo bar")`)
        // intentionally keep the whitespace in the name so
        // legacy tests asserting "section-foo-bar" still pass.
        let name = match raw_name.find(|c: char| c.is_whitespace()) {
            Some(idx) => {
                let prefix = &raw_name[..idx];
                let attrs = raw_name[idx..].trim().to_string();
                let (prefix_kind, _) = DirectiveKind::resolve_with_selector(prefix);
                let is_attribute_bearing = !matches!(
                    prefix_kind,
                    DirectiveKind::Unknown(_)
                        | DirectiveKind::StartOfSection(_)
                        | DirectiveKind::EndOfSection(_)
                );
                if is_attribute_bearing && !attrs.is_empty() {
                    // Only fold inline attrs into the value when
                    // the caller didn't supply an explicit
                    // `:`-prefixed value (that path stays
                    // authoritative).
                    if value.is_none() {
                        value = Some(attrs);
                    }
                    prefix.to_string()
                } else {
                    raw_name
                }
            }
            None => raw_name,
        };

        // Classify the directive, detecting any selector suffix.
        let (kind, selector) = DirectiveKind::resolve_with_selector(&name);

        // Comment directives without a selector → Line::Comment with appropriate style.
        // Comment directives WITH a selector are kept as Line::Directive so
        // the selector information is preserved for downstream filtering.
        if kind.is_comment() && selector.is_none() {
            let style = match kind {
                DirectiveKind::Comment => CommentStyle::Normal,
                DirectiveKind::CommentItalic => CommentStyle::Italic,
                DirectiveKind::CommentBox => CommentStyle::Boxed,
                DirectiveKind::Highlight => CommentStyle::Highlight,
                _ => CommentStyle::Normal,
            };
            let text = value.unwrap_or_default();
            return Ok(Line::Comment(style, text));
        }

        // Meta directive: split value into key + remaining value.
        if matches!(kind, DirectiveKind::Meta(_)) {
            if let Some(ref val) = value {
                let trimmed = val.trim();
                if let Some(pos) = trimmed.find(|c: char| c.is_whitespace()) {
                    let meta_key = trimmed[..pos].to_string();
                    let meta_value = trimmed[pos..].trim().to_string();
                    let kind = DirectiveKind::Meta(meta_key.clone());
                    let directive = Directive {
                        name: "meta".to_string(),
                        value: if meta_value.is_empty() {
                            None
                        } else {
                            Some(meta_value)
                        },
                        kind,
                        selector,
                    };
                    return Ok(Line::Directive(directive));
                } else if !trimmed.is_empty() {
                    // Only a key, no value
                    let meta_key = trimmed.to_string();
                    let kind = DirectiveKind::Meta(meta_key);
                    let directive = Directive {
                        name: "meta".to_string(),
                        value: None,
                        kind,
                        selector,
                    };
                    return Ok(Line::Directive(directive));
                }
            }
            // {meta} without value — treat as unknown
            let directive = Directive {
                name: "meta".to_string(),
                value: None,
                kind: DirectiveKind::Unknown("meta".to_string()),
                selector,
            };
            return Ok(Line::Directive(directive));
        }

        // Image directive: parse key=value attributes from the value string.
        if kind.is_image() {
            let attrs = match &value {
                Some(v) => parse_image_attributes(v),
                None => ImageAttributes::default(),
            };
            let kind = DirectiveKind::Image(attrs);
            let canonical = kind.canonical_name().to_string();
            let directive = Directive {
                name: canonical,
                value,
                kind,
                selector,
            };
            return Ok(Line::Directive(directive));
        }

        // Build the directive with canonical name, kind, and optional selector.
        let canonical = kind.full_canonical_name();
        let directive = Directive {
            name: canonical,
            value,
            kind,
            selector,
        };

        Ok(Line::Directive(directive))
    }

    /// Parses the directive name (text between `{` and either `:` or `}`).
    fn parse_directive_name(&mut self, open_span: &Span) -> Result<String, ParseError> {
        let mut name = String::new();

        loop {
            match self.peek_kind() {
                TokenKind::Text(text) => {
                    name.push_str(text);
                    self.advance();
                }
                TokenKind::Colon | TokenKind::DirectiveClose => break,
                TokenKind::Eof | TokenKind::Newline => {
                    return Err(ParseError::new(
                        "unclosed directive: expected `}`",
                        *open_span,
                    ));
                }
                _ => {
                    // Unexpected token inside directive name (e.g., ChordOpen).
                    let tok = self.peek();
                    return Err(ParseError::new(
                        format!("unexpected {:?} in directive name", tok.kind),
                        tok.span,
                    ));
                }
            }
        }

        if name.trim().is_empty() {
            return Err(ParseError::new("empty directive name", *open_span));
        }

        Ok(name)
    }

    /// Parses the directive value (everything between `:` and `}`).
    ///
    /// The value may contain text tokens and other tokens (like ChordOpen/Close)
    /// that appear literally in the directive value. We collect all text content.
    fn parse_directive_value(&mut self) -> String {
        let mut value = String::new();

        loop {
            match self.peek_kind() {
                TokenKind::Text(text) => {
                    value.push_str(text);
                    self.advance();
                }
                TokenKind::DirectiveClose | TokenKind::Eof | TokenKind::Newline => break,
                TokenKind::Colon => {
                    // Additional colons in value are literal text.
                    value.push(':');
                    self.advance();
                }
                TokenKind::ChordOpen => {
                    value.push('[');
                    self.advance();
                }
                TokenKind::ChordClose => {
                    value.push(']');
                    self.advance();
                }
                TokenKind::DirectiveOpen => {
                    value.push('{');
                    self.advance();
                }
            }
        }

        value
    }

    // -- Lyrics line parsing ------------------------------------------------

    /// Parses a lyrics line containing text and optional chord annotations.
    ///
    /// The line is split into [`LyricsSegment`]s, each consisting of an
    /// optional chord followed by lyric text.
    fn parse_lyrics_line(&mut self) -> Result<Line, ParseError> {
        let mut segments: Vec<LyricsSegment> = Vec::new();
        let mut current_chord: Option<Chord> = None;
        let mut current_text = String::new();

        loop {
            match self.peek_kind() {
                TokenKind::Newline | TokenKind::Eof => {
                    break;
                }
                TokenKind::ChordOpen => {
                    // Flush the current segment before starting a new chord.
                    if current_chord.is_some() || !current_text.is_empty() {
                        segments.push(LyricsSegment::new(
                            current_chord.take(),
                            core::mem::take(&mut current_text),
                        ));
                    }

                    current_chord = Some(self.parse_chord()?);
                }
                TokenKind::Text(text) => {
                    current_text.push_str(text);
                    self.advance();
                }
                TokenKind::DirectiveOpen => {
                    // A directive starting mid-line is unexpected in well-formed
                    // ChordPro, but we handle it gracefully by treating it as
                    // the start of a directive line. First, flush the current
                    // lyrics if any, then break and let the directive be parsed
                    // on a subsequent call.
                    //
                    // However, per the task spec, directives always start at the
                    // beginning of a line. If we see one mid-line, it is likely
                    // a stray `{`. Treat the rest as text.
                    current_text.push('{');
                    self.advance();
                }
                TokenKind::DirectiveClose => {
                    // A stray `}` outside a directive — include as literal text.
                    current_text.push('}');
                    self.advance();
                }
                TokenKind::ChordClose => {
                    // A stray `]` outside a chord — include as literal text.
                    current_text.push(']');
                    self.advance();
                }
                TokenKind::Colon => {
                    // Outside a directive, colons are text. The lexer only emits
                    // Colon inside directives, so this shouldn't normally occur
                    // here, but handle defensively.
                    current_text.push(':');
                    self.advance();
                }
            }
        }

        // Flush the last segment.
        if current_chord.is_some() || !current_text.is_empty() {
            segments.push(LyricsSegment::new(current_chord, current_text));
        }

        // Consume the trailing newline if present.
        if self.peek_kind() == &TokenKind::Newline {
            self.advance();
        }

        if segments.is_empty() {
            Ok(Line::Empty)
        } else {
            // Parse inline markup for each segment's text.
            let segments = segments
                .into_iter()
                .map(Self::apply_inline_markup)
                .collect();
            Ok(Line::Lyrics(LyricsLine { segments }))
        }
    }

    /// Applies inline markup parsing to a lyrics segment.
    ///
    /// If the segment's text contains inline markup tags, the `spans` field is
    /// populated with the parsed span tree and the `text` field is updated to
    /// contain only the plain text (markup tags stripped). If no markup is found,
    /// the segment is returned unchanged.
    fn apply_inline_markup(mut segment: LyricsSegment) -> LyricsSegment {
        if inline_markup::has_inline_markup(&segment.text) {
            let spans = inline_markup::parse_inline_markup(&segment.text);
            if !spans.is_empty() {
                // Update text to be the plain-text version (tags stripped)
                segment.text = inline_markup::spans_to_plain_text(&spans);
                segment.spans = spans;
            }
        }
        segment
    }

    /// Parses a chord annotation: `[` text `]`.
    ///
    /// The opening bracket has already been peeked; this method consumes it,
    /// the chord text, and the closing bracket.
    fn parse_chord(&mut self) -> Result<Chord, ParseError> {
        let open_span = self.peek().span;
        self.advance(); // consume ChordOpen

        let mut name = String::new();

        loop {
            match self.peek_kind() {
                TokenKind::Text(text) => {
                    name.push_str(text);
                    self.advance();
                }
                TokenKind::ChordClose => {
                    self.advance(); // consume ChordClose
                    break;
                }
                TokenKind::Newline | TokenKind::Eof => {
                    return Err(ParseError::new("unclosed chord: expected `]`", open_span));
                }
                _ => {
                    // Unexpected token inside a chord (e.g., DirectiveOpen).
                    let tok = self.peek();
                    return Err(ParseError::new(
                        format!("unexpected {:?} inside chord", tok.kind),
                        tok.span,
                    ));
                }
            }
        }

        Ok(Chord::new(name))
    }
}

// ---------------------------------------------------------------------------
// Convenience function
// ---------------------------------------------------------------------------

/// Parses a ChordPro source string into a [`Song`] AST.
///
/// This is a convenience function that runs the lexer and parser in sequence.
/// Metadata directives populate [`Song::metadata`] automatically.
///
/// # Errors
///
/// Returns a [`ParseError`] if the input contains structural problems.
///
/// # Examples
///
/// ```
/// use chordsketch_chordpro::parser::parse;
///
/// let song = parse("{title: Hello World}\n[Am]La la la").unwrap();
/// assert_eq!(song.metadata.title.as_deref(), Some("Hello World"));
/// assert_eq!(song.lines.len(), 2);
/// ```
#[must_use = "callers must handle the parse error"]
pub fn parse(input: &str) -> Result<Song, ParseError> {
    parse_with_options(input, &ParseOptions::default())
}

/// Options that control parser behavior.
#[derive(Debug, Clone)]
pub struct ParseOptions {
    /// Maximum input size in bytes. Inputs exceeding this limit are rejected
    /// with a [`ParseError`] before lexing begins. Set to `0` to disable.
    ///
    /// Default: 10 MB (10 × 1024 × 1024 bytes).
    pub max_input_size: usize,

    /// Maximum number of errors to collect in lenient parsing mode.
    /// Once this limit is reached, additional errors are silently discarded
    /// to prevent unbounded memory growth from highly malformed input.
    /// Set to `0` to disable the limit.
    ///
    /// Default: 1000.
    pub max_errors: usize,
}

impl Default for ParseOptions {
    fn default() -> Self {
        Self {
            max_input_size: 10 * 1024 * 1024, // 10 MB
            max_errors: 1000,
        }
    }
}

/// Parses a ChordPro source string into a [`Song`] AST with custom options.
///
/// See [`parse`] for details. This variant allows configuring parser behavior
/// via [`ParseOptions`].
///
/// # Errors
///
/// Returns a [`ParseError`] if the input exceeds the configured size limit
/// or contains structural problems.
#[must_use = "callers must handle the parse error"]
pub fn parse_with_options(input: &str, options: &ParseOptions) -> Result<Song, ParseError> {
    if options.max_input_size > 0 && input.len() > options.max_input_size {
        return Err(ParseError::new(
            format!(
                "input size ({} bytes) exceeds maximum ({} bytes)",
                input.len(),
                options.max_input_size
            ),
            Span::new(
                crate::token::Position::new(1, 1),
                crate::token::Position::new(1, 1),
            ),
        ));
    }
    let tokens = Lexer::new(input).tokenize();
    Parser::new(tokens).parse()
}

/// Parses a ChordPro source string leniently, collecting all errors.
///
/// Unlike [`parse`], this function does not fail on the first error.
/// It returns a [`ParseResult`] containing the partial AST and all
/// errors encountered. The size limit from [`ParseOptions::default`]
/// is enforced.
///
/// # Examples
///
/// ```
/// use chordsketch_chordpro::parser::parse_lenient;
///
/// let result = parse_lenient("{title: Test}\n{bad\n[G]Hello");
/// assert!(result.has_errors());
/// assert_eq!(result.song.metadata.title.as_deref(), Some("Test"));
/// // The valid lyrics line was still parsed.
/// assert!(result.song.lines.len() >= 2);
/// ```
#[must_use]
pub fn parse_lenient(input: &str) -> ParseResult {
    parse_lenient_with_options(input, &ParseOptions::default())
}

/// Parses a ChordPro source string leniently with custom options.
///
/// See [`parse_lenient`] for details.
#[must_use]
pub fn parse_lenient_with_options(input: &str, options: &ParseOptions) -> ParseResult {
    if options.max_input_size > 0 && input.len() > options.max_input_size {
        return ParseResult {
            song: Song::new(),
            errors: vec![ParseError::new(
                format!(
                    "input size ({} bytes) exceeds maximum ({} bytes)",
                    input.len(),
                    options.max_input_size
                ),
                Span::new(
                    crate::token::Position::new(1, 1),
                    crate::token::Position::new(1, 1),
                ),
            )],
        };
    }
    let tokens = Lexer::new(input).tokenize();
    Parser::new(tokens).parse_lenient_limited(options.max_errors)
}

// ---------------------------------------------------------------------------
// Multi-song result
// ---------------------------------------------------------------------------

/// The result of a lenient multi-song parse.
///
/// When using [`parse_multi_lenient`], the parser splits the input at `{new_song}`
/// boundaries and parses each segment independently. Each entry in `results`
/// contains the lenient parse result for one song segment.
#[derive(Debug, Clone)]
pub struct MultiParseResult {
    /// The parsed songs, one per segment between `{new_song}` boundaries.
    /// Each entry is the lenient parse result for that song segment.
    pub results: Vec<ParseResult>,
}

impl MultiParseResult {
    /// Returns all successfully parsed songs.
    #[must_use]
    pub fn songs(&self) -> Vec<&Song> {
        self.results.iter().map(|r| &r.song).collect()
    }

    /// Returns `true` if no errors were encountered in any song.
    #[must_use]
    pub fn is_ok(&self) -> bool {
        self.results.iter().all(|r| r.is_ok())
    }

    /// Returns `true` if any errors were encountered in any song.
    #[must_use]
    pub fn has_errors(&self) -> bool {
        self.results.iter().any(|r| r.has_errors())
    }

    /// Returns all errors from all songs.
    #[must_use]
    pub fn all_errors(&self) -> Vec<&ParseError> {
        self.results.iter().flat_map(|r| r.errors.iter()).collect()
    }
}

// ---------------------------------------------------------------------------
// Multi-song convenience functions
// ---------------------------------------------------------------------------

/// Checks whether a trimmed line is a `{new_song}` or `{ns}` directive.
fn is_new_song_line(trimmed: &str) -> bool {
    // Match patterns like {new_song}, { new_song }, {ns}, { ns },
    // {new_song: value}, { ns : tag }, case-insensitive.
    if !trimmed.starts_with('{') || !trimmed.ends_with('}') {
        return false;
    }
    let inner = trimmed[1..trimmed.len() - 1].trim().to_ascii_lowercase();
    // Strip optional colon and value (e.g., "new_song: tag" → "new_song").
    let name = match inner.find(':') {
        Some(pos) => inner[..pos].trim_end(),
        None => inner.as_str(),
    };
    name == "new_song" || name == "ns"
}

/// Splits input text at `{new_song}` / `{ns}` directive boundaries.
///
/// Returns a vector of string slices, where each element is the text of one
/// song. If the input contains no `{new_song}` directives, returns a
/// single-element vector containing the entire input.
fn split_at_new_song(input: &str) -> Vec<&str> {
    let mut segments = Vec::new();
    let mut seg_start = 0;
    let bytes = input.as_bytes();
    let len = bytes.len();
    let mut pos = 0;

    while pos < len {
        let line_start = pos;
        // Advance to end of line content (stop at \r or \n).
        while pos < len && bytes[pos] != b'\r' && bytes[pos] != b'\n' {
            pos += 1;
        }
        let line_end = pos;
        // Consume line terminator: \r\n, \n, or bare \r.
        let after_newline = if pos < len && bytes[pos] == b'\r' {
            if pos + 1 < len && bytes[pos + 1] == b'\n' {
                pos + 2
            } else {
                pos + 1 // bare \r
            }
        } else if pos < len && bytes[pos] == b'\n' {
            pos + 1
        } else {
            pos
        };
        pos = after_newline;

        let line = &input[line_start..line_end];
        let trimmed = line.trim();
        if is_new_song_line(trimmed) {
            segments.push(&input[seg_start..line_start]);
            seg_start = after_newline;
        }
    }

    segments.push(&input[seg_start..]);
    segments
}

/// Parses a multi-song ChordPro source string, splitting at `{new_song}` / `{ns}`
/// boundaries and parsing each segment as an independent [`Song`].
///
/// If the input contains no `{new_song}` directives, the result is a single-element
/// vector containing the entire input parsed as one song.
///
/// # Errors
///
/// Returns a [`ParseError`] if any song segment contains structural problems.
/// On error, parsing stops at the first problematic segment.
///
/// # Examples
///
/// ```
/// use chordsketch_chordpro::parser::parse_multi;
///
/// let input = "{title: Song One}\nLyrics one\n{new_song}\n{title: Song Two}\nLyrics two";
/// let songs = parse_multi(input).unwrap();
/// assert_eq!(songs.len(), 2);
/// assert_eq!(songs[0].metadata.title.as_deref(), Some("Song One"));
/// assert_eq!(songs[1].metadata.title.as_deref(), Some("Song Two"));
/// ```
#[must_use = "callers must handle the parse error"]
pub fn parse_multi(input: &str) -> Result<Vec<Song>, ParseError> {
    parse_multi_with_options(input, &ParseOptions::default())
}

/// Parses a multi-song ChordPro source string with custom options.
///
/// See [`parse_multi`] for details. This variant allows configuring parser
/// behavior via [`ParseOptions`]. The size limit applies to the entire input,
/// not individual song segments.
///
/// # Errors
///
/// Returns a [`ParseError`] if the input exceeds the configured size limit
/// or any song segment contains structural problems.
#[must_use = "callers must handle the parse error"]
pub fn parse_multi_with_options(
    input: &str,
    options: &ParseOptions,
) -> Result<Vec<Song>, ParseError> {
    if options.max_input_size > 0 && input.len() > options.max_input_size {
        return Err(ParseError::new(
            format!(
                "input size ({} bytes) exceeds maximum ({} bytes)",
                input.len(),
                options.max_input_size
            ),
            Span::new(
                crate::token::Position::new(1, 1),
                crate::token::Position::new(1, 1),
            ),
        ));
    }

    let segments = split_at_new_song(input);
    let mut songs = Vec::with_capacity(segments.len());

    for segment in segments {
        let tokens = Lexer::new(segment).tokenize();
        let song = Parser::new(tokens).parse()?;
        songs.push(song);
    }

    Ok(songs)
}

/// Parses a multi-song ChordPro source string leniently, collecting all errors.
///
/// Unlike [`parse_multi`], this function does not fail on the first error.
/// Each song segment is parsed independently with [`parse_lenient`], and all
/// errors are collected. The size limit from [`ParseOptions::default`] is
/// enforced on the entire input.
///
/// # Examples
///
/// ```
/// use chordsketch_chordpro::parser::parse_multi_lenient;
///
/// let input = "{title: Song One}\n[Am\n{new_song}\n{title: Song Two}\n[G]Hello";
/// let result = parse_multi_lenient(input);
/// assert_eq!(result.results.len(), 2);
/// assert!(result.results[0].has_errors()); // unclosed chord
/// assert!(result.results[1].is_ok());
/// ```
#[must_use]
pub fn parse_multi_lenient(input: &str) -> MultiParseResult {
    parse_multi_lenient_with_options(input, &ParseOptions::default())
}

/// Parses a multi-song ChordPro source string leniently with custom options.
///
/// See [`parse_multi_lenient`] for details.
#[must_use]
pub fn parse_multi_lenient_with_options(input: &str, options: &ParseOptions) -> MultiParseResult {
    if options.max_input_size > 0 && input.len() > options.max_input_size {
        return MultiParseResult {
            results: vec![ParseResult {
                song: Song::new(),
                errors: vec![ParseError::new(
                    format!(
                        "input size ({} bytes) exceeds maximum ({} bytes)",
                        input.len(),
                        options.max_input_size
                    ),
                    Span::new(
                        crate::token::Position::new(1, 1),
                        crate::token::Position::new(1, 1),
                    ),
                )],
            }],
        };
    }

    let segments = split_at_new_song(input);
    let results: Vec<ParseResult> = segments
        .into_iter()
        .map(|segment| {
            let tokens = Lexer::new(segment).tokenize();
            Parser::new(tokens).parse_lenient_limited(options.max_errors)
        })
        .collect();

    MultiParseResult { results }
}

// ---------------------------------------------------------------------------
// Image attribute parsing
// ---------------------------------------------------------------------------

/// Maximum byte length for the `src` attribute value.
const IMAGE_SRC_MAX_BYTES: usize = 4096;

/// Maximum byte length for other image attribute values.
const IMAGE_ATTR_MAX_BYTES: usize = 1024;

/// Truncates a string to the given maximum byte length at a valid UTF-8
/// character boundary.
fn truncate_string(s: String, max_bytes: usize) -> String {
    if s.len() <= max_bytes {
        return s;
    }
    let mut end = max_bytes;
    while end > 0 && !s.is_char_boundary(end) {
        end -= 1;
    }
    s[..end].to_string()
}

/// Parses the value string of an `{image}` directive into [`ImageAttributes`].
///
/// The value string is expected to contain `key=value` pairs separated by
/// whitespace. Quoted values (e.g., `title="Album Cover"`) are supported.
/// Unknown keys are silently ignored.
///
/// # Examples
///
/// ```
/// # use chordsketch_chordpro::parser::parse_image_attributes;
/// # use chordsketch_chordpro::ast::ImageAttributes;
/// let attrs = parse_image_attributes("src=photo.jpg width=200");
/// assert_eq!(attrs.src, "photo.jpg");
/// assert_eq!(attrs.width.as_deref(), Some("200"));
/// ```
#[must_use]
pub fn parse_image_attributes(input: &str) -> ImageAttributes {
    let mut attrs = ImageAttributes::default();
    let pairs = split_key_value_pairs(input);

    for (key, value) in pairs {
        match key.to_ascii_lowercase().as_str() {
            "src" => attrs.src = truncate_string(value, IMAGE_SRC_MAX_BYTES),
            "width" => attrs.width = Some(truncate_string(value, IMAGE_ATTR_MAX_BYTES)),
            "height" => attrs.height = Some(truncate_string(value, IMAGE_ATTR_MAX_BYTES)),
            "scale" => attrs.scale = Some(truncate_string(value, IMAGE_ATTR_MAX_BYTES)),
            "title" => attrs.title = Some(truncate_string(value, IMAGE_ATTR_MAX_BYTES)),
            "anchor" => attrs.anchor = Some(truncate_string(value, IMAGE_ATTR_MAX_BYTES)),
            _ => {
                // Unknown attributes are silently ignored per spec.
            }
        }
    }

    attrs
}

/// Splits an input string into `(key, value)` pairs from `key=value` tokens.
///
/// Handles both unquoted values (`key=value`) and quoted values
/// (`key="value with spaces"`). Tokens without an `=` sign are ignored.
fn split_key_value_pairs(input: &str) -> Vec<(String, String)> {
    let mut pairs = Vec::new();
    let bytes = input.as_bytes();
    let len = bytes.len();
    let mut i = 0;

    while i < len {
        // Skip whitespace.
        while i < len && bytes[i].is_ascii_whitespace() {
            i += 1;
        }
        if i >= len {
            break;
        }

        // Read key (up to '=' or whitespace).
        let key_start = i;
        while i < len && bytes[i] != b'=' && !bytes[i].is_ascii_whitespace() {
            i += 1;
        }
        let key = &input[key_start..i];

        if i >= len || bytes[i] != b'=' {
            // No '=' found — skip this token.
            // Advance past any non-whitespace to avoid infinite loop.
            while i < len && !bytes[i].is_ascii_whitespace() {
                i += 1;
            }
            continue;
        }

        // Skip '='.
        i += 1;

        // Read value (possibly quoted).
        let value = if i < len && bytes[i] == b'"' {
            // Quoted value: read until closing '"'.
            i += 1; // skip opening quote
            let val_start = i;
            while i < len && bytes[i] != b'"' {
                i += 1;
            }
            let val = &input[val_start..i];
            if i < len {
                i += 1; // skip closing quote
            }
            val
        } else {
            // Unquoted value: read until whitespace.
            let val_start = i;
            while i < len && !bytes[i].is_ascii_whitespace() {
                i += 1;
            }
            &input[val_start..i]
        };

        if !key.is_empty() {
            pairs.push((key.to_string(), value.to_string()));
        }
    }

    pairs
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::{
        Chord, CommentStyle, Directive, DirectiveKind, Line, LyricsLine, LyricsSegment,
    };

    // -- Helper -------------------------------------------------------------

    /// Parses the input and returns the lines, panicking on error.
    fn lines(input: &str) -> Vec<Line> {
        parse(input).expect("parse failed").lines
    }

    // -- Input size limits (#60) -----------------------------------------------

    #[test]
    fn input_within_limit_succeeds() {
        let opts = ParseOptions {
            max_input_size: 100,
            ..Default::default()
        };
        let result = parse_with_options("{title: Test}", &opts);
        assert!(result.is_ok());
    }

    #[test]
    fn input_exceeding_limit_fails() {
        let opts = ParseOptions {
            max_input_size: 10,
            ..Default::default()
        };
        let result = parse_with_options("{title: This is too long}", &opts);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.message.contains("exceeds maximum"));
    }

    #[test]
    fn zero_limit_disables_check() {
        let opts = ParseOptions {
            max_input_size: 0,
            ..Default::default()
        };
        let result = parse_with_options("{title: Any size is fine}", &opts);
        assert!(result.is_ok());
    }

    #[test]
    fn default_limit_is_10mb() {
        let opts = ParseOptions::default();
        assert_eq!(opts.max_input_size, 10 * 1024 * 1024);
        assert_eq!(opts.max_errors, 1000);
    }

    // -- Empty input --------------------------------------------------------

    #[test]
    fn empty_input() {
        let song = parse("").unwrap();
        assert!(song.lines.is_empty());
    }

    // -- Empty lines --------------------------------------------------------

    #[test]
    fn single_empty_line() {
        let result = lines("\n");
        assert_eq!(result, vec![Line::Empty]);
    }

    #[test]
    fn multiple_empty_lines() {
        let result = lines("\n\n\n");
        assert_eq!(result, vec![Line::Empty, Line::Empty, Line::Empty]);
    }

    // -- Plain text (lyrics without chords) ---------------------------------

    #[test]
    fn plain_text_line() {
        let result = lines("Hello world");
        assert_eq!(
            result,
            vec![Line::Lyrics(LyricsLine {
                segments: vec![LyricsSegment::text_only("Hello world")],
            })]
        );
    }

    #[test]
    fn multiple_plain_text_lines() {
        let result = lines("Line one\nLine two");
        assert_eq!(
            result,
            vec![
                Line::Lyrics(LyricsLine {
                    segments: vec![LyricsSegment::text_only("Line one")],
                }),
                Line::Lyrics(LyricsLine {
                    segments: vec![LyricsSegment::text_only("Line two")],
                }),
            ]
        );
    }

    // -- Chord annotations --------------------------------------------------

    #[test]
    fn single_chord_with_text() {
        let result = lines("[Am]Hello");
        assert_eq!(
            result,
            vec![Line::Lyrics(LyricsLine {
                segments: vec![LyricsSegment::new(Some(Chord::new("Am")), "Hello")],
            })]
        );
    }

    #[test]
    fn multiple_chords_with_text() {
        let result = lines("[Am]Hello [G]world");
        assert_eq!(
            result,
            vec![Line::Lyrics(LyricsLine {
                segments: vec![
                    LyricsSegment::new(Some(Chord::new("Am")), "Hello "),
                    LyricsSegment::new(Some(Chord::new("G")), "world"),
                ],
            })]
        );
    }

    #[test]
    fn chord_only_no_text() {
        let result = lines("[Am]");
        assert_eq!(
            result,
            vec![Line::Lyrics(LyricsLine {
                segments: vec![LyricsSegment::chord_only(Chord::new("Am"))],
            })]
        );
    }

    #[test]
    fn consecutive_chords_no_text_between() {
        let result = lines("[Am][G]");
        assert_eq!(
            result,
            vec![Line::Lyrics(LyricsLine {
                segments: vec![
                    LyricsSegment::chord_only(Chord::new("Am")),
                    LyricsSegment::chord_only(Chord::new("G")),
                ],
            })]
        );
    }

    #[test]
    fn text_before_first_chord() {
        let result = lines("Hello [Am]world");
        assert_eq!(
            result,
            vec![Line::Lyrics(LyricsLine {
                segments: vec![
                    LyricsSegment::text_only("Hello "),
                    LyricsSegment::new(Some(Chord::new("Am")), "world"),
                ],
            })]
        );
    }

    #[test]
    fn chord_at_end_of_line() {
        let result = lines("Hello [Am]");
        assert_eq!(
            result,
            vec![Line::Lyrics(LyricsLine {
                segments: vec![
                    LyricsSegment::text_only("Hello "),
                    LyricsSegment::chord_only(Chord::new("Am")),
                ],
            })]
        );
    }

    #[test]
    fn empty_chord_name() {
        // An empty chord `[]` is valid — chord name is an empty string.
        let result = lines("[]text");
        assert_eq!(
            result,
            vec![Line::Lyrics(LyricsLine {
                segments: vec![LyricsSegment::new(Some(Chord::new("")), "text")],
            })]
        );
    }

    // -- Directives ---------------------------------------------------------

    #[test]
    fn directive_with_value() {
        let result = lines("{title: My Song}");
        assert_eq!(
            result,
            vec![Line::Directive(Directive::with_value("title", "My Song"))],
        );
    }

    #[test]
    fn directive_without_value() {
        let result = lines("{start_of_chorus}");
        assert_eq!(
            result,
            vec![Line::Directive(Directive::name_only("start_of_chorus"))],
        );
    }

    #[test]
    fn directive_value_trimmed() {
        let result = lines("{title:  Hello World  }");
        assert_eq!(
            result,
            vec![Line::Directive(Directive::with_value(
                "title",
                "Hello World"
            ))],
        );
    }

    #[test]
    fn directive_name_trimmed() {
        let result = lines("{  title  : value}");
        assert_eq!(
            result,
            vec![Line::Directive(Directive::with_value("title", "value"))],
        );
    }

    #[test]
    fn directive_with_colon_in_value() {
        // The lexer emits multiple Colon tokens; the parser joins extra colons.
        let result = lines("{comment: time 10:30}");
        // This is the `comment` directive, so it becomes Line::Comment.
        assert_eq!(
            result,
            vec![Line::Comment(
                CommentStyle::Normal,
                "time 10:30".to_string()
            )]
        );
    }

    #[test]
    fn directive_followed_by_lyrics() {
        let result = lines("{title: Test}\n[Am]Hello");
        assert_eq!(
            result,
            vec![
                Line::Directive(Directive::with_value("title", "Test")),
                Line::Lyrics(LyricsLine {
                    segments: vec![LyricsSegment::new(Some(Chord::new("Am")), "Hello")],
                }),
            ]
        );
    }

    // -- Comment directive --------------------------------------------------

    #[test]
    fn comment_directive_full_name() {
        let result = lines("{comment: This is a comment}");
        assert_eq!(
            result,
            vec![Line::Comment(
                CommentStyle::Normal,
                "This is a comment".to_string()
            )],
        );
    }

    #[test]
    fn comment_directive_short_name() {
        let result = lines("{c: Short comment}");
        assert_eq!(
            result,
            vec![Line::Comment(
                CommentStyle::Normal,
                "Short comment".to_string()
            )],
        );
    }

    #[test]
    fn comment_directive_no_value() {
        let result = lines("{comment}");
        assert_eq!(
            result,
            vec![Line::Comment(CommentStyle::Normal, String::new())]
        );
    }

    #[test]
    fn comment_italic_directive() {
        let result = lines("{comment_italic: Softly}");
        assert_eq!(
            result,
            vec![Line::Comment(CommentStyle::Italic, "Softly".to_string())],
        );
    }

    #[test]
    fn comment_italic_short_name() {
        let result = lines("{ci: Softly}");
        assert_eq!(
            result,
            vec![Line::Comment(CommentStyle::Italic, "Softly".to_string())],
        );
    }

    #[test]
    fn comment_box_directive() {
        let result = lines("{comment_box: Important}");
        assert_eq!(
            result,
            vec![Line::Comment(CommentStyle::Boxed, "Important".to_string())],
        );
    }

    #[test]
    fn comment_box_short_name() {
        let result = lines("{cb: Important}");
        assert_eq!(
            result,
            vec![Line::Comment(CommentStyle::Boxed, "Important".to_string())],
        );
    }

    // -- File-level `#` comment lines --------------------------------------

    #[test]
    fn hash_comment_basic() {
        let result = lines("# This is a comment");
        assert_eq!(
            result,
            vec![Line::Comment(
                CommentStyle::Normal,
                "This is a comment".to_string()
            )],
        );
    }

    #[test]
    fn hash_comment_no_space_after_hash() {
        // `#text` (no space) — hash is stripped but no space to remove.
        let result = lines("#no space");
        assert_eq!(
            result,
            vec![Line::Comment(CommentStyle::Normal, "no space".to_string())],
        );
    }

    #[test]
    fn hash_comment_standalone_hash() {
        // A bare `#` produces an empty comment text.
        let result = lines("#");
        assert_eq!(
            result,
            vec![Line::Comment(CommentStyle::Normal, "".to_string())],
        );
    }

    #[test]
    fn hash_comment_mixed_with_directives() {
        // `#` comment before and after a directive — both become Comment(Normal).
        let result = lines("# First\n{title: My Song}\n# Second");
        assert_eq!(
            result,
            vec![
                Line::Comment(CommentStyle::Normal, "First".to_string()),
                Line::Directive(Directive::with_value("title", "My Song")),
                Line::Comment(CommentStyle::Normal, "Second".to_string()),
            ],
        );
    }

    #[test]
    fn hash_comment_indented_is_lyrics_not_comment() {
        // `  # text` (leading spaces) — NOT a comment; treated as a lyrics line
        // because the ChordPro spec requires `#` at column 1.
        let result = lines("  # indented");
        assert!(
            matches!(result[..], [Line::Lyrics(_)]),
            "expected Lyrics, got {result:?}"
        );
    }

    // Release-only: in debug builds the `debug_assert!` added for #2096 fires
    // on this contract violation. The release fallback (treating the whole
    // line as the comment body) is still live, so this test locks it in on
    // release profiles. Regression guard for #2082 (a future caller could
    // re-use this method without the `t.starts_with('#')` gate).
    #[cfg(not(debug_assertions))]
    #[test]
    fn parse_hash_comment_line_is_resilient_to_missing_hash_prefix() {
        let tokens = Lexer::new("no hash prefix\n").tokenize();
        let mut parser = Parser::new(tokens);
        let line = parser
            .parse_hash_comment_line()
            .expect("parse_hash_comment_line returned Err unexpectedly");
        assert_eq!(
            line,
            Line::Comment(CommentStyle::Normal, "no hash prefix".to_string()),
        );
    }

    #[cfg(debug_assertions)]
    #[test]
    #[should_panic(expected = "parse_hash_comment_line called without '#' prefix")]
    fn parse_hash_comment_line_debug_asserts_missing_hash_prefix() {
        // Counterpart to the release-only resilience test above: debug builds
        // must surface the contract violation loudly via `debug_assert!`.
        let tokens = Lexer::new("no hash prefix\n").tokenize();
        let mut parser = Parser::new(tokens);
        let _ = parser.parse_hash_comment_line();
    }

    // -- Directive classification -------------------------------------------

    #[test]
    fn directive_short_alias_title() {
        let result = lines("{t: My Song}");
        let expected = Directive::with_value("title", "My Song");
        assert_eq!(result, vec![Line::Directive(expected)]);
    }

    #[test]
    fn directive_short_alias_subtitle() {
        let result = lines("{st: Alternate}");
        let expected = Directive::with_value("subtitle", "Alternate");
        assert_eq!(result, vec![Line::Directive(expected)]);
    }

    #[test]
    fn directive_short_alias_soc() {
        let result = lines("{soc}");
        let expected = Directive::name_only("start_of_chorus");
        assert_eq!(result, vec![Line::Directive(expected)]);
    }

    #[test]
    fn directive_short_alias_eoc() {
        let result = lines("{eoc}");
        let expected = Directive::name_only("end_of_chorus");
        assert_eq!(result, vec![Line::Directive(expected)]);
    }

    #[test]
    fn directive_case_insensitive() {
        let result = lines("{TITLE: Upper}");
        let expected = Directive::with_value("title", "Upper");
        assert_eq!(result, vec![Line::Directive(expected)]);
    }

    #[test]
    fn directive_mixed_case() {
        let result = lines("{Start_Of_Chorus}");
        let expected = Directive::name_only("start_of_chorus");
        assert_eq!(result, vec![Line::Directive(expected)]);
    }

    #[test]
    fn directive_unknown_preserved() {
        let result = lines("{my_custom: value}");
        assert_eq!(
            result,
            vec![Line::Directive(Directive {
                name: "my_custom".to_string(),
                value: Some("value".to_string()),
                kind: DirectiveKind::Unknown("my_custom".to_string()),
                selector: None,
            })],
        );
    }

    #[test]
    fn directive_kind_on_parsed_directive() {
        let song = parse("{title: Test}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::Title);
            assert_eq!(d.name, "title");
        } else {
            panic!("expected directive");
        }
    }

    // -- Environment directives (all variants) ------------------------------

    #[test]
    fn environment_directives_long_form() {
        let cases = vec![
            (
                "{start_of_chorus}",
                "start_of_chorus",
                DirectiveKind::StartOfChorus,
            ),
            (
                "{end_of_chorus}",
                "end_of_chorus",
                DirectiveKind::EndOfChorus,
            ),
            (
                "{start_of_verse}",
                "start_of_verse",
                DirectiveKind::StartOfVerse,
            ),
            ("{end_of_verse}", "end_of_verse", DirectiveKind::EndOfVerse),
            (
                "{start_of_bridge}",
                "start_of_bridge",
                DirectiveKind::StartOfBridge,
            ),
            (
                "{end_of_bridge}",
                "end_of_bridge",
                DirectiveKind::EndOfBridge,
            ),
            ("{start_of_tab}", "start_of_tab", DirectiveKind::StartOfTab),
            ("{end_of_tab}", "end_of_tab", DirectiveKind::EndOfTab),
        ];

        for (input, expected_name, expected_kind) in cases {
            let result = lines(input);
            if let Line::Directive(ref d) = result[0] {
                assert_eq!(d.name, expected_name, "failed for input: {input}");
                assert_eq!(d.kind, expected_kind, "failed for input: {input}");
            } else {
                panic!("expected directive for input: {input}");
            }
        }
    }

    #[test]
    fn environment_directives_short_form() {
        let cases = vec![
            ("{soc}", "start_of_chorus", DirectiveKind::StartOfChorus),
            ("{eoc}", "end_of_chorus", DirectiveKind::EndOfChorus),
            ("{sov}", "start_of_verse", DirectiveKind::StartOfVerse),
            ("{eov}", "end_of_verse", DirectiveKind::EndOfVerse),
            ("{sob}", "start_of_bridge", DirectiveKind::StartOfBridge),
            ("{eob}", "end_of_bridge", DirectiveKind::EndOfBridge),
            ("{sot}", "start_of_tab", DirectiveKind::StartOfTab),
            ("{eot}", "end_of_tab", DirectiveKind::EndOfTab),
        ];

        for (input, expected_name, expected_kind) in cases {
            let result = lines(input);
            if let Line::Directive(ref d) = result[0] {
                assert_eq!(d.name, expected_name, "failed for input: {input}");
                assert_eq!(d.kind, expected_kind, "failed for input: {input}");
            } else {
                panic!("expected directive for input: {input}");
            }
        }
    }

    // -- Metadata population ------------------------------------------------

    #[test]
    fn metadata_title_populated() {
        let song = parse("{title: Amazing Grace}").unwrap();
        assert_eq!(song.metadata.title.as_deref(), Some("Amazing Grace"));
    }

    #[test]
    fn metadata_title_via_short_alias() {
        let song = parse("{t: Amazing Grace}").unwrap();
        assert_eq!(song.metadata.title.as_deref(), Some("Amazing Grace"));
    }

    #[test]
    fn metadata_subtitle_populated() {
        let song = parse("{subtitle: How sweet}\n{st: The sound}").unwrap();
        assert_eq!(song.metadata.subtitles, vec!["How sweet", "The sound"]);
    }

    #[test]
    fn metadata_artist_populated() {
        let song = parse("{artist: John Newton}").unwrap();
        assert_eq!(song.metadata.artists, vec!["John Newton"]);
    }

    #[test]
    fn metadata_multiple_artists() {
        let song = parse("{artist: John}\n{artist: Jane}").unwrap();
        assert_eq!(song.metadata.artists, vec!["John", "Jane"]);
    }

    #[test]
    fn metadata_composer_populated() {
        let song = parse("{composer: Bach}").unwrap();
        assert_eq!(song.metadata.composers, vec!["Bach"]);
    }

    #[test]
    fn metadata_lyricist_populated() {
        let song = parse("{lyricist: Someone}").unwrap();
        assert_eq!(song.metadata.lyricists, vec!["Someone"]);
    }

    #[test]
    fn metadata_album_populated() {
        let song = parse("{album: Greatest Hits}").unwrap();
        assert_eq!(song.metadata.album.as_deref(), Some("Greatest Hits"));
    }

    #[test]
    fn metadata_year_populated() {
        let song = parse("{year: 1779}").unwrap();
        assert_eq!(song.metadata.year.as_deref(), Some("1779"));
    }

    #[test]
    fn metadata_key_populated() {
        let song = parse("{key: G}").unwrap();
        assert_eq!(song.metadata.key.as_deref(), Some("G"));
    }

    #[test]
    fn metadata_tempo_populated() {
        let song = parse("{tempo: 120}").unwrap();
        assert_eq!(song.metadata.tempo.as_deref(), Some("120"));
    }

    #[test]
    fn metadata_time_populated() {
        let song = parse("{time: 3/4}").unwrap();
        assert_eq!(song.metadata.time.as_deref(), Some("3/4"));
    }

    #[test]
    fn metadata_capo_populated() {
        let song = parse("{capo: 2}").unwrap();
        assert_eq!(song.metadata.capo.as_deref(), Some("2"));
    }

    /// Spec: `{key}` is `[Nx] [Pos]` — multiple declarations
    /// accumulate. The plural `keys` Vec is the authoritative list;
    /// the singular `key` field keeps the last-wins value for
    /// backward-compat callers.
    #[test]
    fn metadata_keys_accumulate_multi_value() {
        let song = parse("{key: G}\n[G]hi\n{key: D}\n[D]ho").unwrap();
        assert_eq!(song.metadata.keys, vec!["G".to_string(), "D".to_string()]);
        assert_eq!(song.metadata.key.as_deref(), Some("D"));
    }

    #[test]
    fn metadata_tempos_accumulate_multi_value() {
        let song = parse("{tempo: 120}\n[G]a\n{tempo: 140}\n[D]b").unwrap();
        assert_eq!(
            song.metadata.tempos,
            vec!["120".to_string(), "140".to_string()]
        );
        assert_eq!(song.metadata.tempo.as_deref(), Some("140"));
    }

    #[test]
    fn metadata_times_accumulate_multi_value() {
        let song = parse("{time: 4/4}\n[G]a\n{time: 6/8}\n[D]b").unwrap();
        assert_eq!(
            song.metadata.times,
            vec!["4/4".to_string(), "6/8".to_string()]
        );
        assert_eq!(song.metadata.time.as_deref(), Some("6/8"));
    }

    /// `{meta: <key> <value>}` long-form must populate the same
    /// plural Vec as the dedicated directives.
    #[test]
    fn metadata_keys_accumulate_via_meta_long_form() {
        let song = parse("{meta: key G}\n{meta: key D}").unwrap();
        assert_eq!(song.metadata.keys, vec!["G".to_string(), "D".to_string()]);
    }

    #[test]
    fn metadata_case_insensitive() {
        let song = parse("{TITLE: Upper Case}").unwrap();
        assert_eq!(song.metadata.title.as_deref(), Some("Upper Case"));
    }

    #[test]
    fn metadata_not_populated_without_value() {
        let song = parse("{title}").unwrap();
        assert_eq!(song.metadata.title, None);
    }

    #[test]
    fn metadata_all_fields_populated() {
        let input = "\
{title: My Song}
{subtitle: A Sub}
{artist: An Artist}
{composer: A Composer}
{lyricist: A Lyricist}
{album: An Album}
{year: 2024}
{key: Am}
{tempo: 100}
{time: 4/4}
{capo: 3}";

        let song = parse(input).unwrap();
        assert_eq!(song.metadata.title.as_deref(), Some("My Song"));
        assert_eq!(song.metadata.subtitles, vec!["A Sub"]);
        assert_eq!(song.metadata.artists, vec!["An Artist"]);
        assert_eq!(song.metadata.composers, vec!["A Composer"]);
        assert_eq!(song.metadata.lyricists, vec!["A Lyricist"]);
        assert_eq!(song.metadata.album.as_deref(), Some("An Album"));
        assert_eq!(song.metadata.year.as_deref(), Some("2024"));
        assert_eq!(song.metadata.key.as_deref(), Some("Am"));
        assert_eq!(song.metadata.tempo.as_deref(), Some("100"));
        assert_eq!(song.metadata.time.as_deref(), Some("4/4"));
        assert_eq!(song.metadata.capo.as_deref(), Some("3"));
    }

    #[test]
    fn metadata_custom_populated_for_unknown_directive() {
        let song = parse("{x_my_custom: some value}").unwrap();
        assert_eq!(
            song.metadata.custom,
            vec![("x_my_custom".to_string(), "some value".to_string())]
        );
    }

    #[test]
    fn metadata_custom_multiple_unknown_directives() {
        let song = parse("{x_one: first}\n{x_two: second}").unwrap();
        assert_eq!(
            song.metadata.custom,
            vec![
                ("x_one".to_string(), "first".to_string()),
                ("x_two".to_string(), "second".to_string()),
            ]
        );
    }

    #[test]
    fn metadata_custom_not_populated_without_value() {
        let song = parse("{x_no_value}").unwrap();
        assert!(song.metadata.custom.is_empty());
    }

    #[test]
    fn metadata_custom_coexists_with_standard_metadata() {
        let input = "{title: My Song}\n{x_custom: custom value}";
        let song = parse(input).unwrap();
        assert_eq!(song.metadata.title.as_deref(), Some("My Song"));
        assert_eq!(
            song.metadata.custom,
            vec![("x_custom".to_string(), "custom value".to_string())]
        );
    }

    // -- Error cases --------------------------------------------------------

    #[test]
    fn unclosed_directive() {
        let err = parse("{title: oops").unwrap_err();
        assert!(
            err.message.contains("unclosed directive"),
            "error message was: {}",
            err.message
        );
    }

    #[test]
    fn unclosed_chord() {
        let err = parse("[Am").unwrap_err();
        assert!(
            err.message.contains("unclosed chord"),
            "error message was: {}",
            err.message
        );
    }

    #[test]
    fn empty_directive_name() {
        let err = parse("{}").unwrap_err();
        assert!(
            err.message.contains("empty directive name"),
            "error message was: {}",
            err.message
        );
    }

    #[test]
    fn empty_directive_with_colon() {
        let err = parse("{: value}").unwrap_err();
        assert!(
            err.message.contains("empty directive name"),
            "error message was: {}",
            err.message
        );
    }

    #[test]
    fn unclosed_chord_at_newline() {
        let err = parse("[Am\ntext").unwrap_err();
        assert!(
            err.message.contains("unclosed chord"),
            "error message was: {}",
            err.message
        );
    }

    #[test]
    fn parse_error_display() {
        let err = parse("{title: no close").unwrap_err();
        let msg = format!("{err}");
        assert!(msg.contains("parse error at line"));
        assert!(msg.contains("unclosed directive"));
    }

    // -- Mixed content / integration ----------------------------------------

    #[test]
    fn full_song() {
        let input = "\
{title: Amazing Grace}
{artist: John Newton}

[G]Amazing [G7]grace, how [C]sweet the [G]sound
[G]That saved a [Em]wretch like [D]me";

        let song = parse(input).unwrap();
        assert_eq!(song.lines.len(), 5);

        // Metadata populated
        assert_eq!(song.metadata.title.as_deref(), Some("Amazing Grace"));
        assert_eq!(song.metadata.artists, vec!["John Newton"]);

        // First line: title directive
        assert_eq!(
            song.lines[0],
            Line::Directive(Directive::with_value("title", "Amazing Grace")),
        );

        // Second line: artist directive
        assert_eq!(
            song.lines[1],
            Line::Directive(Directive::with_value("artist", "John Newton")),
        );

        // Third line: empty
        assert_eq!(song.lines[2], Line::Empty);

        // Fourth line: lyrics with chords
        if let Line::Lyrics(ref lyrics) = song.lines[3] {
            assert_eq!(lyrics.text(), "Amazing grace, how sweet the sound");
            assert!(lyrics.has_chords());
            assert_eq!(lyrics.segments.len(), 4);
            assert_eq!(lyrics.segments[0].chord.as_ref().unwrap().name, "G");
            assert_eq!(lyrics.segments[0].text, "Amazing ");
            assert_eq!(lyrics.segments[1].chord.as_ref().unwrap().name, "G7");
            assert_eq!(lyrics.segments[1].text, "grace, how ");
            assert_eq!(lyrics.segments[2].chord.as_ref().unwrap().name, "C");
            assert_eq!(lyrics.segments[2].text, "sweet the ");
            assert_eq!(lyrics.segments[3].chord.as_ref().unwrap().name, "G");
            assert_eq!(lyrics.segments[3].text, "sound");
        } else {
            panic!("expected Line::Lyrics for line 4");
        }

        // Fifth line: lyrics with chords
        if let Line::Lyrics(ref lyrics) = song.lines[4] {
            assert_eq!(lyrics.text(), "That saved a wretch like me");
            assert_eq!(lyrics.segments.len(), 3);
        } else {
            panic!("expected Line::Lyrics for line 5");
        }
    }

    #[test]
    fn song_with_sections() {
        let input = "\
{start_of_chorus}
[C]La la [G]la
{end_of_chorus}";

        let song = parse(input).unwrap();
        assert_eq!(song.lines.len(), 3);
        assert!(matches!(song.lines[0], Line::Directive(_)));
        assert!(matches!(song.lines[1], Line::Lyrics(_)));
        assert!(matches!(song.lines[2], Line::Directive(_)));
    }

    #[test]
    fn song_with_comments_and_empty_lines() {
        let input = "\
{title: Test}
{comment: Intro}

[Am]Hello
";

        let song = parse(input).unwrap();
        assert_eq!(song.lines.len(), 4);
        assert_eq!(
            song.lines[0],
            Line::Directive(Directive::with_value("title", "Test"))
        );
        assert_eq!(
            song.lines[1],
            Line::Comment(CommentStyle::Normal, "Intro".to_string())
        );
        assert_eq!(song.lines[2], Line::Empty);
        assert!(matches!(song.lines[3], Line::Lyrics(_)));
    }

    #[test]
    fn crlf_line_endings() {
        let input = "{title: Test}\r\n[Am]Hello\r\n";
        let song = parse(input).unwrap();
        assert_eq!(song.lines.len(), 2);
        assert_eq!(
            song.lines[0],
            Line::Directive(Directive::with_value("title", "Test")),
        );
        assert!(matches!(song.lines[1], Line::Lyrics(_)));
    }

    #[test]
    fn stray_close_brace_in_lyrics() {
        // A stray `}` outside a directive is treated as literal text.
        let result = lines("hello } world");
        assert_eq!(
            result,
            vec![Line::Lyrics(LyricsLine {
                segments: vec![LyricsSegment::text_only("hello } world")],
            })]
        );
    }

    #[test]
    fn stray_close_bracket_in_lyrics() {
        // A stray `]` outside a chord is treated as literal text.
        let result = lines("hello ] world");
        assert_eq!(
            result,
            vec![Line::Lyrics(LyricsLine {
                segments: vec![LyricsSegment::text_only("hello ] world")],
            })]
        );
    }

    #[test]
    fn unicode_in_chords_and_lyrics() {
        let result = lines("[Am]こんにちは [G]世界");
        assert_eq!(
            result,
            vec![Line::Lyrics(LyricsLine {
                segments: vec![
                    LyricsSegment::new(Some(Chord::new("Am")), "こんにちは "),
                    LyricsSegment::new(Some(Chord::new("G")), "世界"),
                ],
            })]
        );
    }

    #[test]
    fn multiple_colons_in_directive_value() {
        // Extra colons after the first are treated as part of the value.
        // When the directive is "meta", it is parsed as a Meta directive.
        // Since "key:value:extra" has no whitespace, the whole string
        // becomes the meta key with no value.
        let result = lines("{meta: key:value:extra}");
        assert_eq!(
            result,
            vec![Line::Directive(Directive {
                name: "meta".to_string(),
                value: None,
                kind: DirectiveKind::Meta("key:value:extra".to_string()),
                selector: None,
            })],
        );

        // For non-meta directives, extra colons remain in the value.
        let result = lines("{custom_dir: key:value:extra}");
        assert_eq!(
            result,
            vec![Line::Directive(Directive {
                name: "custom_dir".to_string(),
                value: Some("key:value:extra".to_string()),
                kind: DirectiveKind::Unknown("custom_dir".to_string()),
                selector: None,
            })],
        );
    }

    #[test]
    fn directive_only_whitespace_name() {
        let err = parse("{   }").unwrap_err();
        assert!(
            err.message.contains("empty directive name"),
            "error message was: {}",
            err.message
        );
    }

    #[test]
    fn directive_with_brackets_in_value() {
        // Brackets inside a directive value are included literally.
        let result = lines("{comment: play [Am] here}");
        assert_eq!(
            result,
            vec![Line::Comment(
                CommentStyle::Normal,
                "play [Am] here".to_string()
            )],
        );
    }

    #[test]
    fn chord_line_with_spaces() {
        let result = lines("[Am]  [G]  [C]");
        assert_eq!(
            result,
            vec![Line::Lyrics(LyricsLine {
                segments: vec![
                    LyricsSegment::new(Some(Chord::new("Am")), "  "),
                    LyricsSegment::new(Some(Chord::new("G")), "  "),
                    LyricsSegment::chord_only(Chord::new("C")),
                ],
            })]
        );
    }

    #[test]
    fn trailing_newline_produces_empty_line() {
        let result = lines("text\n");
        assert_eq!(
            result,
            vec![Line::Lyrics(LyricsLine {
                segments: vec![LyricsSegment::text_only("text")],
            })]
        );
    }

    #[test]
    fn parser_struct_directly() {
        // Test using Parser::new directly with tokens.
        let tokens = Lexer::new("[C]Hello").tokenize();
        let song = Parser::new(tokens).parse().unwrap();
        assert_eq!(song.lines.len(), 1);
    }

    // -- Full song with all directive types ---------------------------------

    #[test]
    fn full_song_with_all_directive_types() {
        let input = "\
{t: Amazing Grace}
{st: A Hymn}
{artist: John Newton}
{key: G}
{tempo: 80}
{time: 3/4}
{capo: 2}
{comment: Verse 1}
{ci: Play softly}
{cb: Key change ahead}
{soc}
[G]Amazing [G7]grace
{eoc}";

        let song = parse(input).unwrap();

        // Metadata checks
        assert_eq!(song.metadata.title.as_deref(), Some("Amazing Grace"));
        assert_eq!(song.metadata.subtitles, vec!["A Hymn"]);
        assert_eq!(song.metadata.artists, vec!["John Newton"]);
        assert_eq!(song.metadata.key.as_deref(), Some("G"));
        assert_eq!(song.metadata.tempo.as_deref(), Some("80"));
        assert_eq!(song.metadata.time.as_deref(), Some("3/4"));
        assert_eq!(song.metadata.capo.as_deref(), Some("2"));

        // Line type checks
        assert_eq!(song.lines.len(), 13);
        assert!(matches!(song.lines[0], Line::Directive(_))); // title
        assert!(matches!(song.lines[1], Line::Directive(_))); // subtitle
        assert!(matches!(song.lines[2], Line::Directive(_))); // artist
        assert!(matches!(song.lines[3], Line::Directive(_))); // key
        assert!(matches!(song.lines[4], Line::Directive(_))); // tempo
        assert!(matches!(song.lines[5], Line::Directive(_))); // time
        assert!(matches!(song.lines[6], Line::Directive(_))); // capo
        assert_eq!(
            song.lines[7],
            Line::Comment(CommentStyle::Normal, "Verse 1".to_string())
        );
        assert_eq!(
            song.lines[8],
            Line::Comment(CommentStyle::Italic, "Play softly".to_string())
        );
        assert_eq!(
            song.lines[9],
            Line::Comment(CommentStyle::Boxed, "Key change ahead".to_string())
        );
        // soc
        if let Line::Directive(ref d) = song.lines[10] {
            assert_eq!(d.kind, DirectiveKind::StartOfChorus);
            assert_eq!(d.name, "start_of_chorus");
        } else {
            panic!("expected directive");
        }
        assert!(matches!(song.lines[11], Line::Lyrics(_))); // lyrics
        // eoc
        if let Line::Directive(ref d) = song.lines[12] {
            assert_eq!(d.kind, DirectiveKind::EndOfChorus);
            assert_eq!(d.name, "end_of_chorus");
        } else {
            panic!("expected directive");
        }
    }

    // -- Error diagnostics (issue #25) --------------------------------------

    #[test]
    fn parse_error_implements_std_error() {
        let err = parse("[Am").unwrap_err();
        // Verify that ParseError can be used as a std::error::Error trait object.
        let _: &dyn std::error::Error = &err;
    }

    #[test]
    fn parse_error_source_is_none() {
        let err = parse("[Am").unwrap_err();
        let err_ref: &dyn std::error::Error = &err;
        assert!(err_ref.source().is_none());
    }

    #[test]
    fn parse_error_line_column_accessors() {
        let err = parse("[Am").unwrap_err();
        assert_eq!(err.line(), 1);
        assert_eq!(err.column(), 1);
    }

    #[test]
    fn unclosed_chord_error_location() {
        let err = parse("[Am").unwrap_err();
        assert!(err.message.contains("unclosed chord"));
        assert_eq!(err.span.start.line, 1);
        assert_eq!(err.span.start.column, 1);
    }

    #[test]
    fn unclosed_chord_on_second_line() {
        let err = parse("Hello\n[Am").unwrap_err();
        assert!(err.message.contains("unclosed chord"));
        assert_eq!(err.span.start.line, 2);
        assert_eq!(err.span.start.column, 1);
    }

    #[test]
    fn unclosed_chord_mid_line() {
        let err = parse("text [Am").unwrap_err();
        assert!(err.message.contains("unclosed chord"));
        assert_eq!(err.span.start.line, 1);
        assert_eq!(err.span.start.column, 6);
    }

    #[test]
    fn unclosed_directive_error_location() {
        let err = parse("{title: oops").unwrap_err();
        assert!(err.message.contains("unclosed directive"));
        // Span points to EOF where the closing brace was expected.
        assert_eq!(err.span.start.line, 1);
        assert_eq!(err.span.start.column, 13);
    }

    #[test]
    fn unclosed_directive_on_third_line() {
        let err = parse("line one\nline two\n{title: oops").unwrap_err();
        assert!(err.message.contains("unclosed directive"));
        // Span points to EOF where the closing brace was expected.
        assert_eq!(err.span.start.line, 3);
        assert_eq!(err.span.start.column, 13);
    }

    #[test]
    fn empty_directive_error_location() {
        let err = parse("{}").unwrap_err();
        assert!(err.message.contains("empty directive name"));
        assert_eq!(err.span.start.line, 1);
        assert_eq!(err.span.start.column, 1);
    }

    #[test]
    fn empty_directive_with_colon_error_location() {
        let err = parse("{: value}").unwrap_err();
        assert!(err.message.contains("empty directive name"));
        assert_eq!(err.span.start.line, 1);
        assert_eq!(err.span.start.column, 1);
    }

    #[test]
    fn error_display_format_with_line_column() {
        let err = parse("first line\n{title: no close").unwrap_err();
        let msg = format!("{err}");
        // The error reports the position where the closing brace was expected.
        assert!(
            msg.starts_with("parse error at line 2, column 17:"),
            "unexpected display format: {msg}"
        );
    }

    #[test]
    fn unclosed_chord_at_end_of_line_error_location() {
        // [Am at end followed by newline — error points to the opening bracket
        let err = parse("[Am\nmore text").unwrap_err();
        assert!(err.message.contains("unclosed chord"));
        assert_eq!(err.span.start.line, 1);
        assert_eq!(err.span.start.column, 1);
    }

    #[test]
    fn unclosed_directive_at_eof_error_location() {
        let err = parse("{title").unwrap_err();
        assert!(err.message.contains("unclosed directive"));
        assert_eq!(err.span.start.line, 1);
        assert_eq!(err.span.start.column, 1);
    }

    #[test]
    fn whitespace_only_directive_name_error_location() {
        let err = parse("{   : value}").unwrap_err();
        assert!(err.message.contains("empty directive name"));
        assert_eq!(err.span.start.line, 1);
        assert_eq!(err.span.start.column, 1);
    }

    #[test]
    fn error_after_valid_content() {
        // Valid content followed by an error on a later line
        let input = "{title: Test}\n[Am]Hello\n[G";
        let err = parse(input).unwrap_err();
        assert!(err.message.contains("unclosed chord"));
        assert_eq!(err.span.start.line, 3);
        assert_eq!(err.span.start.column, 1);
    }

    #[test]
    fn multiple_errors_first_is_reported() {
        // Parser stops at first error — verify it's the correct one.
        let err = parse("{title\n{another").unwrap_err();
        assert!(err.message.contains("unclosed directive"));
        assert_eq!(err.span.start.line, 1);
    }

    // --- Tab verbatim (#59) ---

    #[test]
    fn tab_content_is_verbatim() {
        // Brackets inside tab should NOT be parsed as chords.
        let song = parse("{start_of_tab}\ne|---[0]---|\n{end_of_tab}").unwrap();
        // Line 0: start_of_tab directive
        // Line 1: verbatim text line
        // Line 2: end_of_tab directive
        if let Line::Lyrics(ref l) = song.lines[1] {
            assert_eq!(l.segments.len(), 1);
            assert!(l.segments[0].chord.is_none());
            assert_eq!(l.segments[0].text, "e|---[0]---|");
        } else {
            panic!("expected lyrics line for tab content");
        }
    }

    #[test]
    fn tab_content_preserves_braces() {
        let song = parse("{sot}\n{some text}\n{eot}").unwrap();
        if let Line::Lyrics(ref l) = song.lines[1] {
            assert_eq!(l.segments[0].text, "{some text}");
        } else {
            panic!("expected lyrics line for tab content");
        }
    }

    #[test]
    fn chords_parsed_after_tab_ends() {
        // After end_of_tab, chord parsing should resume.
        let song = parse("{sot}\ne|---|\n{eot}\n[Am]Hello").unwrap();
        // Line 3 should be a lyrics line with a chord.
        if let Line::Lyrics(ref l) = song.lines[3] {
            assert!(l.segments[0].chord.is_some());
            assert_eq!(l.segments[0].chord.as_ref().unwrap().name, "Am");
        } else {
            panic!("expected lyrics line with chord after tab section");
        }
    }

    // --- Grid verbatim (#107) ---

    #[test]
    fn grid_content_is_verbatim() {
        // Brackets inside grid should NOT be parsed as chords.
        let song = parse("{start_of_grid}\n| [Am] . | [C] . |\n{end_of_grid}").unwrap();
        // Line 0: start_of_grid directive
        // Line 1: verbatim text line
        // Line 2: end_of_grid directive
        if let Line::Lyrics(ref l) = song.lines[1] {
            assert_eq!(l.segments.len(), 1);
            assert!(l.segments[0].chord.is_none());
            assert_eq!(l.segments[0].text, "| [Am] . | [C] . |");
        } else {
            panic!("expected lyrics line for grid content");
        }
    }

    #[test]
    fn grid_content_preserves_braces() {
        let song = parse("{sog}\n{some text}\n{eog}").unwrap();
        if let Line::Lyrics(ref l) = song.lines[1] {
            assert_eq!(l.segments[0].text, "{some text}");
        } else {
            panic!("expected lyrics line for grid content");
        }
    }

    #[test]
    fn chords_parsed_after_grid_ends() {
        // After end_of_grid, chord parsing should resume.
        let song = parse("{sog}\n| Am . |\n{eog}\n[Am]Hello").unwrap();
        // Line 3 should be a lyrics line with a chord.
        if let Line::Lyrics(ref l) = song.lines[3] {
            assert!(l.segments[0].chord.is_some());
            assert_eq!(l.segments[0].chord.as_ref().unwrap().name, "Am");
        } else {
            panic!("expected lyrics line with chord after grid section");
        }
    }

    #[test]
    fn grid_inline_attribute_form_extracts_shape() {
        // `{start_of_grid shape="1+4x2+4"}` should resolve to
        // the StartOfGrid kind (NOT a custom-section), with the
        // attribute payload preserved in `value` for the
        // renderer to consume.
        let song = parse(r#"{start_of_grid shape="1+4x2+4"}\n| Am . |\n{end_of_grid}"#)
            .unwrap_or_else(|e| panic!("parse failed: {e:?}"));
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::StartOfGrid);
            assert_eq!(d.name, "start_of_grid");
            assert_eq!(d.value.as_deref(), Some(r#"shape="1+4x2+4""#));
        } else {
            panic!("expected start_of_grid directive");
        }
    }

    #[test]
    fn grid_inline_label_and_shape_attributes() {
        // Both attributes ride along in `value`; the renderers
        // pull them out with `extract_grid_label` / `GridShape::parse`.
        let song =
            parse(r#"{start_of_grid shape="4x4" label="Intro"}\n| G . |\n{end_of_grid}"#).unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::StartOfGrid);
            assert!(d.value.as_deref().unwrap().contains(r#"label="Intro""#));
        } else {
            panic!("expected start_of_grid directive");
        }
    }

    #[test]
    fn custom_section_with_space_preserves_whole_name() {
        // `{start_of_foo bar}` is a custom section "foo bar"
        // (per the legacy contract) — the inline-attribute
        // split MUST NOT fire because the prefix `start_of_foo`
        // resolves to `StartOfSection("foo")`, which is
        // excluded from the split eligibility list.
        let song = parse("{start_of_foo bar}\ntext\n{end_of_foo bar}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::StartOfSection("foo bar".to_string()));
            assert_eq!(d.value, None);
        } else {
            panic!("expected StartOfSection");
        }
    }

    #[test]
    fn explicit_colon_value_wins_over_inline_attrs() {
        // If the directive has a `:`-prefixed value, that value
        // is authoritative; inline attrs after the directive name
        // are folded into the name itself (not duplicated into
        // value). Spec edge case.
        let song = parse(r#"{start_of_grid shape="4x4": Verse}\n| G |\n{end_of_grid}"#).unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::StartOfGrid);
            // The explicit `:`-prefixed value `Verse` should win.
            assert_eq!(d.value.as_deref(), Some("Verse"));
        } else {
            panic!("expected start_of_grid directive");
        }
    }

    #[test]
    fn grid_short_aliases_sog_eog() {
        let song = parse("{sog}\n| Am |\n{eog}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::StartOfGrid);
            assert_eq!(d.name, "start_of_grid");
        } else {
            panic!("expected start_of_grid directive");
        }
        if let Line::Directive(ref d) = song.lines[2] {
            assert_eq!(d.kind, DirectiveKind::EndOfGrid);
            assert_eq!(d.name, "end_of_grid");
        } else {
            panic!("expected end_of_grid directive");
        }
    }

    #[test]
    fn grid_with_label() {
        let song = parse("{start_of_grid: Intro}\n| Am . | C . |\n{end_of_grid}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::StartOfGrid);
            assert_eq!(d.value.as_deref(), Some("Intro"));
        } else {
            panic!("expected start_of_grid directive with label");
        }
    }

    // --- Define directive (#37) ---

    #[test]
    fn define_directive_parsed() {
        let song = parse("{define: Asus4 base-fret 1 frets x 0 2 2 3 0}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::Define);
            assert_eq!(d.name, "define");
            assert_eq!(
                d.value.as_deref(),
                Some("Asus4 base-fret 1 frets x 0 2 2 3 0")
            );
        } else {
            panic!("expected define directive");
        }
    }

    #[test]
    fn chord_directive_parsed() {
        let song = parse("{chord: Asus4}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::ChordDirective);
            assert_eq!(d.value.as_deref(), Some("Asus4"));
        } else {
            panic!("expected chord directive");
        }
    }

    #[test]
    fn page_control_directives_long_form() {
        let song = parse("{new_page}\n{new_physical_page}\n{column_break}\n{columns: 2}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::NewPage);
            assert_eq!(d.name, "new_page");
            assert!(d.value.is_none());
        } else {
            panic!("expected new_page directive");
        }
        if let Line::Directive(ref d) = song.lines[1] {
            assert_eq!(d.kind, DirectiveKind::NewPhysicalPage);
            assert_eq!(d.name, "new_physical_page");
            assert!(d.value.is_none());
        } else {
            panic!("expected new_physical_page directive");
        }
        if let Line::Directive(ref d) = song.lines[2] {
            assert_eq!(d.kind, DirectiveKind::ColumnBreak);
            assert_eq!(d.name, "column_break");
            assert!(d.value.is_none());
        } else {
            panic!("expected column_break directive");
        }
        if let Line::Directive(ref d) = song.lines[3] {
            assert_eq!(d.kind, DirectiveKind::Columns);
            assert_eq!(d.name, "columns");
            assert_eq!(d.value.as_deref(), Some("2"));
        } else {
            panic!("expected columns directive");
        }
    }

    #[test]
    fn page_control_directives_short_form() {
        let song = parse("{np}\n{npp}\n{colb}\n{col: 3}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::NewPage);
            assert_eq!(d.name, "new_page");
        } else {
            panic!("expected new_page directive");
        }
        if let Line::Directive(ref d) = song.lines[1] {
            assert_eq!(d.kind, DirectiveKind::NewPhysicalPage);
            assert_eq!(d.name, "new_physical_page");
        } else {
            panic!("expected new_physical_page directive");
        }
        if let Line::Directive(ref d) = song.lines[2] {
            assert_eq!(d.kind, DirectiveKind::ColumnBreak);
            assert_eq!(d.name, "column_break");
        } else {
            panic!("expected column_break directive");
        }
        if let Line::Directive(ref d) = song.lines[3] {
            assert_eq!(d.kind, DirectiveKind::Columns);
            assert_eq!(d.name, "columns");
            assert_eq!(d.value.as_deref(), Some("3"));
        } else {
            panic!("expected columns directive");
        }
    }

    #[test]
    fn page_control_not_metadata() {
        let song = parse("{new_page}\n{columns: 2}").unwrap();
        // Page control directives should not populate metadata
        assert!(song.metadata.title.is_none());
        assert!(song.metadata.custom.is_empty());
    }

    // --- Lenient parsing / multi-error (#61) ---

    #[test]
    fn parse_lenient_no_errors() {
        let result = parse_lenient("{title: Test}\n[Am]Hello");
        assert!(result.is_ok());
        assert!(!result.has_errors());
        assert_eq!(result.song.metadata.title.as_deref(), Some("Test"));
        assert_eq!(result.song.lines.len(), 2);
    }

    #[test]
    fn parse_lenient_collects_multiple_errors() {
        // Two errors: unclosed directive on line 1, unclosed chord on line 3
        let result = parse_lenient("{title\nHello world\n[Am");
        assert!(result.has_errors());
        assert_eq!(result.errors.len(), 2);
        // The valid lyrics line in the middle should still be present.
        assert!(result.song.lines.iter().any(|l| {
            if let Line::Lyrics(ll) = l {
                ll.text() == "Hello world"
            } else {
                false
            }
        }));
    }

    #[test]
    fn parse_lenient_partial_ast_with_metadata() {
        // Title parses successfully, then an error, then more content.
        let result = parse_lenient("{title: My Song}\n{bad\n[G]La la");
        assert_eq!(result.errors.len(), 1);
        assert_eq!(result.song.metadata.title.as_deref(), Some("My Song"));
        // Title directive + skipped error line + lyrics = at least 2 lines
        assert!(result.song.lines.len() >= 2);
    }

    #[test]
    fn parse_lenient_all_lines_bad() {
        let result = parse_lenient("{unclosed\n[bad");
        assert_eq!(result.errors.len(), 2);
        assert!(result.song.lines.is_empty());
    }

    #[test]
    fn parse_lenient_error_locations() {
        let result = parse_lenient("{ok: fine}\n{bad\n[Am]Good\n{also bad");
        assert_eq!(result.errors.len(), 2);
        assert_eq!(result.errors[0].line(), 2);
        assert_eq!(result.errors[1].line(), 4);
    }

    #[test]
    fn parse_lenient_empty_input() {
        let result = parse_lenient("");
        assert!(result.is_ok());
        assert!(result.song.lines.is_empty());
    }

    #[test]
    fn parse_lenient_size_limit() {
        let opts = ParseOptions {
            max_input_size: 10,
            ..Default::default()
        };
        let result = parse_lenient_with_options("this input is too long", &opts);
        assert!(result.has_errors());
        assert_eq!(result.errors.len(), 1);
        assert!(result.errors[0].message.contains("exceeds maximum"));
    }

    #[test]
    fn parse_lenient_max_errors_limits_collection() {
        // Generate input with many errors (unclosed directives)
        let input: String = (0..100).map(|_| "{unclosed\n").collect();
        let opts = ParseOptions {
            max_errors: 5,
            ..Default::default()
        };
        let result = parse_lenient_with_options(&input, &opts);
        assert!(result.has_errors());
        assert_eq!(result.errors.len(), 5);
    }

    #[test]
    fn parse_lenient_zero_max_errors_disables_limit() {
        let input: String = (0..20).map(|_| "{unclosed\n").collect();
        let opts = ParseOptions {
            max_errors: 0,
            ..Default::default()
        };
        let result = parse_lenient_with_options(&input, &opts);
        assert_eq!(result.errors.len(), 20);
    }

    #[test]
    fn transpose_directive_parsed() {
        let song = parse("{transpose: 2}").expect("parse failed");
        assert_eq!(song.lines.len(), 1);
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::Transpose);
            assert_eq!(d.name, "transpose");
            assert_eq!(d.value.as_deref(), Some("2"));
        } else {
            panic!("expected transpose directive");
        }
    }

    #[test]
    fn transpose_directive_negative_value() {
        let song = parse("{transpose: -3}").expect("parse failed");
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::Transpose);
            assert_eq!(d.value.as_deref(), Some("-3"));
        } else {
            panic!("expected transpose directive");
        }
    }

    #[test]
    fn transpose_directive_no_value() {
        let song = parse("{transpose}").expect("parse failed");
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::Transpose);
            assert!(d.value.is_none());
        } else {
            panic!("expected transpose directive");
        }
    }

    #[test]
    fn transpose_directive_is_not_metadata() {
        let kind = DirectiveKind::Transpose;
        assert!(!kind.is_metadata());
    }

    #[test]
    fn transpose_directive_case_insensitive() {
        let song = parse("{Transpose: 5}").expect("parse failed");
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.kind, DirectiveKind::Transpose);
            assert_eq!(d.name, "transpose");
            assert_eq!(d.value.as_deref(), Some("5"));
        } else {
            panic!("expected transpose directive");
        }
    }

    // -- Custom section directives (#108) -----------------------------------

    #[test]
    fn custom_section_start_parsed() {
        let result = lines("{start_of_intro}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.name, "start_of_intro");
            assert_eq!(d.kind, DirectiveKind::StartOfSection("intro".to_string()));
            assert!(d.is_section_start());
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn custom_section_end_parsed() {
        let result = lines("{end_of_intro}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.name, "end_of_intro");
            assert_eq!(d.kind, DirectiveKind::EndOfSection("intro".to_string()));
            assert!(d.is_section_end());
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn custom_section_with_label() {
        let result = lines("{start_of_intro: Guitar Intro}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.name, "start_of_intro");
            assert_eq!(d.value.as_deref(), Some("Guitar Intro"));
            assert_eq!(d.kind, DirectiveKind::StartOfSection("intro".to_string()));
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn custom_section_lyrics_parsed_normally() {
        let song = parse("{start_of_intro}\n[Am]Hello [G]world\n{end_of_intro}").unwrap();
        // Lines: start_of_intro, lyrics, end_of_intro
        assert_eq!(song.lines.len(), 3);
        if let Line::Lyrics(ref l) = song.lines[1] {
            assert!(l.has_chords());
            assert_eq!(l.segments.len(), 2);
            assert_eq!(l.segments[0].chord.as_ref().unwrap().name, "Am");
        } else {
            panic!("expected lyrics line inside custom section");
        }
    }

    #[test]
    fn custom_section_various_names() {
        for name in &["outro", "solo", "interlude", "coda", "pre_chorus"] {
            let input = format!("{{start_of_{name}}}");
            let result = lines(&input);
            if let Line::Directive(ref d) = result[0] {
                assert_eq!(d.name, format!("start_of_{name}"));
                assert!(d.is_section_start(), "should be section start for {name}");
            } else {
                panic!("expected directive for {name}");
            }
        }
    }

    // -- Inline markup in lyrics -------------------------------------------

    #[test]
    fn lyrics_with_bold_markup() {
        use crate::inline_markup::TextSpan;

        let result = lines("[Am]Hello <b>world</b>");
        match &result[0] {
            Line::Lyrics(lyrics) => {
                assert_eq!(lyrics.segments.len(), 1);
                let seg = &lyrics.segments[0];
                assert_eq!(seg.text, "Hello world");
                assert_eq!(
                    seg.spans,
                    vec![
                        TextSpan::Plain("Hello ".to_string()),
                        TextSpan::Bold(vec![TextSpan::Plain("world".to_string())]),
                    ]
                );
            }
            _ => panic!("expected lyrics line"),
        }
    }

    #[test]
    fn custom_section_case_insensitive() {
        let result = lines("{Start_Of_Intro}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.name, "start_of_intro");
            assert_eq!(d.kind, DirectiveKind::StartOfSection("intro".to_string()));
        } else {
            panic!("expected directive");
        }
    }

    // --- Image directive (#124) ---

    #[test]
    fn image_directive_basic() {
        let song = parse("{image: src=photo.jpg}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.name, "image");
            if let DirectiveKind::Image(ref attrs) = d.kind {
                assert_eq!(attrs.src, "photo.jpg");
                assert!(attrs.width.is_none());
                assert!(attrs.height.is_none());
                assert!(attrs.scale.is_none());
                assert!(attrs.title.is_none());
                assert!(attrs.anchor.is_none());
            } else {
                panic!("expected Image directive kind");
            }
        } else {
            panic!("expected directive");
        }
    }

    // --- Inline markup (#112) ---

    #[test]
    fn lyrics_without_markup_has_empty_spans() {
        let result = lines("[Am]Hello world");
        match &result[0] {
            Line::Lyrics(lyrics) => {
                assert_eq!(lyrics.segments[0].text, "Hello world");
                assert!(lyrics.segments[0].spans.is_empty());
            }
            _ => panic!("expected lyrics line"),
        }
    }

    #[test]
    fn image_directive_all_attributes() {
        let song =
            parse(r#"{image: src=logo.png width=200 height=100 scale=0.5 title="Album Cover" anchor=top}"#)
                .unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            if let DirectiveKind::Image(ref attrs) = d.kind {
                assert_eq!(attrs.src, "logo.png");
                assert_eq!(attrs.width.as_deref(), Some("200"));
                assert_eq!(attrs.height.as_deref(), Some("100"));
                assert_eq!(attrs.scale.as_deref(), Some("0.5"));
                assert_eq!(attrs.title.as_deref(), Some("Album Cover"));
                assert_eq!(attrs.anchor.as_deref(), Some("top"));
            } else {
                panic!("expected Image directive kind");
            }
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn lyrics_with_nested_markup() {
        use crate::inline_markup::TextSpan;

        let result = lines("<b><i>both</i></b>");
        match &result[0] {
            Line::Lyrics(lyrics) => {
                assert_eq!(lyrics.segments[0].text, "both");
                assert_eq!(
                    lyrics.segments[0].spans,
                    vec![TextSpan::Bold(vec![TextSpan::Italic(vec![
                        TextSpan::Plain("both".to_string())
                    ])])]
                );
            }
            _ => panic!("expected lyrics line"),
        }
    }

    #[test]
    fn image_directive_quoted_value_with_spaces() {
        let song = parse(r#"{image: src=cover.jpg title="My Great Album"}"#).unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            if let DirectiveKind::Image(ref attrs) = d.kind {
                assert_eq!(attrs.src, "cover.jpg");
                assert_eq!(attrs.title.as_deref(), Some("My Great Album"));
            } else {
                panic!("expected Image directive kind");
            }
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn lyrics_markup_text_field_has_stripped_content() {
        let result = lines("<b>bold</b> and <i>italic</i> text");
        match &result[0] {
            Line::Lyrics(lyrics) => {
                // text field should have markup stripped
                assert_eq!(lyrics.segments[0].text, "bold and italic text");
                // spans should be populated
                assert!(!lyrics.segments[0].spans.is_empty());
            }
            _ => panic!("expected lyrics line"),
        }
    }

    #[test]
    fn image_directive_no_value() {
        let song = parse("{image}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.name, "image");
            if let DirectiveKind::Image(ref attrs) = d.kind {
                assert_eq!(attrs.src, "");
            } else {
                panic!("expected Image directive kind");
            }
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn image_directive_unknown_attributes_ignored() {
        let song = parse("{image: src=pic.jpg unknown=foo bar}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            if let DirectiveKind::Image(ref attrs) = d.kind {
                assert_eq!(attrs.src, "pic.jpg");
                // unknown attribute is silently ignored
            } else {
                panic!("expected Image directive kind");
            }
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn image_directive_case_insensitive() {
        let song = parse("{IMAGE: src=photo.jpg}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            assert_eq!(d.name, "image");
            assert!(d.kind.is_image());
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn image_directive_width_only() {
        let song = parse("{image: src=img.png width=50%}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            if let DirectiveKind::Image(ref attrs) = d.kind {
                assert_eq!(attrs.src, "img.png");
                assert_eq!(attrs.width.as_deref(), Some("50%"));
                assert!(attrs.height.is_none());
            } else {
                panic!("expected Image directive kind");
            }
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn image_directive_preserves_raw_value() {
        let song = parse("{image: src=photo.jpg width=200}").unwrap();
        if let Line::Directive(ref d) = song.lines[0] {
            // The raw value string is preserved.
            assert_eq!(d.value.as_deref(), Some("src=photo.jpg width=200"));
        } else {
            panic!("expected directive");
        }
    }

    // --- parse_image_attributes unit tests ---

    #[test]
    fn parse_image_attributes_empty_input() {
        let attrs = super::parse_image_attributes("");
        assert_eq!(attrs.src, "");
        assert!(attrs.width.is_none());
    }

    #[test]
    fn parse_image_attributes_src_only() {
        let attrs = super::parse_image_attributes("src=test.png");
        assert_eq!(attrs.src, "test.png");
    }

    #[test]
    fn parse_image_attributes_multiple() {
        let attrs = super::parse_image_attributes("src=a.jpg width=100 height=200");
        assert_eq!(attrs.src, "a.jpg");
        assert_eq!(attrs.width.as_deref(), Some("100"));
        assert_eq!(attrs.height.as_deref(), Some("200"));
    }

    #[test]
    fn parse_image_attributes_quoted_value() {
        let attrs = super::parse_image_attributes(r#"src=a.jpg title="Hello World""#);
        assert_eq!(attrs.src, "a.jpg");
        assert_eq!(attrs.title.as_deref(), Some("Hello World"));
    }

    #[test]
    fn parse_image_attributes_extra_whitespace() {
        let attrs = super::parse_image_attributes("  src=a.jpg   width=100  ");
        assert_eq!(attrs.src, "a.jpg");
        assert_eq!(attrs.width.as_deref(), Some("100"));
    }

    #[test]
    fn parse_image_attributes_case_insensitive_keys() {
        let attrs = super::parse_image_attributes("SRC=photo.jpg WIDTH=200 Height=100");
        assert_eq!(attrs.src, "photo.jpg");
        assert_eq!(attrs.width.as_deref(), Some("200"));
        assert_eq!(attrs.height.as_deref(), Some("100"));
    }

    #[test]
    fn parse_image_attributes_mixed_case_keys() {
        let attrs = super::parse_image_attributes("Src=a.jpg Scale=0.5 Title=test Anchor=column");
        assert_eq!(attrs.src, "a.jpg");
        assert_eq!(attrs.scale.as_deref(), Some("0.5"));
        assert_eq!(attrs.title.as_deref(), Some("test"));
        assert_eq!(attrs.anchor.as_deref(), Some("column"));
    }

    #[test]
    fn parse_image_attributes_src_truncated_at_limit() {
        let long_src = "a".repeat(5000);
        let input = format!("src={long_src}");
        let attrs = super::parse_image_attributes(&input);
        assert_eq!(attrs.src.len(), super::IMAGE_SRC_MAX_BYTES);
    }

    #[test]
    fn parse_image_attributes_other_attrs_truncated_at_limit() {
        let long_title = "x".repeat(2000);
        let input = format!("src=ok.jpg title=\"{long_title}\" width={long_title}");
        let attrs = super::parse_image_attributes(&input);
        assert_eq!(attrs.src, "ok.jpg");
        assert_eq!(
            attrs.title.as_deref().map(str::len),
            Some(super::IMAGE_ATTR_MAX_BYTES)
        );
        assert_eq!(
            attrs.width.as_deref().map(str::len),
            Some(super::IMAGE_ATTR_MAX_BYTES)
        );
    }

    #[test]
    fn parse_image_attributes_truncation_respects_utf8_boundary() {
        // Each CJK character is 3 bytes. 341 chars = 1023 bytes, 342 = 1026.
        // With a 1024 limit the truncation must land on a char boundary.
        let cjk = "".repeat(342); // 1026 bytes
        let input = format!("title=\"{cjk}\"");
        let attrs = super::parse_image_attributes(&input);
        let title = attrs.title.unwrap();
        assert!(title.len() <= super::IMAGE_ATTR_MAX_BYTES);
        // Must be valid UTF-8 (String guarantees this, but verify length is
        // at a 3-byte boundary).
        assert_eq!(title.len(), 1023); // 341 * 3
    }

    #[test]
    fn parse_image_attributes_values_within_limit_unchanged() {
        let title = "a".repeat(1024);
        let input = format!("src=ok.jpg title=\"{title}\"");
        let attrs = super::parse_image_attributes(&input);
        assert_eq!(attrs.title.as_deref(), Some(title.as_str()));
    }

    #[test]
    fn truncate_string_empty() {
        assert_eq!(super::truncate_string(String::new(), 100), "");
    }

    #[test]
    fn split_key_value_pairs_basic() {
        let pairs = super::split_key_value_pairs("key=value");
        assert_eq!(pairs, vec![("key".to_string(), "value".to_string())]);
    }

    #[test]
    fn split_key_value_pairs_quoted() {
        let pairs = super::split_key_value_pairs(r#"key="hello world""#);
        assert_eq!(pairs, vec![("key".to_string(), "hello world".to_string())]);
    }

    #[test]
    fn split_key_value_pairs_mixed() {
        let pairs = super::split_key_value_pairs(r#"a=1 b="two three" c=4"#);
        assert_eq!(pairs.len(), 3);
        assert_eq!(pairs[0], ("a".to_string(), "1".to_string()));
        assert_eq!(pairs[1], ("b".to_string(), "two three".to_string()));
        assert_eq!(pairs[2], ("c".to_string(), "4".to_string()));
    }

    #[test]
    fn split_key_value_pairs_no_equals() {
        let pairs = super::split_key_value_pairs("bare_token");
        assert!(pairs.is_empty());
    }

    #[test]
    fn split_key_value_pairs_empty() {
        let pairs = super::split_key_value_pairs("");
        assert!(pairs.is_empty());
    }

    #[test]
    fn split_key_value_pairs_unterminated_quote() {
        // Unterminated quote: value should be everything after the opening quote.
        let pairs = super::split_key_value_pairs(r#"key="hello world"#);
        assert_eq!(pairs, vec![("key".to_string(), "hello world".to_string())]);
    }

    #[test]
    fn parse_image_attributes_unterminated_quoted_title() {
        // From issue #288 (M5): unterminated quoted value should be accepted
        // gracefully — the value is everything from the opening quote to EOI.
        let attrs = super::parse_image_attributes(r#"src=photo.jpg title="My Album"#);
        assert_eq!(attrs.src, "photo.jpg");
        assert_eq!(attrs.title.as_deref(), Some("My Album"));
    }

    #[test]
    fn parse_image_attributes_unterminated_quote_with_trailing_attrs() {
        // When a quote is not terminated, all remaining text becomes the value.
        let attrs = super::parse_image_attributes(r#"src=photo.jpg title="My Album width=100"#);
        assert_eq!(attrs.src, "photo.jpg");
        assert_eq!(attrs.title.as_deref(), Some("My Album width=100"));
        // width should NOT be parsed since it was consumed as part of the title.
        assert!(attrs.width.is_none());
    }
}

#[cfg(test)]
mod delegate_tests {
    use super::*;
    use crate::ast::{DirectiveKind, Line};

    fn lines(input: &str) -> Vec<Line> {
        parse(input).expect("parse failed").lines
    }

    #[test]
    fn abc_content_is_verbatim() {
        let song = parse("{start_of_abc}\nX:1\nK:G\n{end_of_abc}").unwrap();
        assert_eq!(song.lines.len(), 4);
        if let Line::Lyrics(ref l) = song.lines[1] {
            assert_eq!(l.segments.len(), 1);
            assert!(l.segments[0].chord.is_none());
            assert_eq!(l.segments[0].text, "X:1");
        } else {
            panic!("expected lyrics line for ABC content");
        }
    }

    #[test]
    fn abc_preserves_brackets() {
        let song = parse("{start_of_abc}\n|:GABc|[1d2d2:|[2d4d4:|\n{end_of_abc}").unwrap();
        if let Line::Lyrics(ref l) = song.lines[1] {
            assert_eq!(l.segments[0].text, "|:GABc|[1d2d2:|[2d4d4:|");
        } else {
            panic!("expected verbatim lyrics line");
        }
    }

    #[test]
    fn ly_content_is_verbatim() {
        let song = parse("{start_of_ly}\n\\relative c' { c4 d e f }\n{end_of_ly}").unwrap();
        assert_eq!(song.lines.len(), 3);
        if let Line::Lyrics(ref l) = song.lines[1] {
            assert!(l.segments[0].chord.is_none());
        } else {
            panic!("expected lyrics line for Lilypond content");
        }
    }

    #[test]
    fn svg_content_is_verbatim() {
        let song = parse("{start_of_svg}\n<svg><rect/></svg>\n{end_of_svg}").unwrap();
        assert_eq!(song.lines.len(), 3);
        if let Line::Lyrics(ref l) = song.lines[1] {
            assert!(l.segments[0].chord.is_none());
        } else {
            panic!("expected lyrics line for SVG content");
        }
    }

    #[test]
    fn textblock_content_is_verbatim() {
        let song = parse("{start_of_textblock}\n[Am]Not a chord\n{end_of_textblock}").unwrap();
        assert_eq!(song.lines.len(), 3);
        if let Line::Lyrics(ref l) = song.lines[1] {
            assert_eq!(l.segments.len(), 1);
            assert!(l.segments[0].chord.is_none());
            assert_eq!(l.segments[0].text, "[Am]Not a chord");
        } else {
            panic!("expected lyrics line for textblock content");
        }
    }

    #[test]
    fn textblock_preserves_braces() {
        let song = parse("{start_of_textblock}\n{some directive}\n{end_of_textblock}").unwrap();
        if let Line::Lyrics(ref l) = song.lines[1] {
            assert_eq!(l.segments[0].text, "{some directive}");
        } else {
            panic!("expected verbatim lyrics line");
        }
    }

    #[test]
    fn chords_parsed_after_abc_ends() {
        let song = parse("{start_of_abc}\nX:1\n{end_of_abc}\n[Am]Hello").unwrap();
        if let Line::Lyrics(ref l) = song.lines[3] {
            assert!(l.segments[0].chord.is_some());
            assert_eq!(l.segments[0].chord.as_ref().unwrap().name, "Am");
        } else {
            panic!("expected lyrics line with chord after ABC section");
        }
    }

    #[test]
    fn chords_parsed_after_ly_ends() {
        let song = parse("{start_of_ly}\nnotes\n{end_of_ly}\n[G]Hello").unwrap();
        if let Line::Lyrics(ref l) = song.lines[3] {
            assert!(l.segments[0].chord.is_some());
            assert_eq!(l.segments[0].chord.as_ref().unwrap().name, "G");
        } else {
            panic!("expected lyrics line with chord after Lilypond section");
        }
    }

    #[test]
    fn chords_parsed_after_svg_ends() {
        let song = parse("{start_of_svg}\n<svg/>\n{end_of_svg}\n[C]Hello").unwrap();
        if let Line::Lyrics(ref l) = song.lines[3] {
            assert!(l.segments[0].chord.is_some());
            assert_eq!(l.segments[0].chord.as_ref().unwrap().name, "C");
        } else {
            panic!("expected lyrics line with chord after SVG section");
        }
    }

    #[test]
    fn chords_parsed_after_textblock_ends() {
        let song = parse("{start_of_textblock}\ntext\n{end_of_textblock}\n[D]Hello").unwrap();
        if let Line::Lyrics(ref l) = song.lines[3] {
            assert!(l.segments[0].chord.is_some());
            assert_eq!(l.segments[0].chord.as_ref().unwrap().name, "D");
        } else {
            panic!("expected lyrics line with chord after textblock section");
        }
    }

    #[test]
    fn abc_directive_with_label() {
        let result = lines("{start_of_abc: My Melody}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.kind, DirectiveKind::StartOfAbc);
            assert_eq!(d.value.as_deref(), Some("My Melody"));
        } else {
            panic!("expected directive");
        }
    }

    // -- Selector suffix parsing --------------------------------------------

    #[test]
    fn selector_suffix_on_metadata_directive() {
        let result = lines("{title-piano: My Song}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.name, "title");
            assert_eq!(d.value.as_deref(), Some("My Song"));
            assert_eq!(d.kind, DirectiveKind::Title);
            assert_eq!(d.selector.as_deref(), Some("piano"));
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn textblock_directive_with_label() {
        let result = lines("{start_of_textblock: Notes}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.kind, DirectiveKind::StartOfTextblock);
            assert_eq!(d.value.as_deref(), Some("Notes"));
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn selector_suffix_on_key_directive() {
        let result = lines("{key-bass: E}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.name, "key");
            assert_eq!(d.value.as_deref(), Some("E"));
            assert_eq!(d.kind, DirectiveKind::Key);
            assert_eq!(d.selector.as_deref(), Some("bass"));
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn delegate_sections_not_custom() {
        assert_eq!(
            DirectiveKind::from_name("start_of_abc"),
            DirectiveKind::StartOfAbc
        );
        assert_eq!(
            DirectiveKind::from_name("start_of_ly"),
            DirectiveKind::StartOfLy
        );
        assert_eq!(
            DirectiveKind::from_name("start_of_svg"),
            DirectiveKind::StartOfSvg
        );
        assert_eq!(
            DirectiveKind::from_name("start_of_textblock"),
            DirectiveKind::StartOfTextblock
        );
    }

    #[test]
    fn lyrics_markup_preserves_backward_compat() {
        // The LyricsLine::text() method should return plain text
        let result = lines("[Am]Hello <b>bold</b> [G]world");
        match &result[0] {
            Line::Lyrics(lyrics) => {
                assert_eq!(lyrics.text(), "Hello bold world");
            }
            _ => panic!("expected lyrics line"),
        }
    }

    // -- NewSong directive --------------------------------------------------

    #[test]
    fn new_song_directive_kind() {
        assert_eq!(DirectiveKind::from_name("new_song"), DirectiveKind::NewSong);
        assert_eq!(DirectiveKind::from_name("ns"), DirectiveKind::NewSong);
        assert_eq!(DirectiveKind::from_name("NEW_SONG"), DirectiveKind::NewSong);
        assert_eq!(DirectiveKind::from_name("Ns"), DirectiveKind::NewSong);
    }

    #[test]
    fn new_song_canonical_name() {
        assert_eq!(DirectiveKind::NewSong.canonical_name(), "new_song");
    }

    #[test]
    fn new_song_parsed_as_directive() {
        let result = lines("{new_song}");
        assert_eq!(result.len(), 1);
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.name, "new_song");
            assert_eq!(d.kind, DirectiveKind::NewSong);
            assert!(d.value.is_none());
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn selector_suffix_on_comment_directive() {
        // Comment directives with selectors are kept as Line::Directive
        // (not converted to Line::Comment) to preserve the selector.
        let result = lines("{comment-piano: Play softly}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.kind, DirectiveKind::Comment);
            assert_eq!(d.value.as_deref(), Some("Play softly"));
            assert_eq!(d.selector.as_deref(), Some("piano"));
        } else {
            panic!(
                "expected directive for comment with selector, got {:?}",
                result[0]
            );
        }
    }

    #[test]
    fn ns_alias_parsed_as_directive() {
        let result = lines("{ns}");
        assert_eq!(result.len(), 1);
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.name, "new_song");
            assert_eq!(d.kind, DirectiveKind::NewSong);
        } else {
            panic!("expected directive");
        }
    }

    // -- Multi-song parsing -------------------------------------------------

    #[test]
    fn parse_multi_single_song() {
        let input = "{title: Only Song}\n[G]Hello";
        let songs = parse_multi(input).unwrap();
        assert_eq!(songs.len(), 1);
        assert_eq!(songs[0].metadata.title.as_deref(), Some("Only Song"));
    }

    #[test]
    fn parse_multi_two_songs() {
        let input = "{title: Song One}\nLyrics one\n{new_song}\n{title: Song Two}\nLyrics two";
        let songs = parse_multi(input).unwrap();
        assert_eq!(songs.len(), 2);
        assert_eq!(songs[0].metadata.title.as_deref(), Some("Song One"));
        assert_eq!(songs[1].metadata.title.as_deref(), Some("Song Two"));
    }

    #[test]
    fn parse_multi_ns_alias() {
        let input = "{title: First}\n{ns}\n{title: Second}";
        let songs = parse_multi(input).unwrap();
        assert_eq!(songs.len(), 2);
        assert_eq!(songs[0].metadata.title.as_deref(), Some("First"));
        assert_eq!(songs[1].metadata.title.as_deref(), Some("Second"));
    }

    #[test]
    fn parse_multi_three_songs() {
        let input = "{title: A}\n{new_song}\n{title: B}\n{new_song}\n{title: C}";
        let songs = parse_multi(input).unwrap();
        assert_eq!(songs.len(), 3);
        assert_eq!(songs[0].metadata.title.as_deref(), Some("A"));
        assert_eq!(songs[1].metadata.title.as_deref(), Some("B"));
        assert_eq!(songs[2].metadata.title.as_deref(), Some("C"));
    }

    #[test]
    fn parse_multi_empty_first_song() {
        // {new_song} at the very beginning means the first segment is empty
        let input = "{new_song}\n{title: Second}";
        let songs = parse_multi(input).unwrap();
        assert_eq!(songs.len(), 2);
        assert!(songs[0].metadata.title.is_none());
        assert_eq!(songs[1].metadata.title.as_deref(), Some("Second"));
    }

    #[test]
    fn parse_multi_case_insensitive() {
        let input = "{title: A}\n{NEW_SONG}\n{title: B}";
        let songs = parse_multi(input).unwrap();
        assert_eq!(songs.len(), 2);
    }

    #[test]
    fn parse_multi_with_whitespace() {
        let input = "{title: A}\n{ new_song }\n{title: B}";
        let songs = parse_multi(input).unwrap();
        assert_eq!(songs.len(), 2);
    }

    #[test]
    fn parse_multi_crlf_line_endings() {
        let input = "{title: A}\r\n[G]Hello\r\n{new_song}\r\n{title: B}\r\n[Am]World\r\n";
        let songs = parse_multi(input).unwrap();
        assert_eq!(songs.len(), 2);
        assert_eq!(songs[0].metadata.title, Some("A".to_string()));
        assert_eq!(songs[1].metadata.title, Some("B".to_string()));
    }

    #[test]
    fn parse_multi_lenient_collects_errors() {
        let input = "{title: Good}\n[Am\n{new_song}\n{title: Also Good}\n[G]Hello";
        let result = parse_multi_lenient(input);
        assert_eq!(result.results.len(), 2);
        assert!(result.results[0].has_errors()); // unclosed chord
        assert!(result.results[1].is_ok());
        assert_eq!(
            result.results[1].song.metadata.title.as_deref(),
            Some("Also Good")
        );
    }

    #[test]
    fn comment_without_selector_still_becomes_line_comment() {
        let result = lines("{comment: Normal comment}");
        assert!(
            matches!(result[0], Line::Comment(CommentStyle::Normal, _)),
            "comment without selector should still be Line::Comment"
        );
    }

    #[test]
    fn parse_multi_songs_helper() {
        let input = "{title: A}\n{new_song}\n{title: B}";
        let result = parse_multi_lenient(input);
        let songs = result.songs();
        assert_eq!(songs.len(), 2);
        assert_eq!(songs[0].metadata.title.as_deref(), Some("A"));
        assert_eq!(songs[1].metadata.title.as_deref(), Some("B"));
    }

    #[test]
    fn parse_multi_preserves_song_content() {
        let input = "{title: Song One}
{artist: Artist One}
{start_of_chorus}
[G]La la [C]la
{end_of_chorus}
{new_song}
{title: Song Two}
{key: Am}
[Am]Hello [G]world";
        let songs = parse_multi(input).unwrap();
        assert_eq!(songs.len(), 2);

        // First song
        assert_eq!(songs[0].metadata.title.as_deref(), Some("Song One"));
        assert_eq!(songs[0].metadata.artists, vec!["Artist One".to_string()]);

        // Second song
        assert_eq!(songs[1].metadata.title.as_deref(), Some("Song Two"));
        assert_eq!(songs[1].metadata.key.as_deref(), Some("Am"));
    }

    #[test]
    fn is_new_song_line_detection() {
        assert!(is_new_song_line("{new_song}"));
        assert!(is_new_song_line("{ns}"));
        assert!(is_new_song_line("{NEW_SONG}"));
        assert!(is_new_song_line("{NS}"));
        assert!(is_new_song_line("{ new_song }"));
        assert!(is_new_song_line("{ ns }"));
        // Directives with values should also be detected (#315).
        assert!(is_new_song_line("{new_song: value}"));
        assert!(is_new_song_line("{ns: tag}"));
        assert!(is_new_song_line("{ new_song : tag }"));

        assert!(!is_new_song_line("{title}"));
        assert!(!is_new_song_line("new_song"));
        assert!(!is_new_song_line(""));
        assert!(!is_new_song_line("{new_songs}"));
    }

    #[test]
    fn split_at_new_song_bare_cr() {
        // Bare \r (classic Mac line endings) should be handled correctly (#313).
        let input = "{title: A}\r{new_song}\r{title: B}";
        let segments = split_at_new_song(input);
        assert_eq!(segments.len(), 2);
        assert!(segments[0].contains("title: A"));
        assert!(segments[1].contains("title: B"));
    }

    #[test]
    fn single_parse_ignores_new_song() {
        // The single-song parse() should treat {new_song} as a regular directive
        // and not fail.
        let song = parse("{title: Test}\n{new_song}\n[G]Hello").unwrap();
        assert_eq!(song.metadata.title.as_deref(), Some("Test"));
        // The {new_song} should appear as a Directive line
        let has_new_song = song
            .lines
            .iter()
            .any(|l| matches!(l, Line::Directive(d) if d.kind == DirectiveKind::NewSong));
        assert!(has_new_song);
    }

    #[test]
    fn selector_suffix_on_environment_directive() {
        let result = lines("{start_of_chorus-piano}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.name, "start_of_chorus");
            assert_eq!(d.kind, DirectiveKind::StartOfChorus);
            assert_eq!(d.selector.as_deref(), Some("piano"));
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn selector_suffix_on_end_environment() {
        let result = lines("{end_of_verse-guitar}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.name, "end_of_verse");
            assert_eq!(d.kind, DirectiveKind::EndOfVerse);
            assert_eq!(d.selector.as_deref(), Some("guitar"));
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn no_selector_on_plain_directive() {
        let result = lines("{title: My Song}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.selector, None);
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn selector_suffix_case_insensitive() {
        let result = lines("{Title-PIANO: My Song}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.kind, DirectiveKind::Title);
            assert_eq!(d.selector.as_deref(), Some("piano"));
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn selector_with_short_alias() {
        let result = lines("{t-guitar: My Song}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.name, "title");
            assert_eq!(d.kind, DirectiveKind::Title);
            assert_eq!(d.selector.as_deref(), Some("guitar"));
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn unknown_directive_with_hyphen_no_selector() {
        // "my-custom" -> "my" is Unknown, so the whole name is Unknown
        let result = lines("{my-custom: value}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.kind, DirectiveKind::Unknown("my-custom".to_string()));
            assert_eq!(d.selector, None);
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn custom_section_with_selector() {
        let result = lines("{start_of_intro-piano}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(d.kind, DirectiveKind::StartOfSection("intro".to_string()));
            assert_eq!(d.selector.as_deref(), Some("piano"));
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    #[should_panic(expected = "token list must contain at least an Eof token")]
    fn parser_new_panics_on_empty_tokens() {
        let _parser = Parser::new(Vec::new());
    }

    #[test]
    fn parser_try_new_returns_err_on_empty_tokens() {
        // Non-panicking counterpart to Parser::new. Callers that build
        // token vectors by hand (LSP, fuzz harnesses) can recover from an
        // empty stream without aborting.
        //
        // Parser does not derive Debug, so unwrap the Result by hand rather
        // than via `expect_err`.
        match Parser::try_new(Vec::new()) {
            Ok(_) => panic!("try_new should reject an empty token list"),
            Err(err) => {
                assert!(
                    err.message.contains("empty token list"),
                    "unexpected message: {}",
                    err.message,
                );
                assert_eq!(err.line(), 1);
                assert_eq!(err.column(), 1);
            }
        }
    }

    #[test]
    fn parser_try_new_accepts_non_empty_tokens() {
        let tokens = Lexer::new("[C]Hello").tokenize();
        let song = Parser::try_new(tokens)
            .expect("try_new should accept a non-empty token list")
            .parse()
            .expect("parse failed");
        assert_eq!(song.lines.len(), 1);
    }

    // -- Multi-song input size limits -----------------------------------------

    #[test]
    fn multi_song_oversized_input_rejected() {
        let opts = ParseOptions {
            max_input_size: 10,
            ..Default::default()
        };
        let input = "{title: A}\n{new_song}\n{title: B}";
        let result = parse_multi_with_options(input, &opts);
        assert!(result.is_err());
        assert!(result.unwrap_err().message.contains("exceeds maximum"));
    }

    #[test]
    fn multi_song_lenient_oversized_input_rejected() {
        let opts = ParseOptions {
            max_input_size: 10,
            ..Default::default()
        };
        let input = "{title: A}\n{new_song}\n{title: B}";
        let result = parse_multi_lenient_with_options(input, &opts);
        assert_eq!(result.results.len(), 1);
        assert!(
            result.results[0].errors[0]
                .message
                .contains("exceeds maximum")
        );
    }

    #[test]
    fn multi_song_within_limit_succeeds() {
        let opts = ParseOptions {
            max_input_size: 1000,
            ..Default::default()
        };
        let input = "{title: A}\n{new_song}\n{title: B}";
        let result = parse_multi_with_options(input, &opts);
        assert!(result.is_ok());
        assert_eq!(result.unwrap().len(), 2);
    }

    // -- Config override directives -------------------------------------------

    #[test]
    fn config_override_basic() {
        let result = lines("{+config.pdf.margins.top: 100}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(
                d.kind,
                DirectiveKind::ConfigOverride("pdf.margins.top".to_string())
            );
            assert_eq!(d.value.as_deref(), Some("100"));
            assert_eq!(d.name, "+config.pdf.margins.top");
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn config_override_string_value() {
        let result = lines("{+config.pdf.theme.foreground: blue}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(
                d.kind,
                DirectiveKind::ConfigOverride("pdf.theme.foreground".to_string())
            );
            assert_eq!(d.value.as_deref(), Some("blue"));
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn config_override_no_value() {
        let result = lines("{+config.settings.lyrics_only}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(
                d.kind,
                DirectiveKind::ConfigOverride("settings.lyrics_only".to_string())
            );
            assert_eq!(d.value, None);
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn config_override_case_insensitive() {
        let result = lines("{+Config.PDF.Margins.Top: 50}");
        if let Line::Directive(ref d) = result[0] {
            assert_eq!(
                d.kind,
                DirectiveKind::ConfigOverride("pdf.margins.top".to_string())
            );
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn bare_plus_config_is_unknown() {
        // {+config} without a dot-separated key is Unknown
        let result = lines("{+config: something}");
        if let Line::Directive(ref d) = result[0] {
            assert!(matches!(d.kind, DirectiveKind::Unknown(_)));
        } else {
            panic!("expected directive");
        }
    }

    #[test]
    fn config_overrides_extracted_from_song() {
        let song = crate::parse(
            "{title: Test}\n{+config.pdf.margins.top: 100}\n{+config.settings.transpose: 2}\n",
        )
        .unwrap();
        let overrides = song.config_overrides();
        assert_eq!(overrides.len(), 2);
        assert_eq!(overrides[0], ("pdf.margins.top", "100"));
        assert_eq!(overrides[1], ("settings.transpose", "2"));
    }

    #[test]
    fn config_overrides_empty_when_none() {
        let song = crate::parse("{title: Test}\n[G]Hello\n").unwrap();
        assert!(song.config_overrides().is_empty());
    }

    #[test]
    fn config_overrides_not_in_multi_song_leak() {
        let songs = crate::parse_multi(
            "{title: A}\n{+config.settings.transpose: 5}\n{new_song}\n{title: B}\n",
        )
        .unwrap();
        assert_eq!(songs.len(), 2);
        assert_eq!(songs[0].config_overrides().len(), 1);
        assert!(songs[1].config_overrides().is_empty());
    }
}

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

    #[test]
    fn test_metadata_entries_capped_at_limit() {
        // Generate more subtitles than the cap allows.
        let count = Parser::MAX_METADATA_ENTRIES + 100;
        let mut input = String::new();
        for i in 0..count {
            input.push_str(&format!("{{subtitle: sub{i}}}\n"));
        }
        let song = parse(&input).unwrap();
        assert_eq!(
            song.metadata.subtitles.len(),
            Parser::MAX_METADATA_ENTRIES,
            "subtitles should be capped at MAX_METADATA_ENTRIES"
        );
    }

    #[test]
    fn test_metadata_cap_applies_per_field() {
        // Each field has its own cap — filling subtitles does not affect artists.
        let mut input = String::new();
        for i in 0..Parser::MAX_METADATA_ENTRIES {
            input.push_str(&format!("{{subtitle: s{i}}}\n"));
        }
        input.push_str("{artist: Alice}\n");
        let song = parse(&input).unwrap();
        assert_eq!(song.metadata.subtitles.len(), Parser::MAX_METADATA_ENTRIES);
        assert_eq!(song.metadata.artists.len(), 1);
    }

    #[test]
    fn test_metadata_cap_via_meta_directive() {
        // The {meta: subtitle ...} path should also enforce the cap.
        let count = Parser::MAX_METADATA_ENTRIES + 50;
        let mut input = String::new();
        for i in 0..count {
            input.push_str(&format!("{{meta: subtitle s{i}}}\n"));
        }
        let song = parse(&input).unwrap();
        assert_eq!(
            song.metadata.subtitles.len(),
            Parser::MAX_METADATA_ENTRIES,
            "meta directive path should also cap subtitles"
        );
    }
}