audex 0.2.0

Audio metadata reading and writing library with flexible I/O and easy wrappers
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
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
//! # FLAC Format Support
//!
//! This module provides comprehensive support for reading and writing Free Lossless Audio Codec (FLAC) files.
//!
//! ## Overview
//!
//! FLAC is a lossless audio compression format that provides:
//! - **Lossless compression**: Perfect bit-for-bit reconstruction of original audio
//! - **Fast decoding**: Simple algorithm allows efficient decompression
//! - **Seeking support**: Seek tables enable quick navigation
//! - **Metadata support**: Vorbis Comments, embedded pictures, cue sheets, and more
//! - **Error detection**: MD5 checksums and CRC checks
//!
//! ## Supported Features
//!
//! - Read/write audio properties (sample rate, bit depth, channels, duration)
//! - Read/write Vorbis Comment tags (artist, title, album, etc.)
//! - Embedded artwork via PICTURE blocks
//! - Seek tables for fast seeking
//! - Cue sheets for CD track information
//! - Application-specific blocks
//! - Multiple metadata block types
//! - Robust parsing with error recovery
//!
//! ## Basic Usage
//!
//! ```no_run
//! use audex::flac::FLAC;
//! use audex::{FileType, Tags};
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // Load a FLAC file
//!     let mut flac = FLAC::load("song.flac")?;
//!
//!     // Access audio information
//!     println!("Sample rate: {} Hz", flac.info.sample_rate);
//!     println!("Bit depth: {} bits", flac.info.bits_per_sample);
//!     println!("Channels: {}", flac.info.channels);
//!     println!("Total samples: {}", flac.info.total_samples);
//!
//!     // Read Vorbis Comment tags using the Tags trait
//!     if let Some(ref tags) = flac.tags {
//!         if let Some(title) = tags.get("TITLE") {
//!             println!("Title: {:?}", title);
//!         }
//!     }
//!
//!     // Modify tags and save using set for Vorbis Comments
//!     if let Some(ref mut tags) = flac.tags {
//!         tags.set("TITLE", vec!["New Title".to_string()]);
//!     }
//!     flac.save()?;
//!     Ok(())
//! }
//! ```
//!
//! ## Metadata Blocks
//!
//! FLAC files contain metadata blocks before the audio data:
//! - **STREAMINFO**: Required block with audio properties (always present)
//! - **VORBIS_COMMENT**: Tags and metadata (artist, title, etc.)
//! - **PICTURE**: Embedded artwork (album art, etc.)
//! - **SEEKTABLE**: Seek points for fast navigation
//! - **CUESHEET**: CD track information
//! - **APPLICATION**: Application-specific data
//! - **PADDING**: Reserved space for future metadata additions
//!
//! ## Error Handling
//!
//! This implementation includes robust error handling:
//! - Validates block sizes against configurable limits
//! - Detects and handles corrupted blocks
//! - Supports partial parsing (continues after recoverable errors)
//! - Provides detailed error context with file positions
//!
//! ## See Also
//!
//! - `FLAC` - Main struct for FLAC file handling
//! - `FLACStreamInfo` - Audio stream information
//! - `VCommentDict` - Vorbis Comment tags
//! - `Picture` - Embedded artwork

/// Convert an arbitrary-length byte slice to an integer using big-endian byte order.
///
/// Reads up to 8 bytes and interprets them as a big-endian unsigned integer.
/// For slices shorter than 8 bytes, the result is zero-extended on the high bits.
/// Inputs longer than 8 bytes are clamped to the last 8 bytes to prevent
/// silent loss of high bits from overflowing the u64 accumulator.
pub fn to_int_be(data: &[u8]) -> u64 {
    // Only the last 8 bytes can fit in a u64; earlier bytes would be
    // shifted out. Clamp to avoid silent truncation.
    let start = data.len().saturating_sub(8);
    data[start..]
        .iter()
        .fold(0u64, |acc, &byte| (acc << 8) | byte as u64)
}

use crate::tags::PaddingInfo;
use crate::util::resize_bytes;
use crate::vorbis::VCommentDict;
use crate::{AudexError, FileType, Result, StreamInfo, VERSION_STRING};
use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt};
use std::fs::{File, OpenOptions};
use std::io::{BufReader, Cursor, ErrorKind, Read, Seek, SeekFrom, Write};
use std::path::Path;

#[cfg(feature = "async")]
use crate::util::resize_bytes_async;
#[cfg(feature = "async")]
use tokio::fs::{File as TokioFile, OpenOptions as TokioOpenOptions};
#[cfg(feature = "async")]
use tokio::io::BufReader as TokioBufReader;

/// Type alias for a user-supplied function that determines padding size after a save.
///
/// Receives the current [`PaddingInfo`] and returns the desired padding in bytes.
/// A negative return value means "use the library default".
type PaddingFunction = Box<dyn FnOnce(&PaddingInfo) -> i64>;
use std::cmp::min;
use std::time::Duration;

/// Configuration options for FLAC file parsing.
///
/// These options control how the parser handles various edge cases and errors
/// that may occur in real-world FLAC files. The defaults are tuned for maximum
/// compatibility with potentially malformed files.
///
/// # Examples
///
/// ```no_run
/// use audex::flac::{FLAC, FLACParseOptions};
///
/// // Use strict parsing (less forgiving)
/// let options = FLACParseOptions {
///     distrust_size: false,        // Trust block size headers
///     max_block_size: 1024 * 1024, // 1MB limit
///     ignore_errors: false,         // Fail on any error
///     streaming_io: true,
///     ..Default::default()
/// };
///
/// // Load a file with custom options
/// let flac = FLAC::from_file_with_options("audio.flac", options)?;
/// # Ok::<(), audex::AudexError>(())
/// ```
///
/// # Default Behavior
///
/// The default configuration is designed for maximum robustness:
/// - Validates block sizes rather than trusting headers
/// - Allows up to 16MB blocks (handles most real-world files)
/// - Continues parsing after recoverable errors
/// - Uses streaming I/O for memory efficiency
#[derive(Debug, Clone)]
pub struct FLACParseOptions {
    /// Validate block sizes against actual data instead of trusting headers.
    ///
    /// When `true`, the parser reads and validates block data before accepting
    /// the size from the header. This protects against corrupted or malicious
    /// files with incorrect size fields.
    ///
    /// **Default**: `true` (recommended for untrusted files)
    pub distrust_size: bool,

    /// Maximum allowed metadata block size in bytes.
    ///
    /// Blocks exceeding this size are treated as invalid. This prevents
    /// memory exhaustion from corrupted or malicious files claiming extremely
    /// large block sizes.
    ///
    /// **Default**: 16MB (16 * 1024 * 1024 bytes)
    pub max_block_size: u32,

    /// Continue parsing after encountering non-fatal errors.
    ///
    /// When `true`, the parser attempts to recover from errors and continue
    /// loading other metadata blocks. Errors are recorded in `parse_errors`
    /// but don't abort the entire load operation.
    ///
    /// **Default**: `true` (allows partial file access)
    pub ignore_errors: bool,

    /// Use streaming I/O for reading blocks.
    ///
    /// When `true`, uses buffered reading to reduce memory usage and improve
    /// performance for large files. Disabling may be useful for debugging.
    ///
    /// **Default**: `true` (recommended)
    pub streaming_io: bool,

    /// Error handling mode for Vorbis comment UTF-8 decoding.
    ///
    /// Controls how invalid UTF-8 sequences in Vorbis comments are handled:
    /// - `Strict`: Fail with an error on any invalid UTF-8
    /// - `Replace`: Replace invalid sequences with U+FFFD (default)
    /// - `Ignore`: Silently drop invalid sequences
    ///
    /// **Default**: `Replace` (backward-compatible behavior)
    pub vorbis_error_mode: crate::vorbis::ErrorMode,
}

impl Default for FLACParseOptions {
    fn default() -> Self {
        Self {
            distrust_size: true,
            max_block_size: 16 * 1024 * 1024, // 16MB
            ignore_errors: true,
            streaming_io: true,
            vorbis_error_mode: crate::vorbis::ErrorMode::Replace,
        }
    }
}

/// FLAC-specific error with contextual information.
///
/// This error type provides detailed information about what went wrong during
/// FLAC file parsing, including the error type, file position where it occurred,
/// and a human-readable context message.
///
/// # Examples
///
/// ```
/// use audex::flac::FLAC;
/// use audex::FileType;
///
/// match FLAC::load("corrupted.flac") {
///     Ok(flac) => {
///         // Check for recoverable errors during parsing
///         if !flac.parse_errors.is_empty() {
///             println!("Parsed with {} errors", flac.parse_errors.len());
///             for error in &flac.parse_errors {
///                 println!("  {:?} at position {:?}: {}",
///                     error.kind, error.position, error.context);
///             }
///         }
///     }
///     Err(e) => eprintln!("Failed to load: {}", e),
/// }
/// ```
#[derive(Debug, Clone)]
pub struct FLACError {
    /// The specific type of error that occurred
    pub kind: FLACErrorKind,

    /// File byte offset where the error was detected, if known
    pub position: Option<u64>,

    /// Human-readable description providing additional context
    pub context: String,
}

/// Categories of errors that can occur during FLAC parsing.
///
/// These error kinds represent different failure modes, from structural
/// issues (invalid headers) to data corruption (oversized blocks) to
/// partial successes where some blocks failed but others loaded.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum FLACErrorKind {
    /// The FLAC file header is invalid or missing.
    ///
    /// This typically means the file is not a FLAC file, or the initial
    /// "fLaC" signature is missing or corrupted.
    InvalidHeader,

    /// A metadata block's size exceeds limits or is invalid.
    ///
    /// This occurs when:
    /// - Block size exceeds `max_block_size` setting
    /// - Block size would cause integer overflow
    /// - Block size doesn't match actual data length
    BlockSizeError,

    /// Multiple VORBIS_COMMENT blocks were found.
    ///
    /// The FLAC specification allows only one VORBIS_COMMENT block per file.
    /// Finding multiple blocks indicates a malformed or non-compliant file.
    MultipleVorbisBlocks,

    /// Multiple SEEKTABLE blocks were found.
    ///
    /// The FLAC specification allows only one SEEKTABLE block per file.
    MultipleSeekTableBlocks,

    /// Multiple CUESHEET blocks were found.
    ///
    /// The FLAC specification allows only one CUESHEET block per file.
    MultipleCueSheetBlocks,

    /// The STREAMINFO block contains an invalid sample rate of 0.
    InvalidSampleRate,

    /// A metadata block's data is corrupted or incomplete.
    ///
    /// The block header parsed successfully, but the block data itself
    /// is invalid, truncated, or fails validation checks.
    CorruptedBlock,

    /// A size calculation resulted in overflow.
    ///
    /// This typically indicates a corrupted file with invalid size fields
    /// that would cause integer overflow when processed.
    SizeOverflow,

    /// Parsing partially succeeded with some recoverable errors.
    ///
    /// Some metadata blocks loaded successfully, but others failed.
    /// The contained vector lists the specific errors encountered.
    /// This only occurs when `ignore_errors` is enabled in parse options.
    PartialSuccess(Vec<String>),
}

impl std::fmt::Display for FLACError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match &self.kind {
            FLACErrorKind::InvalidHeader => write!(f, "Invalid FLAC header"),
            FLACErrorKind::BlockSizeError => write!(f, "Block size error"),
            FLACErrorKind::MultipleVorbisBlocks => {
                write!(f, "Multiple Vorbis comment blocks found")
            }
            FLACErrorKind::MultipleSeekTableBlocks => {
                write!(f, "More than one SeekTable block found")
            }
            FLACErrorKind::MultipleCueSheetBlocks => {
                write!(f, "More than one CueSheet block found")
            }
            FLACErrorKind::InvalidSampleRate => {
                write!(f, "A sample rate value of 0 is invalid")
            }
            FLACErrorKind::CorruptedBlock => write!(f, "Corrupted block data"),
            FLACErrorKind::SizeOverflow => write!(f, "Size overflow"),
            FLACErrorKind::PartialSuccess(errors) => {
                write!(f, "Partial success with errors: {}", errors.join("; "))
            }
        }
    }
}

/// Represents a FLAC audio file with metadata and audio stream information.
///
/// This struct provides access to all FLAC metadata blocks and audio properties.
/// FLAC files contain a STREAMINFO block (always present) followed by optional
/// metadata blocks for tags, pictures, seeking, cue sheets, and more.
///
/// # Structure
///
/// A FLAC file consists of:
/// 1. **File header**: "fLaC" signature
/// 2. **Metadata blocks**: One or more blocks containing file information
/// 3. **Audio frames**: Compressed audio data (not loaded into this struct)
///
/// # Examples
///
/// ## Loading and Reading Metadata
///
/// ```no_run
/// use audex::flac::FLAC;
/// use audex::{FileType, Tags};
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let flac = FLAC::load("song.flac")?;
///
///     // Access audio properties
///     println!("Sample rate: {} Hz", flac.info.sample_rate);
///     println!("Bit depth: {} bits", flac.info.bits_per_sample);
///     println!("Channels: {}", flac.info.channels);
///
///     // Read Vorbis Comment tags using the Tags trait
///     if let Some(ref tags) = flac.tags {
///         if let Some(artist) = tags.get("ARTIST") {
///             println!("Artist: {:?}", artist);
///         }
///     }
///
///     // Check for embedded artwork
///     if !flac.pictures.is_empty() {
///         println!("Found {} embedded pictures", flac.pictures.len());
///     }
///     Ok(())
/// }
/// ```
///
/// ## Modifying and Saving
///
/// ```no_run
/// use audex::flac::FLAC;
/// use audex::{FileType, Tags};
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let mut flac = FLAC::load("song.flac")?;
///
///     // Modify tags using set for Vorbis Comments
///     if let Some(ref mut tags) = flac.tags {
///         tags.set("TITLE", vec!["New Title".to_string()]);
///         tags.set("ALBUM", vec!["New Album".to_string()]);
///     }
///
///     // Save changes
///     flac.save()?;
///     Ok(())
/// }
/// ```
///
/// ## Custom Parsing Options
///
/// ```no_run
/// use audex::flac::{FLAC, FLACParseOptions};
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let options = FLACParseOptions {
///         distrust_size: true,
///         max_block_size: 16 * 1024 * 1024,
///         ignore_errors: true,
///         streaming_io: true,
///         ..Default::default()
///     };
///
///     // Load file with custom options using static method
///     let flac = FLAC::from_file_with_options("song.flac", options)?;
///     Ok(())
/// }
/// ```
///
/// # See Also
///
/// - [`FLACStreamInfo`] - Audio stream properties
/// - [`VCommentDict`] - Vorbis Comment tags
/// - [`Picture`] - Embedded artwork
#[derive(Debug)]
pub struct FLAC {
    /// Audio stream information from STREAMINFO block (always present)
    pub info: FLACStreamInfo,

    /// Vorbis Comment tags (TITLE, ARTIST, ALBUM, etc.), if present
    pub tags: Option<VCommentDict>,

    /// Embedded pictures (album art, artist photos, etc.)
    pub pictures: Vec<Picture>,

    /// Seek table for fast seeking to specific timestamps
    pub seektable: Option<SeekTable>,

    /// Cue sheet with CD track information
    pub cuesheet: Option<CueSheet>,

    /// Application-specific metadata blocks
    pub application_blocks: Vec<ApplicationBlock>,

    /// Generic metadata blocks not fitting other categories
    pub metadata_blocks: Vec<MetadataBlock>,

    /// Padding blocks (reserved space for future metadata)
    pub padding_blocks: Vec<Padding>,

    /// Path to the file (used for save operations)
    filename: String,

    /// Parsing configuration options
    parse_options: FLACParseOptions,

    /// Errors encountered during parsing (when ignore_errors is enabled)
    ///
    /// This field is publicly accessible to check for recoverable errors
    /// that occurred during file loading.
    pub parse_errors: Vec<FLACError>,

    /// Blocks with size values exceeding the 24-bit FLAC spec limit
    ///
    /// Stores (block_type, actual_size) for blocks that claim sizes > 16MB.
    /// Used for validation and diagnostics.
    invalid_overflow_size: Vec<(u8, usize)>,

    /// Original header sizes for oversized blocks loaded from file.
    ///
    /// Maps block_type -> original 3-byte header size for VorbisComment (4)
    /// and Picture (6) blocks that were already oversized on disk. When saving,
    /// if the serialized block still exceeds 0xFFFFFF and we have the original
    /// size recorded here, we write back the original (wrong) size instead of
    /// erroring -- preserving the file's existing brokenness rather than
    /// refusing to save.
    /// pattern.
    original_overflow_sizes: std::collections::HashMap<u8, u32>,

    /// Whether the file has been modified since loading
    ///
    /// Used to optimize saves (skip writing if nothing changed).
    dirty: bool,

    /// Original metadata bytes for comparison
    ///
    /// Stored to detect changes and enable intelligent save optimizations.
    original_metadata: Vec<u8>,

    /// Original block type ordering
    ///
    /// Preserves the original order of metadata blocks for byte-identical
    /// writes when nothing has changed.
    original_block_order: Vec<u8>,
}

impl FLAC {
    /// Create a new empty FLAC instance with default stream info and no tags.
    pub fn new() -> Self {
        Self {
            info: FLACStreamInfo::default(),
            tags: None,
            pictures: Vec::new(),
            seektable: None,
            cuesheet: None,
            application_blocks: Vec::new(),
            metadata_blocks: Vec::new(),
            padding_blocks: Vec::new(),
            filename: String::new(),
            parse_options: FLACParseOptions::default(),
            parse_errors: Vec::new(),
            invalid_overflow_size: Vec::new(),
            original_overflow_sizes: std::collections::HashMap::new(),
            dirty: false,
            original_metadata: Vec::new(),
            original_block_order: Vec::new(),
        }
    }

    /// Create new FLAC with custom parsing options
    pub fn with_options(options: FLACParseOptions) -> Self {
        Self {
            info: FLACStreamInfo::default(),
            tags: None,
            pictures: Vec::new(),
            seektable: None,
            cuesheet: None,
            application_blocks: Vec::new(),
            metadata_blocks: Vec::new(),
            padding_blocks: Vec::new(),
            filename: String::new(),
            parse_options: options,
            parse_errors: Vec::new(),
            invalid_overflow_size: Vec::new(),
            original_overflow_sizes: std::collections::HashMap::new(),
            dirty: false,
            original_metadata: Vec::new(),
            original_block_order: Vec::new(),
        }
    }

    /// Get parsing errors encountered during file processing
    pub fn parse_errors(&self) -> &[FLACError] {
        &self.parse_errors
    }

    /// Check if parsing was successful (no critical errors)
    pub fn is_valid(&self) -> bool {
        !self
            .parse_errors
            .iter()
            .any(|e| matches!(e.kind, FLACErrorKind::InvalidHeader))
    }

    /// Loads a FLAC file from the specified path using default parsing options.
    ///
    /// This method opens and parses a FLAC file, loading all metadata blocks
    /// including STREAMINFO, Vorbis Comments, pictures, seek tables, and more.
    /// Audio frame data is not loaded into memory.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the FLAC file to load
    ///
    /// # Returns
    ///
    /// * `Ok(FLAC)` - Successfully loaded FLAC file with all metadata
    /// * `Err(AudexError)` - Failed to open file or parse FLAC structure
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The file cannot be opened (doesn't exist, permission denied, etc.)
    /// - The file is not a valid FLAC file (missing "fLaC" signature)
    /// - Required STREAMINFO block is missing or corrupted
    /// - Metadata blocks exceed size limits (see [`FLACParseOptions`])
    ///
    /// With default options, recoverable errors are logged in `parse_errors`
    /// but don't prevent loading. Check `flac.parse_errors` after loading
    /// to see if any issues were encountered.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use audex::flac::FLAC;
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let flac = FLAC::from_file("song.flac")?;
    ///
    ///     // Check for any parsing errors
    ///     if !flac.parse_errors.is_empty() {
    ///         println!("Loaded with {} warnings", flac.parse_errors.len());
    ///     }
    ///
    ///     println!("Sample rate: {} Hz", flac.info.sample_rate);
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # See Also
    ///
    /// - [`FLAC::from_file_with_options`] - Load with custom parsing options
    /// - [`FLAC::load`](FileType::load) - Trait method (same as `from_file`)
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::from_file_with_options(path, FLACParseOptions::default())
    }

    /// Loads a FLAC file with custom parsing options.
    ///
    /// This method provides fine-grained control over how the FLAC file is parsed,
    /// including error handling behavior, size limits, and I/O strategy.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the FLAC file
    /// * `options` - Custom parsing configuration
    ///
    /// # Returns
    ///
    /// * `Ok(FLAC)` - Successfully loaded FLAC file
    /// * `Err(AudexError)` - Failed to load (behavior depends on options)
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use audex::flac::{FLAC, FLACParseOptions};
    ///
    /// // Strict parsing: fail on any error
    /// let options = FLACParseOptions {
    ///     distrust_size: false,
    ///     max_block_size: 1024 * 1024,  // 1MB limit
    ///     ignore_errors: false,           // Fail on errors
    ///     streaming_io: true,
    ///     ..Default::default()
    /// };
    ///
    /// match FLAC::from_file_with_options("song.flac", options) {
    ///     Ok(flac) => println!("Loaded successfully"),
    ///     Err(e) => eprintln!("Failed: {}", e),
    /// }
    /// ```
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all, fields(path = %path.as_ref().display())))]
    pub fn from_file_with_options<P: AsRef<Path>>(
        path: P,
        options: FLACParseOptions,
    ) -> Result<Self> {
        let path = path.as_ref();
        debug_event!("parsing FLAC file");
        let file = File::open(path)?;
        let mut flac = Self::with_options(options);
        flac.filename = path.to_string_lossy().to_string();

        if flac.parse_options.streaming_io {
            let mut reader = BufReader::new(file);
            flac.parse_flac_streaming(&mut reader)?;
        } else {
            // Legacy memory-based parsing
            let mut file = file;
            flac.parse_flac(&mut file)?;
        }

        Ok(flac)
    }

    /// Parse FLAC data from a reader with custom options.
    ///
    /// This allows callers to control parsing behavior (including Vorbis
    /// comment error handling) when loading from an in-memory buffer or
    /// any other reader.
    pub fn from_reader_with_options<R: Read + Seek>(
        reader: &mut R,
        options: FLACParseOptions,
    ) -> Result<Self> {
        let mut flac = Self::with_options(options);
        if flac.parse_options.streaming_io {
            flac.parse_flac_streaming(reader)?;
        } else {
            flac.parse_flac(reader)?;
        }
        Ok(flac)
    }

    /// Parse FLAC file structure
    fn parse_flac<R: Read + Seek>(&mut self, reader: &mut R) -> Result<()> {
        // Check for ID3 tags first
        let mut signature = [0u8; 4];
        reader.read_exact(&mut signature)?;

        if &signature[..3] == b"ID3" {
            // Skip ID3v2 tag
            let mut id3_size_bytes = [0u8; 6];
            reader.read_exact(&mut id3_size_bytes)?;
            let id3_size = self.decode_id3_size(&id3_size_bytes[2..])?;
            reader.seek(SeekFrom::Current(id3_size as i64))?;

            // Read FLAC signature after ID3
            reader.read_exact(&mut signature)?;
        }

        if &signature != b"fLaC" {
            return Err(AudexError::FLACNoHeader);
        }

        // Store position after fLaC header
        let metadata_start = reader.stream_position()?;

        // Parse metadata blocks
        self.parse_metadata_blocks(reader)?;

        // Calculate audio offset by scanning block headers (reliable regardless
        // of reader state after complex read patterns)
        let metadata_end = self.find_audio_offset_from_file(reader)?;

        // Capture original metadata for change detection
        // Cap to actual file size to prevent OOM from crafted size fields
        let file_end = reader.seek(SeekFrom::End(0))?;
        let capped_end = metadata_end.min(file_end);
        // Guard against underflow when metadata_start exceeds the computed end
        // position (can happen with truncated or malformed files)
        let metadata_size_u64 = capped_end.checked_sub(metadata_start).ok_or_else(|| {
            AudexError::InvalidData("metadata region extends beyond file boundaries".to_string())
        })?;
        let metadata_size = usize::try_from(metadata_size_u64).map_err(|_| {
            AudexError::InvalidData("metadata region too large for this platform".to_string())
        })?;
        reader.seek(SeekFrom::Start(metadata_start))?;
        self.original_metadata = vec![0u8; metadata_size];
        // Use read_exact for byte-identical capture, tolerate EOF for truncated test files
        match reader.read_exact(&mut self.original_metadata) {
            Ok(()) => {} // Successfully read all metadata
            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                // Truncated file - clear original_metadata so we don't try to compare
                self.original_metadata.clear();
            }
            Err(e) => return Err(e.into()),
        }

        // Calculate accurate bitrate from audio stream size
        // Use metadata_end (already computed) as the audio start position
        // instead of stream_position() which can be unreliable with BufReader
        if self.info.total_samples > 0 {
            if let Ok(end_pos) = reader.seek(SeekFrom::End(0)) {
                if let Some(duration) = self.info.length {
                    if end_pos >= metadata_end {
                        let audio_size = end_pos - metadata_end;
                        let duration_secs = duration.as_secs_f64();
                        if duration_secs > 0.0 {
                            let bitrate = (audio_size * 8) as f64 / duration_secs;
                            self.info.bitrate = Some(bitrate as u32);
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Decode ID3v2 size (synchsafe integer)
    fn decode_id3_size(&self, size_bytes: &[u8]) -> Result<u32> {
        if size_bytes.len() != 4 {
            return Err(AudexError::InvalidData("Invalid ID3 size".to_string()));
        }

        let size = ((size_bytes[0] & 0x7F) as u32) << 21
            | ((size_bytes[1] & 0x7F) as u32) << 14
            | ((size_bytes[2] & 0x7F) as u32) << 7
            | (size_bytes[3] & 0x7F) as u32;

        Ok(size)
    }

    /// Parse FLAC file structure with streaming I/O
    fn parse_flac_streaming<R: Read + Seek>(&mut self, reader: &mut R) -> Result<()> {
        // Check for ID3 tags first
        let mut signature = [0u8; 4];
        reader.read_exact(&mut signature)?;

        if &signature[..3] == b"ID3" {
            // Skip ID3v2 tag
            let mut id3_size_bytes = [0u8; 6];
            reader.read_exact(&mut id3_size_bytes)?;
            let id3_size = self.decode_id3_size(&id3_size_bytes[2..])?;
            reader.seek(SeekFrom::Current(id3_size as i64))?;

            // Read FLAC signature after ID3
            reader.read_exact(&mut signature)?;
        }

        if &signature != b"fLaC" {
            let error = FLACError {
                kind: FLACErrorKind::InvalidHeader,
                position: reader.stream_position().ok(),
                context: "Missing or invalid FLAC signature".to_string(),
            };
            self.parse_errors.push(error);
            return Err(AudexError::FLACNoHeader);
        }

        // Store position after fLaC header
        let metadata_start = reader.stream_position()?;

        // Parse metadata blocks with streaming
        self.parse_metadata_blocks_streaming(reader)?;

        // Calculate audio offset by scanning block headers (reliable regardless
        // of BufReader state, unlike stream_position() after complex read patterns)
        let metadata_end = self.find_audio_offset_from_file(reader)?;

        // Capture original metadata for change detection
        // Cap to actual file size to prevent OOM from crafted size fields
        let file_end = reader.seek(SeekFrom::End(0))?;
        let capped_end = metadata_end.min(file_end);
        // Guard against underflow when metadata_start exceeds the computed end
        // position (can happen with truncated or malformed files)
        let metadata_size_u64 = capped_end.checked_sub(metadata_start).ok_or_else(|| {
            AudexError::InvalidData("metadata region extends beyond file boundaries".to_string())
        })?;
        let metadata_size = usize::try_from(metadata_size_u64).map_err(|_| {
            AudexError::InvalidData("metadata region too large for this platform".to_string())
        })?;
        reader.seek(SeekFrom::Start(metadata_start))?;
        self.original_metadata = vec![0u8; metadata_size];
        // Use read_exact for byte-identical capture, tolerate EOF for truncated test files
        match reader.read_exact(&mut self.original_metadata) {
            Ok(()) => {} // Successfully read all metadata
            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                // Truncated file - clear original_metadata so we don't try to compare
                self.original_metadata.clear();
            }
            Err(e) => return Err(e.into()),
        }

        // Calculate accurate bitrate from audio stream size
        if self.info.total_samples > 0 {
            if let Ok(end_pos) = reader.seek(SeekFrom::End(0)) {
                if let Some(duration) = self.info.length {
                    if end_pos >= metadata_end {
                        let audio_size = end_pos - metadata_end;
                        let duration_secs = duration.as_secs_f64();
                        if duration_secs > 0.0 {
                            let bitrate = (audio_size * 8) as f64 / duration_secs;
                            self.info.bitrate = Some(bitrate as u32);
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Parse FLAC metadata blocks with streaming I/O and robustness
    fn parse_metadata_blocks_streaming<R: Read + Seek>(&mut self, reader: &mut R) -> Result<()> {
        let mut is_last = false;
        let mut vorbis_comment_count = 0;
        // Cap the number of metadata blocks to prevent excessive iteration
        // on crafted files where the is_last flag is never set.
        const MAX_METADATA_BLOCKS: usize = 1024;
        let mut block_count: usize = 0;

        while !is_last {
            block_count += 1;
            if block_count > MAX_METADATA_BLOCKS {
                return Err(AudexError::InvalidData(format!(
                    "Exceeded maximum metadata block count ({})",
                    MAX_METADATA_BLOCKS
                )));
            }
            // Propagate stream_position errors instead of defaulting to 0,
            // which would cause subtraction underflow in later offset math
            let block_start_pos = reader.stream_position()?;

            // Read block header (4 bytes)
            let mut header = [0u8; 4];
            if let Err(e) = reader.read_exact(&mut header) {
                if self.parse_options.ignore_errors {
                    self.parse_errors.push(FLACError {
                        kind: FLACErrorKind::CorruptedBlock,
                        position: Some(block_start_pos),
                        context: format!("Failed to read block header: {}", e),
                    });
                    break;
                }
                return Err(e.into());
            }

            let block_type = header[0] & 0x7F; // Remove last block flag
            is_last = (header[0] & 0x80) != 0; // Check last block flag

            let block_size = u32::from_be_bytes([0, header[1], header[2], header[3]]);

            // Track block order for byte-identical writes
            self.original_block_order.push(block_type);

            // Read the block data to store in metadata_blocks
            let block_data_start = reader.stream_position()?;

            // Validate block size — always enforce the limit regardless of
            // distrust_size to prevent uncapped allocations from crafted files
            if block_size > self.parse_options.max_block_size {
                let error = FLACError {
                    kind: FLACErrorKind::BlockSizeError,
                    position: Some(block_start_pos),
                    context: format!(
                        "Block size {} exceeds maximum {}",
                        block_size, self.parse_options.max_block_size
                    ),
                };
                self.parse_errors.push(error);

                // VORBIS_COMMENT (block_type 4) block size errors are always fatal
                // to prevent OOM attacks, even with ignore_errors enabled
                if block_type == 4 || !self.parse_options.ignore_errors {
                    return Err(AudexError::InvalidData(format!(
                        "Block size {} exceeds maximum {}",
                        block_size, self.parse_options.max_block_size
                    )));
                }

                // For non-Vorbis blocks with ignore_errors, skip the full
                // declared block_size to position at the next block header.
                // Using min(block_size, max_block_size) here would leave the
                // reader mid-block, causing the next iteration to misparse.
                reader.seek(SeekFrom::Current(block_size as i64))?;
                continue;
            }

            // Emit per-block trace for observability
            trace_event!(
                block_type = block_type,
                block_size = block_size,
                is_last = is_last,
                "parsing FLAC metadata block"
            );

            // Handle different block types with error recovery
            let parse_result = match block_type {
                0 => {
                    // STREAMINFO block (mandatory, always first)
                    self.parse_streaminfo_block_safe(reader, block_size, block_start_pos)
                }
                1 => {
                    // PADDING block - parse and store
                    self.parse_padding_block_safe(reader, block_size, block_start_pos)
                }
                2 => {
                    // APPLICATION block - preserve all data
                    self.parse_application_block_safe(reader, block_size, block_start_pos)
                }
                3 => {
                    // SEEKTABLE block - check for duplicates
                    if self.seektable.is_some() {
                        self.parse_errors.push(FLACError {
                            kind: FLACErrorKind::MultipleSeekTableBlocks,
                            position: Some(block_start_pos),
                            context: "> 1 SeekTable block found".to_string(),
                        });

                        if !self.parse_options.ignore_errors {
                            return Err(AudexError::InvalidData(
                                "> 1 SeekTable block found".to_string(),
                            ));
                        }

                        // Skip duplicate SeekTable block
                        reader.seek(SeekFrom::Current(block_size as i64))?;
                        Ok(())
                    } else {
                        self.parse_seektable_block_safe(reader, block_size, block_start_pos)
                    }
                }
                4 => {
                    // VORBIS_COMMENT block - handle multiples gracefully
                    vorbis_comment_count += 1;
                    if vorbis_comment_count > 1 {
                        self.parse_errors.push(FLACError {
                            kind: FLACErrorKind::MultipleVorbisBlocks,
                            position: Some(block_start_pos),
                            context: format!(
                                "Found {} VORBIS_COMMENT blocks, using first",
                                vorbis_comment_count
                            ),
                        });

                        if !self.parse_options.ignore_errors {
                            return Err(AudexError::FLACVorbis);
                        }

                        // Skip duplicate Vorbis block
                        reader.seek(SeekFrom::Current(block_size as i64))?;
                        Ok(())
                    } else {
                        self.parse_vorbis_comment_block_safe(reader, block_size, block_start_pos)
                    }
                }
                5 => {
                    // CUESHEET block - check for duplicates
                    if self.cuesheet.is_some() {
                        self.parse_errors.push(FLACError {
                            kind: FLACErrorKind::MultipleCueSheetBlocks,
                            position: Some(block_start_pos),
                            context: "> 1 CueSheet block found".to_string(),
                        });

                        if !self.parse_options.ignore_errors {
                            return Err(AudexError::InvalidData(
                                "> 1 CueSheet block found".to_string(),
                            ));
                        }

                        // Skip duplicate CueSheet block
                        reader.seek(SeekFrom::Current(block_size as i64))?;
                        Ok(())
                    } else {
                        self.parse_cuesheet_block_safe(reader, block_size, block_start_pos)
                    }
                }
                6 => {
                    // PICTURE block
                    self.parse_picture_block_safe(reader, block_size, block_start_pos)
                }
                _ => {
                    // Unknown or reserved block type - skip
                    reader.seek(SeekFrom::Current(block_size as i64))?;
                    Ok(())
                }
            };

            // Handle parse errors
            if let Err(e) = parse_result {
                warn_event!(block_type = block_type, error = %e, "FLAC metadata block parse error");
                let error = FLACError {
                    kind: FLACErrorKind::CorruptedBlock,
                    position: Some(block_start_pos),
                    context: format!("Block type {} parse error: {}", block_type, e),
                };
                self.parse_errors.push(error);

                // Determine if error is fatal based on type and ignore_errors setting
                let is_fatal_error = if self.parse_options.ignore_errors {
                    // With ignore_errors, still fail on critical errors:
                    // - Fatal Vorbis errors (OOM attacks, structural corruption)
                    // but allow benign truncations to be skipped
                    block_type == 4 && self.is_fatal_vorbis_error(&e)
                } else {
                    // Without ignore_errors, STREAMINFO and certain Vorbis errors are fatal
                    block_type == 0 || (block_type == 4 && self.is_fatal_vorbis_error(&e))
                };

                if is_fatal_error {
                    return Err(e);
                }

                // Try to skip corrupted block and continue
                let current_pos = reader.stream_position()?;
                let expected_pos = block_start_pos + 4 + block_size as u64;
                if current_pos != expected_pos {
                    reader.seek(SeekFrom::Start(expected_pos))?;
                }
            } else {
                // Successfully parsed block - add it to metadata_blocks list
                // Read the block data to store
                let current_pos = reader.stream_position()?;
                let bytes_to_read = current_pos.checked_sub(block_data_start).ok_or_else(|| {
                    AudexError::InvalidData(format!(
                        "FLAC block position underflow: current {} < start {}",
                        current_pos, block_data_start
                    ))
                })? as usize;

                // For VorbisComment (4) and Picture (6) blocks: if the real
                // content size exceeds the 24-bit max, record the original
                // header size so we can write it back on save (distrust_size
                // round-trip).
                if (block_type == 4 || block_type == 6) && bytes_to_read > 0xFFFFFF {
                    self.original_overflow_sizes.insert(block_type, block_size);
                }

                // Seek back to read the block data
                reader.seek(SeekFrom::Start(block_data_start))?;
                let mut block_data = vec![0u8; bytes_to_read];
                reader.read_exact(&mut block_data)?;

                // Add to metadata_blocks
                self.metadata_blocks
                    .push(MetadataBlock::new(block_type, block_data));
            }
        }

        // Emit debug summaries after all metadata blocks are parsed
        debug_event!(
            sample_rate = self.info.sample_rate,
            channels = self.info.channels,
            bits_per_sample = self.info.bits_per_sample,
            total_samples = self.info.total_samples,
            "FLAC STREAMINFO parsed"
        );
        if let Some(ref _tags) = self.tags {
            debug_event!(
                tag_count = _tags.keys().len(),
                vendor = %_tags.vendor(),
                "FLAC Vorbis Comment parsed"
            );
        }
        let _picture_count = self.pictures.len();
        if _picture_count > 0 {
            debug_event!(picture_count = _picture_count, "FLAC pictures parsed");
        }

        Ok(())
    }

    /// Check if a VORBIS_COMMENT error is fatal (indicates corruption)
    fn is_fatal_vorbis_error(&self, error: &AudexError) -> bool {
        // Errors related to malicious data structures are fatal (e.g., OOM attacks)
        // Benign truncations (IO errors) are not fatal
        match error {
            AudexError::InvalidData(msg) => {
                // Fatal: Structural errors indicating malicious data
                // Non-fatal: "failed to fill whole buffer" (IO truncation)
                if msg.contains("failed to fill whole buffer") {
                    // This is a benign truncation, not fatal
                    false
                } else {
                    // Fatal OOM protection errors
                    msg.contains("exceeds maximum")
                        // Fatal: I/O read errors in Vorbis structure
                        || msg.contains("failed to read vendor")
                        || msg.contains("failed to read comment count")
                        || msg.contains("failed to read comment length")
                        || msg.contains("Truncated Vorbis")
                        // Fatal when strict mode: UTF-8 encoding errors wrapped
                        // by the safe parser as InvalidData
                        || (matches!(self.parse_options.vorbis_error_mode, crate::vorbis::ErrorMode::Strict)
                            && msg.contains("encoding error"))
                }
            }
            // UTF-8 encoding errors are fatal when strict error mode is selected
            AudexError::FormatError(_) => {
                matches!(
                    self.parse_options.vorbis_error_mode,
                    crate::vorbis::ErrorMode::Strict
                )
            }
            _ => false,
        }
    }

    /// Parse FLAC metadata blocks (legacy method)
    fn parse_metadata_blocks<R: Read + Seek>(&mut self, reader: &mut R) -> Result<()> {
        let mut is_last = false;
        // Cap the number of metadata blocks to prevent excessive iteration
        // on crafted files where the is_last flag is never set. FLAC only
        // defines 7 block types (0-6) and real files rarely exceed a dozen
        // blocks, so 1024 is a generous upper bound.
        const MAX_METADATA_BLOCKS: usize = 1024;
        let mut block_count: usize = 0;

        while !is_last {
            block_count += 1;
            if block_count > MAX_METADATA_BLOCKS {
                return Err(AudexError::InvalidData(format!(
                    "Exceeded maximum metadata block count ({})",
                    MAX_METADATA_BLOCKS
                )));
            }
            // Read block header (4 bytes)
            let mut header = [0u8; 4];
            reader.read_exact(&mut header)?;

            let block_type = header[0] & 0x7F; // Remove last block flag
            is_last = (header[0] & 0x80) != 0; // Check last block flag

            let block_size = u32::from_be_bytes([0, header[1], header[2], header[3]]);

            // Enforce block size limit to prevent uncapped allocations
            // from crafted files (matching the streaming parser path)
            if block_size > self.parse_options.max_block_size {
                return Err(AudexError::InvalidData(format!(
                    "Block size {} exceeds maximum {}",
                    block_size, self.parse_options.max_block_size
                )));
            }

            // Track block order for byte-identical writes
            self.original_block_order.push(block_type);

            // Read the block data to store in metadata_blocks
            let block_data_start = reader.stream_position()?;

            match block_type {
                0 => {
                    // STREAMINFO block (mandatory, always first)
                    self.parse_streaminfo_block(reader, block_size)?;
                }
                1 => {
                    // PADDING block - parse and store
                    self.parse_padding_block(reader, block_size)?
                }
                2 => {
                    // APPLICATION block - preserve all data
                    self.parse_application_block(reader, block_size)?;
                }
                3 => {
                    // SEEKTABLE block
                    if self.seektable.is_some() {
                        return Err(AudexError::InvalidData(
                            "> 1 SeekTable block found".to_string(),
                        ));
                    }
                    self.parse_seektable_block(reader, block_size)?;
                }
                4 => {
                    // VORBIS_COMMENT block — reject duplicates since the
                    // FLAC spec mandates at most one per file
                    if self.tags.is_some() {
                        return Err(AudexError::InvalidData(
                            "> 1 VorbisComment block found".to_string(),
                        ));
                    }
                    self.parse_vorbis_comment_block(reader, block_size)?;
                }
                5 => {
                    // CUESHEET block
                    if self.cuesheet.is_some() {
                        return Err(AudexError::InvalidData(
                            "> 1 CueSheet block found".to_string(),
                        ));
                    }
                    self.parse_cuesheet_block(reader, block_size)?;
                }
                6 => {
                    // PICTURE block
                    self.parse_picture_block(reader, block_size)?;
                }
                _ => {
                    // Unknown or reserved block type - skip
                    reader.seek(SeekFrom::Current(block_size as i64))?;
                }
            }

            // Add block to metadata_blocks list
            let current_pos = reader.stream_position()?;
            let bytes_to_read = current_pos.checked_sub(block_data_start).ok_or_else(|| {
                AudexError::InvalidData(format!(
                    "FLAC block position underflow: current {} < start {}",
                    current_pos, block_data_start
                ))
            })? as usize;

            // For VorbisComment (4) and Picture (6) blocks: if the real
            // content size exceeds the 24-bit max, record the original
            // header size so we can write it back on save (distrust_size
            // round-trip).
            if (block_type == 4 || block_type == 6) && bytes_to_read > 0xFFFFFF {
                self.original_overflow_sizes.insert(block_type, block_size);
            }

            // Seek back to read the block data
            reader.seek(SeekFrom::Start(block_data_start))?;
            let mut block_data = vec![0u8; bytes_to_read];
            reader.read_exact(&mut block_data)?;

            // Add to metadata_blocks
            self.metadata_blocks
                .push(MetadataBlock::new(block_type, block_data));
        }

        Ok(())
    }

    /// Parse STREAMINFO metadata block (legacy)
    fn parse_streaminfo_block<R: Read>(&mut self, reader: &mut R, _block_size: u32) -> Result<()> {
        let mut data = [0u8; 34]; // STREAMINFO is always 34 bytes
        reader.read_exact(&mut data)?;

        let mut cursor = Cursor::new(&data);

        // Parse STREAMINFO fields
        self.info.min_blocksize = cursor.read_u16::<BigEndian>()?;
        self.info.max_blocksize = cursor.read_u16::<BigEndian>()?;

        let min_framesize_bytes = [cursor.read_u8()?, cursor.read_u8()?, cursor.read_u8()?];
        self.info.min_framesize = u32::from_be_bytes([
            0,
            min_framesize_bytes[0],
            min_framesize_bytes[1],
            min_framesize_bytes[2],
        ]);

        let max_framesize_bytes = [cursor.read_u8()?, cursor.read_u8()?, cursor.read_u8()?];
        self.info.max_framesize = u32::from_be_bytes([
            0,
            max_framesize_bytes[0],
            max_framesize_bytes[1],
            max_framesize_bytes[2],
        ]);

        // Parse sample rate, channels, bits per sample, total samples (20 + 3 + 5 + 36 = 64 bits)
        let combined = cursor.read_u64::<BigEndian>()?;

        self.info.sample_rate = ((combined >> 44) & 0xFFFFF) as u32; // 20 bits
        self.info.channels = (((combined >> 41) & 0x07) as u16) + 1; // 3 bits, +1 because encoded as channels-1
        self.info.bits_per_sample = (((combined >> 36) & 0x1F) as u16) + 1; // 5 bits, +1 because encoded as bps-1
        self.info.total_samples = combined & 0xFFFFFFFFF; // 36 bits

        // A sample rate of 0 is invalid per the FLAC specification
        if self.info.sample_rate == 0 {
            return Err(AudexError::InvalidData(
                "A sample rate value of 0 is invalid".to_string(),
            ));
        }

        // MD5 signature (16 bytes)
        cursor.read_exact(&mut self.info.md5_signature)?;

        // Calculate length and bitrate
        if self.info.sample_rate > 0 {
            if self.info.total_samples > 0 {
                let duration_secs = self.info.total_samples as f64 / self.info.sample_rate as f64;
                self.info.length = Some(Duration::from_secs_f64(duration_secs));

                // FLAC bitrate is variable, but we can estimate average
                // This would be more accurate with actual file size
                let bits_per_second = self.info.sample_rate as u64
                    * self.info.channels as u64
                    * self.info.bits_per_sample as u64;
                // Saturate to u32::MAX instead of silently truncating
                self.info.bitrate = Some(u32::try_from(bits_per_second).unwrap_or(u32::MAX));
            } else {
                // Zero samples means zero duration and zero bitrate
                self.info.length = Some(Duration::from_secs(0));
                self.info.bitrate = Some(0);
            }
        }

        Ok(())
    }

    /// Parse STREAMINFO metadata block with safety checks
    fn parse_streaminfo_block_safe<R: Read + Seek>(
        &mut self,
        reader: &mut R,
        block_size: u32,
        _block_start_pos: u64,
    ) -> Result<()> {
        // STREAMINFO must be exactly 34 bytes
        if block_size != 34 {
            return Err(AudexError::InvalidData(format!(
                "Invalid STREAMINFO size: {} (expected 34)",
                block_size
            )));
        }

        self.parse_streaminfo_block(reader, block_size)
    }

    /// Parse VORBIS_COMMENT metadata block (legacy)
    fn parse_vorbis_comment_block<R: Read>(
        &mut self,
        reader: &mut R,
        block_size: u32,
    ) -> Result<()> {
        let mut data = vec![0u8; block_size as usize];
        reader.read_exact(&mut data)?;

        // Parse Vorbis comment data - FLAC files don't have framing bit
        let comment = VCommentDict::from_bytes_with_options(
            &data,
            self.parse_options.vorbis_error_mode,
            false,
        )?;
        self.tags = Some(comment);

        Ok(())
    }

    /// Parse VORBIS_COMMENT metadata block with safety checks
    fn parse_vorbis_comment_block_safe<R: Read + Seek>(
        &mut self,
        reader: &mut R,
        block_size: u32,
        block_start_pos: u64,
    ) -> Result<()> {
        if self.parse_options.distrust_size {
            // When distrust_size is set, ignore header size and parse directly
            // from the stream. The VComment parser reads field-by-field using
            // internal length fields, leaving the stream at the correct position.
            let start_pos = reader.stream_position()?;
            let mut comment = VCommentDict::new();
            comment
                .load(reader, self.parse_options.vorbis_error_mode, false)
                .map_err(|e| {
                    AudexError::InvalidData(format!(
                        "Vorbis comment parse error at position {}: {}",
                        block_start_pos, e
                    ))
                })?;

            let real_size = reader.stream_position()? - start_pos;

            // Enforce max_block_size on the actual bytes consumed, not
            // just the header's declared size. A crafted file could
            // have a small header size but large internal VComment
            // length fields that bypass the caller's check.
            if real_size > self.parse_options.max_block_size as u64 {
                return Err(AudexError::InvalidData(format!(
                    "Vorbis comment actual size ({} bytes) exceeds max_block_size ({})",
                    real_size, self.parse_options.max_block_size
                )));
            }

            if real_size > 0xFFFFFF_u64 {
                self.original_overflow_sizes.insert(4, block_size);
            }

            self.tags = Some(comment);
        } else {
            // Enforce the same max_block_size limit used by the distrust_size
            // path and by all other block types. A hardcoded cap here would
            // create an inconsistency where disabling distrust_size silently
            // raises the effective limit beyond the configured ceiling.
            if block_size > self.parse_options.max_block_size {
                return Err(AudexError::InvalidData(format!(
                    "Vorbis comment block size ({} bytes) exceeds max_block_size ({})",
                    block_size, self.parse_options.max_block_size
                )));
            }

            let mut data = vec![0u8; block_size as usize];
            reader.read_exact(&mut data)?;

            // FLAC files don't have framing bit in Vorbis comments.
            // Use the configured error mode so that callers who set
            // e.g. ErrorMode::Strict get consistent validation
            // regardless of the distrust_size setting.
            let comment = VCommentDict::from_bytes_with_options(
                &data,
                self.parse_options.vorbis_error_mode,
                false,
            )?;
            self.tags = Some(comment);
        }

        Ok(())
    }

    /// Maximum metadata block size for legacy parsers (64 MB).
    const MAX_LEGACY_BLOCK: u32 = 64 * 1024 * 1024;

    /// Parse SEEKTABLE metadata block (legacy)
    fn parse_seektable_block<R: Read>(&mut self, reader: &mut R, block_size: u32) -> Result<()> {
        // Check against global ParseLimits before allocating, so that
        // restrictive limits configured for untrusted input are honoured
        // even through the legacy code path.
        crate::limits::ParseLimits::default()
            .check_tag_size(block_size as u64, "FLAC legacy seektable block")?;
        if block_size > Self::MAX_LEGACY_BLOCK {
            return Err(AudexError::ParseError(format!(
                "FLAC block too large: {} bytes",
                block_size
            )));
        }
        let mut data = vec![0u8; block_size as usize];
        reader.read_exact(&mut data)?;

        let seektable = SeekTable::from_bytes(&data)?;
        self.seektable = Some(seektable);

        Ok(())
    }

    /// Parse SEEKTABLE metadata block with safety checks
    fn parse_seektable_block_safe<R: Read + Seek>(
        &mut self,
        reader: &mut R,
        block_size: u32,
        _block_start_pos: u64,
    ) -> Result<()> {
        let safe_size = if self.parse_options.distrust_size {
            min(block_size, self.parse_options.max_block_size)
        } else {
            block_size
        };

        let mut data = vec![0u8; safe_size as usize];
        let bytes_read = reader.read(&mut data)?;

        if bytes_read < safe_size as usize {
            return Err(AudexError::InvalidData(
                "Truncated SEEKTABLE block".to_string(),
            ));
        }

        data.truncate(bytes_read);

        // Use robust seek table parsing with limits
        let max_seekpoints = Some(10000); // Reasonable limit for seek points
        let seektable = SeekTable::from_bytes_with_options(&data, max_seekpoints)?;
        self.seektable = Some(seektable);

        // Skip any remaining bytes if we truncated
        if block_size > safe_size {
            reader.seek(SeekFrom::Current((block_size - safe_size) as i64))?;
        }

        Ok(())
    }

    /// Parse CUESHEET metadata block (legacy)
    fn parse_cuesheet_block<R: Read>(&mut self, reader: &mut R, block_size: u32) -> Result<()> {
        // Enforce global ParseLimits before allocating (see parse_seektable_block)
        crate::limits::ParseLimits::default()
            .check_tag_size(block_size as u64, "FLAC legacy cuesheet block")?;
        if block_size > Self::MAX_LEGACY_BLOCK {
            return Err(AudexError::ParseError(format!(
                "FLAC block too large: {} bytes",
                block_size
            )));
        }
        let mut data = vec![0u8; block_size as usize];
        reader.read_exact(&mut data)?;

        let cuesheet = CueSheet::from_bytes(&data)?;
        self.cuesheet = Some(cuesheet);

        Ok(())
    }

    /// Parse CUESHEET metadata block with safety checks
    fn parse_cuesheet_block_safe<R: Read + Seek>(
        &mut self,
        reader: &mut R,
        block_size: u32,
        _block_start_pos: u64,
    ) -> Result<()> {
        let safe_size = if self.parse_options.distrust_size {
            min(block_size, self.parse_options.max_block_size)
        } else {
            block_size
        };

        let mut data = vec![0u8; safe_size as usize];
        let bytes_read = reader.read(&mut data)?;

        if bytes_read < safe_size as usize {
            return Err(AudexError::InvalidData(
                "Truncated CUESHEET block".to_string(),
            ));
        }

        data.truncate(bytes_read);
        let cuesheet = CueSheet::from_bytes(&data)?;
        self.cuesheet = Some(cuesheet);

        // Skip any remaining bytes if we truncated
        if block_size > safe_size {
            reader.seek(SeekFrom::Current((block_size - safe_size) as i64))?;
        }

        Ok(())
    }

    /// Parse PICTURE metadata block (legacy)
    fn parse_picture_block<R: Read>(&mut self, reader: &mut R, block_size: u32) -> Result<()> {
        // Enforce global ParseLimits before allocating (see parse_seektable_block)
        crate::limits::ParseLimits::default()
            .check_tag_size(block_size as u64, "FLAC legacy picture block")?;
        if block_size > Self::MAX_LEGACY_BLOCK {
            return Err(AudexError::ParseError(format!(
                "FLAC block too large: {} bytes",
                block_size
            )));
        }
        let mut data = vec![0u8; block_size as usize];
        reader.read_exact(&mut data)?;

        let picture = Picture::from_bytes(&data)?;
        self.pictures.push(picture);

        Ok(())
    }

    /// Parse PICTURE metadata block with safety checks
    fn parse_picture_block_safe<R: Read + Seek>(
        &mut self,
        reader: &mut R,
        block_size: u32,
        _block_start_pos: u64,
    ) -> Result<()> {
        if self.parse_options.distrust_size {
            // When distrust_size is set, ignore header size and parse directly
            // from the stream using internal length fields.
            let start_pos = reader.stream_position()?;
            let max_picture_size = Some(self.parse_options.max_block_size as usize);

            match Picture::from_reader(reader, max_picture_size) {
                Ok(picture) => {
                    let real_size = reader.stream_position()? - start_pos;
                    if real_size > 0xFFFFFF_u64 {
                        self.original_overflow_sizes.insert(6, block_size);
                    }
                    self.pictures.push(picture);
                }
                Err(_) if self.parse_options.ignore_errors => {
                    // Skip corrupted picture, try to recover position
                    let _ = reader.seek(SeekFrom::Start(start_pos + block_size as u64));
                }
                Err(e) => return Err(e),
            }
        } else {
            let mut data = vec![0u8; block_size as usize];
            reader.read_exact(&mut data)?;

            let max_picture_size = Some(self.parse_options.max_block_size as usize);

            match Picture::from_bytes_with_options(&data, max_picture_size) {
                Ok(picture) => self.pictures.push(picture),
                Err(_) if self.parse_options.ignore_errors => {}
                Err(e) => return Err(e),
            }
        }

        Ok(())
    }

    /// Parse PADDING metadata block (legacy)
    fn parse_padding_block<R: Read + Seek>(
        &mut self,
        reader: &mut R,
        block_size: u32,
    ) -> Result<()> {
        // For padding blocks, we don't need to read the actual data
        // Just skip it and record the size
        let padding = Padding::new(block_size as usize);
        self.padding_blocks.push(padding);
        reader.seek(SeekFrom::Current(block_size as i64))?;
        Ok(())
    }

    /// Parse APPLICATION metadata block (legacy)
    fn parse_application_block<R: Read>(&mut self, reader: &mut R, block_size: u32) -> Result<()> {
        let mut data = vec![0u8; block_size as usize];
        reader.read_exact(&mut data)?;

        let application_block = ApplicationBlock::from_bytes(&data)?;
        self.application_blocks.push(application_block);

        Ok(())
    }

    /// Parse APPLICATION metadata block with safety checks
    fn parse_application_block_safe<R: Read + Seek>(
        &mut self,
        reader: &mut R,
        block_size: u32,
        _block_start_pos: u64,
    ) -> Result<()> {
        let safe_size = if self.parse_options.distrust_size {
            min(block_size, self.parse_options.max_block_size)
        } else {
            block_size
        };

        let mut data = vec![0u8; safe_size as usize];
        let bytes_read = reader.read(&mut data)?;

        if bytes_read < safe_size as usize {
            return Err(AudexError::InvalidData(
                "Truncated APPLICATION block".to_string(),
            ));
        }

        data.truncate(bytes_read);

        let application_block = ApplicationBlock::from_bytes(&data)?;
        self.application_blocks.push(application_block);

        // Skip any remaining bytes if we truncated
        if block_size > safe_size {
            reader.seek(SeekFrom::Current((block_size - safe_size) as i64))?;
        }

        Ok(())
    }

    /// Parse PADDING metadata block with safety checks
    fn parse_padding_block_safe<R: Read + Seek>(
        &mut self,
        reader: &mut R,
        block_size: u32,
        _block_start_pos: u64,
    ) -> Result<()> {
        // Padding blocks can be very large, so we handle them efficiently
        let safe_size = if self.parse_options.distrust_size {
            min(block_size, self.parse_options.max_block_size)
        } else {
            block_size
        };

        // Create padding block record
        let padding = Padding::new(safe_size as usize);
        self.padding_blocks.push(padding);

        // Skip the padding data without reading it into memory
        reader.seek(SeekFrom::Current(safe_size as i64))?;

        // Skip any remaining bytes if we truncated
        if block_size > safe_size {
            reader.seek(SeekFrom::Current((block_size - safe_size) as i64))?;
        }

        Ok(())
    }

    /// Add a new picture to the file
    pub fn add_picture(&mut self, picture: Picture) {
        // Pictures will be validated when serialized during save()
        self.pictures.push(picture);
        self.dirty = true;
    }

    /// Clear all pictures from the file
    pub fn clear_pictures(&mut self) {
        self.pictures.clear();
        // Also remove picture blocks from metadata_blocks (block type 6)
        self.metadata_blocks.retain(|block| block.block_type != 6);
        self.dirty = true;
    }

    /// Add a new Application block to the file
    pub fn add_application_block(&mut self, application_block: ApplicationBlock) {
        self.application_blocks.push(application_block);
        self.dirty = true;
    }

    /// Clear all Application blocks from the file
    pub fn clear_application_blocks(&mut self) {
        self.application_blocks.clear();
        self.dirty = true;
    }

    /// Get Application blocks with a specific application ID
    pub fn get_application_blocks_by_id(&self, application_id: [u8; 4]) -> Vec<&ApplicationBlock> {
        self.application_blocks
            .iter()
            .filter(|block| block.application_id == application_id)
            .collect()
    }

    /// Remove Application blocks with a specific application ID
    pub fn remove_application_blocks_by_id(&mut self, application_id: [u8; 4]) -> usize {
        let initial_len = self.application_blocks.len();
        self.application_blocks
            .retain(|block| block.application_id != application_id);
        let removed_count = initial_len - self.application_blocks.len();
        if removed_count > 0 {
            self.dirty = true;
        }
        removed_count
    }

    /// Add padding block to the file
    pub fn add_padding(&mut self, size: usize) {
        if size > 0 {
            self.padding_blocks.push(Padding::new(size));
            self.dirty = true;
        }
    }

    /// Clear all padding blocks from the file
    pub fn clear_padding(&mut self) {
        self.padding_blocks.clear();
        self.dirty = true;
    }

    /// Get total padding size across all padding blocks
    pub fn total_padding_size(&self) -> usize {
        self.padding_blocks.iter().map(|p| p.size).sum()
    }

    /// Get information about blocks that exceed size limits
    pub fn get_overflow_blocks(&self) -> &[(u8, usize)] {
        &self.invalid_overflow_size
    }

    /// Check if any blocks have overflow size issues
    pub fn has_overflow_blocks(&self) -> bool {
        !self.invalid_overflow_size.is_empty()
    }

    /// Optimize padding distribution for better performance
    /// Consolidates small padding blocks and removes empty ones
    pub fn optimize_padding(&mut self) {
        let initial_len = self.padding_blocks.len();

        // Remove zero-size padding blocks
        self.padding_blocks.retain(|p| p.size > 0);

        // If we have multiple small padding blocks, consider consolidating
        if self.padding_blocks.len() > 1 {
            let total_size: usize = self.padding_blocks.iter().map(|p| p.size).sum();
            let small_blocks = self.padding_blocks.iter().filter(|p| p.size < 1024).count();

            // If we have many small blocks, consolidate them
            if small_blocks > 3 {
                self.padding_blocks.clear();
                if total_size > 0 {
                    self.padding_blocks.push(Padding::new(total_size));
                }
            }
        }

        // Mark dirty if we actually changed the padding structure
        if initial_len != self.padding_blocks.len() {
            self.dirty = true;
        }
    }

    /// Calculate optimal padding size based on metadata growth patterns
    pub fn calculate_optimal_padding(&self, growth_factor: f64) -> usize {
        // Calculate current metadata size (excluding padding)
        let mut total_metadata_size = 34; // STREAMINFO is always 34 bytes

        if let Some(ref tags) = self.tags {
            if let Ok(data) = tags.to_bytes() {
                total_metadata_size += data.len();
            }
        }

        total_metadata_size += self
            .pictures
            .iter()
            .filter_map(|p| p.to_bytes().ok())
            .map(|data| data.len())
            .sum::<usize>();

        if let Some(ref seektable) = self.seektable {
            if let Ok(data) = seektable.to_bytes() {
                total_metadata_size += data.len();
            }
        }

        if let Some(ref cuesheet) = self.cuesheet {
            if let Ok(data) = cuesheet.to_bytes() {
                total_metadata_size += data.len();
            }
        }

        // Apply growth factor with reasonable bounds
        let growth_padding = (total_metadata_size as f64 * growth_factor) as usize;
        let min_padding = 1024; // 1KB minimum
        let max_padding = 64 * 1024; // 64KB maximum

        growth_padding.max(min_padding).min(max_padding)
    }

    /// Add empty Vorbis comment block to file
    pub fn add_tags(&mut self) -> Result<()> {
        if self.tags.is_some() && !self.parse_options.ignore_errors {
            return Err(AudexError::FLACVorbis);
        }
        // With ignore_errors, replace existing tags

        self.tags = Some(VCommentDict::with_framing(false));
        self.dirty = true;
        Ok(())
    }

    /// Saves metadata changes to the FLAC file using in-place modification.
    ///
    /// This method writes modified metadata (tags, pictures, etc.) back to the file
    /// while preserving the audio data. It uses in-place modification when possible
    /// to avoid rewriting the entire file.
    ///
    /// # Strategy
    ///
    /// The save operation attempts to:
    /// 1. Reuse existing padding if metadata fits
    /// 2. Resize metadata blocks if needed
    /// 3. Only rewrite the metadata section, not audio data
    /// 4. Maintain optimal padding for future edits
    ///
    /// # Arguments
    ///
    /// * `path` - Optional alternative path to save to (uses original filename if `None`)
    /// * `_delete_id3` - (Reserved) Whether to remove ID3 tags
    /// * `padding_func` - Optional function to calculate custom padding size
    ///
    /// # Returns
    ///
    /// * `Ok(())` - Metadata successfully saved
    /// * `Err(AudexError)` - Failed to write file
    ///
    /// # Errors
    ///
    /// This function will return an error if:
    /// - The file cannot be opened for writing
    /// - The file doesn't exist
    /// - Insufficient disk space
    /// - Metadata blocks exceed FLAC size limits
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use audex::flac::FLAC;
    /// use audex::Tags;
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let mut flac = FLAC::from_file("song.flac")?;
    ///
    ///     // Modify tags using the Tags trait
    ///     if let Some(ref mut tags) = flac.tags {
    ///         tags.set("ARTIST", vec!["New Artist".to_string()]);
    ///     }
    ///
    ///     // Save with default padding
    ///     flac.save_to_file(None::<&str>, false, None)?;
    ///     Ok(())
    /// }
    /// ```
    ///
    /// ```no_run
    /// use audex::flac::FLAC;
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let mut flac = FLAC::from_file("song.flac")?;
    ///
    ///     // Save to different file
    ///     flac.save_to_file(Some("output.flac"), false, None)?;
    ///     Ok(())
    /// }
    /// ```
    ///
    /// # See Also
    ///
    /// - [`FLAC::save`](FileType::save) - Trait method for saving
    /// - [`FLAC::add_padding`] - Add padding for future edits
    pub fn save_to_file<P: AsRef<Path>>(
        &mut self,
        path: Option<P>,
        _delete_id3: bool,
        padding_func: Option<PaddingFunction>,
    ) -> Result<()> {
        let file_path = match path {
            Some(p) => p.as_ref().to_path_buf(),
            None => std::path::PathBuf::from(&self.filename),
        };

        self.save_to_file_in_place(&file_path, padding_func)
    }

    fn save_to_file_in_place(
        &mut self,
        file_path: &Path,
        padding_func: Option<PaddingFunction>,
    ) -> Result<()> {
        if !file_path.exists() {
            return Err(AudexError::InvalidData("File does not exist".to_string()));
        }

        // Open file for reading and writing
        let mut file = OpenOptions::new().read(true).write(true).open(file_path)?;

        // Find where the audio data starts by reading minimal header data
        let audio_offset = self.find_audio_offset_from_file(&mut file)?;

        // Calculate available space (current metadata size minus "fLaC" header)
        let header_size = 4u64; // "fLaC" signature size
        let available = audio_offset.checked_sub(header_size).ok_or_else(|| {
            AudexError::InvalidData(
                "audio offset is smaller than FLAC header size, file may be corrupt".to_string(),
            )
        })?;

        // Calculate content (audio data) size for padding calculation
        let file_size = file.seek(SeekFrom::End(0))?;
        let content_size = file_size.checked_sub(audio_offset).ok_or_else(|| {
            AudexError::InvalidData(
                "file size is smaller than audio offset, file may be truncated".to_string(),
            )
        })? as usize;

        // Generate new metadata, or return early if nothing changed
        let new_metadata = match self.prepare_metadata(padding_func, available, content_size)? {
            Some(m) => m,
            None => return Ok(()), // no changes
        };

        let data_size = new_metadata.len() as u64;

        // Log metadata block size and padding details for diagnostics
        trace_event!(
            metadata_bytes = data_size,
            available_bytes = available,
            audio_offset = audio_offset,
            "writing FLAC metadata blocks"
        );

        // Use resize_bytes to modify file in-place (works with File which
        // supports set_len for truncation).
        resize_bytes(&mut file, available, data_size, header_size)?;

        // Write "fLaC" marker + new metadata
        file.seek(SeekFrom::Start(0))?;
        file.write_all(b"fLaC")?;
        file.write_all(&new_metadata)?;

        // Store new metadata as original and reset dirty flag
        self.original_metadata = new_metadata;
        self.dirty = false;

        Ok(())
    }

    /// Core save logic that operates on any readable/writable/seekable handle.
    ///
    /// This is used by the writer-based save path (`save_to_writer`,
    /// `clear_writer`). The handle must already contain valid FLAC data
    /// (starting with the `fLaC` marker followed by metadata blocks and
    /// audio frames).
    fn save_to_writer_impl(
        &mut self,
        file: &mut dyn crate::ReadWriteSeek,
        padding_func: Option<PaddingFunction>,
    ) -> Result<()> {
        // Find where the audio data starts by reading minimal header data
        let audio_offset = self.find_audio_offset_from_file(file)?;

        // Calculate available space (current metadata size minus "fLaC" header)
        let header_size = 4u64; // "fLaC" signature size
        let available = audio_offset.checked_sub(header_size).ok_or_else(|| {
            AudexError::InvalidData(
                "audio offset is smaller than FLAC header size, file may be corrupt".to_string(),
            )
        })?;

        // Calculate content (audio data) size for padding calculation
        let file_size = file.seek(SeekFrom::End(0))?;
        let content_size = file_size.checked_sub(audio_offset).ok_or_else(|| {
            AudexError::InvalidData(
                "file size is smaller than audio offset, file may be truncated".to_string(),
            )
        })? as usize;

        // Generate new metadata, or return early if nothing changed
        let new_metadata = match self.prepare_metadata(padding_func, available, content_size)? {
            Some(m) => m,
            None => return Ok(()), // no changes
        };

        let data_size = new_metadata.len() as u64;

        // Resize the metadata region in-place and keep track of the new logical
        // end so writer-based callers can observe the correct boundary.
        let logical_end = Self::resize_metadata_region(file, available, data_size, header_size)?;

        // Write "fLaC" marker + new metadata
        file.seek(SeekFrom::Start(0))?;
        file.write_all(b"fLaC")?;
        file.write_all(&new_metadata)?;
        file.seek(SeekFrom::Start(logical_end))?;

        // Store new metadata as original and reset dirty flag
        self.original_metadata = new_metadata;
        self.dirty = false;

        Ok(())
    }

    /// Prepare new metadata blocks for saving.
    ///
    /// Returns `Some(bytes)` with the serialised metadata if there are changes
    /// to write, or `None` if the metadata is unchanged and the save can be
    /// skipped.
    fn prepare_metadata(
        &mut self,
        padding_func: Option<PaddingFunction>,
        available: u64,
        content_size: usize,
    ) -> Result<Option<Vec<u8>>> {
        if padding_func.is_none()
            && !self.original_metadata.is_empty()
            && self.original_metadata.len() as u64 == available
        {
            // Try to regenerate and see if it matches original
            let regenerated =
                self.generate_metadata_blocks(None, available as usize, content_size)?;
            if regenerated == self.original_metadata {
                // No changes detected, skip write
                self.dirty = false;
                return Ok(None);
            }
            Ok(Some(regenerated))
        } else {
            // Need to regenerate with custom padding or size changed
            let regenerated =
                self.generate_metadata_blocks(padding_func, available as usize, content_size)?;
            Ok(Some(regenerated))
        }
    }

    /// Shift audio data and resize the metadata region between the `fLaC`
    /// header and the first audio frame.
    ///
    /// This operates on a `dyn ReadWriteSeek` trait object so it can be
    /// used by the writer-based save path without requiring a `'static`
    /// bound (unlike `resize_bytes` from `util`).
    ///
    /// Returns the new logical end of the file after resizing. When the
    /// metadata shrinks, stale trailing bytes are scrubbed or truncated via
    /// the shared writer helper before the value is returned.
    fn resize_metadata_region(
        file: &mut dyn crate::ReadWriteSeek,
        old_size: u64,
        new_size: u64,
        offset: u64,
    ) -> Result<u64> {
        if old_size == new_size {
            return file.seek(SeekFrom::End(0)).map_err(Into::into);
        }

        let file_size = file.seek(SeekFrom::End(0))?;
        let buffer_size: usize = 64 * 1024;

        if new_size > old_size {
            // Metadata grew -- shift audio data to the right to make room.
            let grow = new_size - old_size;
            let src_start = offset + old_size; // where audio currently starts
            let bytes_to_move = file_size - src_start;

            // Extend the stream by writing zeroes at the end.
            file.seek(SeekFrom::End(0))?;
            let mut remaining = grow;
            let zero_buf = vec![0u8; buffer_size];
            while remaining > 0 {
                let chunk = std::cmp::min(remaining, buffer_size as u64) as usize;
                file.write_all(&zero_buf[..chunk])?;
                remaining -= chunk as u64;
            }

            // Move data from right to left (reverse order to avoid overlap
            // corruption).
            if bytes_to_move > 0 {
                let mut pos = bytes_to_move;
                let mut buf = vec![0u8; buffer_size];
                while pos > 0 {
                    let chunk = std::cmp::min(pos, buffer_size as u64) as usize;
                    let read_offset = src_start + pos - chunk as u64;
                    let write_offset = read_offset + grow;

                    file.seek(SeekFrom::Start(read_offset))?;
                    file.read_exact(&mut buf[..chunk])?;
                    file.seek(SeekFrom::Start(write_offset))?;
                    file.write_all(&buf[..chunk])?;

                    pos -= chunk as u64;
                }
            }
            let new_total = file_size + (new_size - old_size);
            file.flush()?;
            Ok(new_total)
        } else {
            // Metadata shrank -- shift audio data to the left.
            let src_start = offset + old_size; // where audio currently starts
            let dst_start = offset + new_size; // where audio should go
            let bytes_to_move = file_size - src_start;

            // Move data left in forward order.
            let mut moved = 0u64;
            let mut buf = vec![0u8; buffer_size];
            while moved < bytes_to_move {
                let chunk = std::cmp::min(bytes_to_move - moved, buffer_size as u64) as usize;
                file.seek(SeekFrom::Start(src_start + moved))?;
                file.read_exact(&mut buf[..chunk])?;
                file.seek(SeekFrom::Start(dst_start + moved))?;
                file.write_all(&buf[..chunk])?;
                moved += chunk as u64;
            }

            // Scrub or truncate any stale trailing bytes left behind by the
            // left-shift. Trait-object writers cannot always be physically
            // truncated, so we use the shared fallback helper.
            let new_total = file_size - (old_size - new_size);
            crate::util::truncate_writer_dyn(file, new_total)?;
            file.flush()?;
            Ok(new_total)
        }
    }

    /// Find where audio data starts by reading from file handle
    fn find_audio_offset_from_file<F: Read + Seek + ?Sized>(&self, file: &mut F) -> Result<u64> {
        file.seek(SeekFrom::Start(0))?;

        // Check for ID3 tags first
        let mut signature = [0u8; 4];
        file.read_exact(&mut signature)?;

        if &signature[..3] == b"ID3" {
            // Skip ID3v2 tag
            let mut id3_size_bytes = [0u8; 6];
            file.read_exact(&mut id3_size_bytes)?;
            let id3_size = self.decode_id3_size(&id3_size_bytes[2..])?;
            file.seek(SeekFrom::Current(id3_size as i64))?;

            // Read FLAC signature after ID3
            file.read_exact(&mut signature)?;
        }

        if &signature != b"fLaC" {
            return Err(AudexError::FLACNoHeader);
        }

        // Cap the number of metadata blocks to prevent infinite loops on
        // crafted files where the is_last flag is never set and block
        // sizes are zero.
        const MAX_METADATA_BLOCKS: usize = 1024;
        let mut block_count: usize = 0;

        loop {
            block_count += 1;
            if block_count > MAX_METADATA_BLOCKS {
                return Err(AudexError::InvalidData(format!(
                    "Exceeded maximum metadata block count ({}) in audio offset search",
                    MAX_METADATA_BLOCKS
                )));
            }

            // Read block header (4 bytes)
            let mut header = [0u8; 4];
            match file.read_exact(&mut header) {
                Ok(()) => {}
                Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                    break;
                }
                Err(e) => return Err(e.into()),
            }

            let is_last = (header[0] & 0x80) != 0;
            let block_type = header[0] & 0x7F;
            let block_size = u32::from_be_bytes([0, header[1], header[2], header[3]]) as u64;

            if block_type == 4 {
                // Vorbis comment: read actual content to find true size
                Self::skip_vorbis_comment_content(file)?;
            } else if block_type == 6 {
                // Picture: read actual content to find true size
                Self::skip_picture_content(file)?;
            } else {
                file.seek(SeekFrom::Current(block_size as i64))?;
            }

            if is_last {
                break;
            }
        }

        Ok(file.stream_position()?)
    }

    /// Skip past a Vorbis Comment block by reading its actual content
    /// (not trusting the header size field)
    fn skip_vorbis_comment_content<F: Read + Seek + ?Sized>(file: &mut F) -> Result<()> {
        let cur = file.stream_position()?;
        let file_end = file.seek(SeekFrom::End(0))?;
        file.seek(SeekFrom::Start(cur))?;

        let mut len_buf = [0u8; 4];

        // vendor string length (4 bytes LE) + vendor string
        file.read_exact(&mut len_buf)?;
        let vendor_len = u32::from_le_bytes(len_buf) as u64;
        if file.stream_position()? + vendor_len > file_end {
            return Err(AudexError::InvalidData(
                "Vorbis vendor length exceeds file size".to_string(),
            ));
        }
        file.seek(SeekFrom::Current(vendor_len as i64))?;

        // comment count (4 bytes LE)
        file.read_exact(&mut len_buf)?;
        let count = u32::from_le_bytes(len_buf);
        if count > 100_000 {
            return Err(AudexError::InvalidData(format!(
                "Vorbis comment count {} too large",
                count
            )));
        }

        // each comment: length (4 bytes LE) + data
        for _ in 0..count {
            file.read_exact(&mut len_buf)?;
            let comment_len = u32::from_le_bytes(len_buf) as u64;
            if file.stream_position()? + comment_len > file_end {
                return Err(AudexError::InvalidData(
                    "Vorbis comment length exceeds file size".to_string(),
                ));
            }
            file.seek(SeekFrom::Current(comment_len as i64))?;
        }

        Ok(())
    }

    /// Skip past a Picture block by reading its actual content
    /// (not trusting the header size field)
    fn skip_picture_content<F: Read + Seek + ?Sized>(file: &mut F) -> Result<()> {
        let cur = file.stream_position()?;
        let file_end = file.seek(SeekFrom::End(0))?;
        file.seek(SeekFrom::Start(cur))?;

        let mut buf4 = [0u8; 4];

        // picture type (4 bytes BE)
        file.read_exact(&mut buf4)?;

        // MIME type: length (4 bytes BE) + data
        file.read_exact(&mut buf4)?;
        let mime_len = u32::from_be_bytes(buf4) as u64;
        if file.stream_position()? + mime_len > file_end {
            return Err(AudexError::InvalidData(
                "Picture MIME length exceeds file size".to_string(),
            ));
        }
        file.seek(SeekFrom::Current(mime_len as i64))?;

        // description: length (4 bytes BE) + data
        file.read_exact(&mut buf4)?;
        let desc_len = u32::from_be_bytes(buf4) as u64;
        if file.stream_position()? + desc_len > file_end {
            return Err(AudexError::InvalidData(
                "Picture description length exceeds file size".to_string(),
            ));
        }
        file.seek(SeekFrom::Current(desc_len as i64))?;

        // width (4) + height (4) + depth (4) + colors (4)
        file.seek(SeekFrom::Current(16))?;

        // picture data: length (4 bytes BE) + data
        file.read_exact(&mut buf4)?;
        let data_len = u32::from_be_bytes(buf4) as u64;
        if file.stream_position()? + data_len > file_end {
            return Err(AudexError::InvalidData(
                "Picture data length exceeds file size".to_string(),
            ));
        }
        file.seek(SeekFrom::Current(data_len as i64))?;

        Ok(())
    }

    /// Generate new metadata blocks as a single byte vector
    fn generate_metadata_blocks(
        &mut self,
        padding_func: Option<PaddingFunction>,
        available: usize,
        content_size: usize,
    ) -> Result<Vec<u8>> {
        // Clear any previous overflow size tracking
        self.invalid_overflow_size.clear();

        // Collect metadata blocks to write
        let mut blocks = Vec::new();

        // Always include StreamInfo first
        let streaminfo_data = self.info.to_bytes()?;
        self.add_block_with_overflow_check(&mut blocks, 0, streaminfo_data)?;

        // Track which blocks we've written to avoid duplicates
        let mut written_blocks = std::collections::HashSet::new();
        written_blocks.insert(0u8); // STREAMINFO already written

        // Clone data before the loop to avoid borrow issues
        let application_blocks = self.application_blocks.clone();
        let pictures = self.pictures.clone();
        let metadata_blocks = self.metadata_blocks.clone();
        let original_block_order = self.original_block_order.clone();

        // Use original block order if available, otherwise use default order
        if !original_block_order.is_empty() {
            // Write blocks in original order
            for &block_type in &original_block_order {
                // Skip STREAMINFO (already written) and blocks we've already added
                if block_type == 0 || written_blocks.contains(&block_type) {
                    continue;
                }

                match block_type {
                    1 => {
                        // PADDING - skip for now, will be handled at the end
                        continue;
                    }
                    2 => {
                        // APPLICATION - add all application blocks
                        if !written_blocks.contains(&2) {
                            for app_block in &application_blocks {
                                let app_data = app_block.to_bytes()?;
                                self.add_block_with_overflow_check(&mut blocks, 2, app_data)?;
                            }
                            written_blocks.insert(2);
                        }
                    }
                    3 => {
                        // SEEKTABLE
                        if let Some(ref seektable) = self.seektable {
                            let seek_data = seektable.to_bytes()?;
                            self.add_block_with_overflow_check(&mut blocks, 3, seek_data)?;
                            written_blocks.insert(3);
                        }
                    }
                    4 => {
                        // VORBIS_COMMENT
                        if let Some(ref tags) = self.tags {
                            let mut comment_to_write = tags.clone();
                            if !comment_to_write.keys().is_empty() {
                                comment_to_write.set_vendor(format!("Audex {}", VERSION_STRING));
                            }
                            let vorbis_data = comment_to_write.to_bytes()?;
                            self.add_block_with_overflow_check(&mut blocks, 4, vorbis_data)?;
                            written_blocks.insert(4);
                        }
                    }
                    5 => {
                        // CUESHEET
                        if let Some(ref cuesheet) = self.cuesheet {
                            let cue_data = cuesheet.to_bytes()?;
                            self.add_block_with_overflow_check(&mut blocks, 5, cue_data)?;
                            written_blocks.insert(5);
                        }
                    }
                    6 => {
                        // PICTURE - add all pictures
                        if !written_blocks.contains(&6) {
                            for picture in &pictures {
                                let pic_data = picture.to_bytes()?;
                                let override_size = self.validate_picture_size(&pic_data)?;
                                let mut block = MetadataBlock::new(6, pic_data);
                                block.override_header_size = override_size;
                                blocks.push(block);
                            }
                            written_blocks.insert(6);
                        }
                    }
                    _ => {
                        // Unknown block type - add from metadata_blocks
                        for metadata_block in &metadata_blocks {
                            if metadata_block.block_type == block_type {
                                let block_data = metadata_block.data.clone();
                                self.add_block_with_overflow_check(
                                    &mut blocks,
                                    block_type,
                                    block_data,
                                )?;
                            }
                        }
                        written_blocks.insert(block_type);
                    }
                }
            }
        }

        // Add any blocks not yet written (handles both default order and
        // blocks added after loading that weren't in the original order)
        if !written_blocks.contains(&4) {
            if let Some(ref tags) = self.tags {
                let mut comment_to_write = tags.clone();
                if !comment_to_write.keys().is_empty() {
                    comment_to_write.set_vendor(format!("Audex {}", VERSION_STRING));
                }
                let vorbis_data = comment_to_write.to_bytes()?;
                self.add_block_with_overflow_check(&mut blocks, 4, vorbis_data)?;
                written_blocks.insert(4);
            }
        }

        if !written_blocks.contains(&3) {
            if let Some(ref seektable) = self.seektable {
                let seek_data = seektable.to_bytes()?;
                self.add_block_with_overflow_check(&mut blocks, 3, seek_data)?;
                written_blocks.insert(3);
            }
        }

        if !written_blocks.contains(&2) {
            for app_block in &application_blocks {
                let app_data = app_block.to_bytes()?;
                self.add_block_with_overflow_check(&mut blocks, 2, app_data)?;
            }
            written_blocks.insert(2);
        }

        if !written_blocks.contains(&5) {
            if let Some(ref cuesheet) = self.cuesheet {
                let cue_data = cuesheet.to_bytes()?;
                self.add_block_with_overflow_check(&mut blocks, 5, cue_data)?;
                written_blocks.insert(5);
            }
        }

        if !written_blocks.contains(&6) {
            for picture in &pictures {
                let pic_data = picture.to_bytes()?;
                let override_size = self.validate_picture_size(&pic_data)?;
                let mut block = MetadataBlock::new(6, pic_data);
                block.override_header_size = override_size;
                blocks.push(block);
            }
            written_blocks.insert(6);
        }

        // Add other metadata blocks not yet written
        for metadata_block in &metadata_blocks {
            if matches!(metadata_block.block_type, 0..=6) {
                continue;
            }
            if !written_blocks.contains(&metadata_block.block_type) {
                let block_data = metadata_block.data.clone();
                self.add_block_with_overflow_check(
                    &mut blocks,
                    metadata_block.block_type,
                    block_data,
                )?;
                written_blocks.insert(metadata_block.block_type);
            }
        }

        // Always recalculate padding:
        // strip all existing padding and add a single new padding block
        {
            let padding_size = self.calculate_padding_size_for_generation(
                available,
                content_size,
                &blocks,
                padding_func,
            )?;

            if padding_size > 0 {
                // Handle very large padding blocks by splitting if necessary
                self.add_padding_blocks(&mut blocks, padding_size)?;
            }
        }

        // Convert blocks to byte vector
        let mut metadata_bytes = Vec::new();
        for (i, block) in blocks.iter().enumerate() {
            let is_last = i == blocks.len() - 1;

            // Validate block type before writing (0-126 valid; 127 is
            // reserved, >= 128 collides with the is-last flag bit)
            if block.block_type >= 127 {
                return Err(AudexError::InvalidData(format!(
                    "FLAC block type {} is out of valid range (0-126)",
                    block.block_type
                )));
            }

            // Write block header
            let header_byte = block.block_type | if is_last { 0x80 } else { 0x00 };
            metadata_bytes.push(header_byte);

            // Write block size (24 bits), using override if present
            let size = block
                .override_header_size
                .unwrap_or(block.data.len() as u32);
            let size_bytes = size.to_be_bytes();
            metadata_bytes.extend_from_slice(&size_bytes[1..]);

            // Write block data
            metadata_bytes.extend_from_slice(&block.data);
        }

        Ok(metadata_bytes)
    }

    /// Calculate padding size for metadata generation
    fn calculate_padding_size_for_generation(
        &self,
        available: usize,
        content_size: usize,
        blocks: &[MetadataBlock],
        padding_func: Option<PaddingFunction>,
    ) -> Result<usize> {
        // Calculate size of all metadata blocks
        let mut blockssize: usize = blocks.iter().map(|b| 4 + b.data.len()).sum();

        // Take the padding overhead into account. We always add one to make things simple.
        // This adds the overhead of one padding block header (4 bytes)
        blockssize += 4;

        // Calculate padding space
        let padding_space = (available as i64) - (blockssize as i64);
        let cont_size = content_size as i64;

        // Create PaddingInfo
        let info = PaddingInfo::new(padding_space, cont_size);

        // Get padding using standard algorithm
        let padding_result = info.get_padding_with(padding_func);

        // Apply max size limit as per FLAC specification
        let padding_size = std::cmp::min(padding_result, Picture::MAX_SIZE as i64);

        Ok(padding_size.max(0) as usize)
    }

    /// Validate picture block size with tolerance.
    ///
    /// Returns `Some(original_size)` if the block was already oversized on
    /// load and should use the original header size; returns `None` if the
    /// block fits within spec limits.
    fn validate_picture_size(&mut self, pic_data: &[u8]) -> Result<Option<u32>> {
        const MAX_BLOCK_SIZE: usize = 0xFFFFFF; // 24-bit limit

        if pic_data.len() > MAX_BLOCK_SIZE {
            // If the picture block was already oversized when loaded, allow
            // the round-trip with the original header size.
            if let Some(&original_size) = self.original_overflow_sizes.get(&6u8) {
                self.invalid_overflow_size.push((6, pic_data.len()));
                return Ok(Some(original_size));
            }

            // Newly oversized -- error out.
            self.invalid_overflow_size.push((6, pic_data.len()));
            return Err(AudexError::InvalidData(format!(
                "Picture block too large: {} bytes (max: {} bytes)",
                pic_data.len(),
                MAX_BLOCK_SIZE
            )));
        }

        Ok(None)
    }

    /// Add a metadata block with overflow size checking.
    ///
    /// If the block data exceeds the 24-bit size limit (0xFFFFFF) but we have
    /// an original overflow size recorded from loading (i.e. the block was
    /// already oversized on disk), we allow the write and attach the original
    /// header size so the writer can emit it. This preserves the file's
    /// existing brokenness rather than refusing to save.
    fn add_block_with_overflow_check(
        &mut self,
        blocks: &mut Vec<MetadataBlock>,
        block_type: u8,
        data: Vec<u8>,
    ) -> Result<()> {
        const MAX_BLOCK_SIZE: usize = 0xFFFFFF; // 24-bit limit

        if data.len() > MAX_BLOCK_SIZE {
            // Check if this block type was already oversized when we loaded the
            // file. If so, we round-trip the original (wrong) header size
            // instead of erroring.
            if let Some(&original_size) = self.original_overflow_sizes.get(&block_type) {
                self.invalid_overflow_size.push((block_type, data.len()));
                let mut block = MetadataBlock::new(block_type, data);
                block.override_header_size = Some(original_size);
                blocks.push(block);
                return Ok(());
            }

            // Newly oversized block -- error out.
            self.invalid_overflow_size.push((block_type, data.len()));
            return Err(AudexError::InvalidData(format!(
                "Block type {} too large: {} bytes (max: {} bytes)",
                block_type,
                data.len(),
                MAX_BLOCK_SIZE
            )));
        }

        blocks.push(MetadataBlock::new(block_type, data));
        Ok(())
    }

    /// Add padding blocks, splitting large ones if necessary
    fn add_padding_blocks(
        &mut self,
        blocks: &mut Vec<MetadataBlock>,
        total_padding: usize,
    ) -> Result<()> {
        const MAX_PADDING_SIZE: usize = 0xFFFFFF; // 24-bit limit

        if total_padding == 0 {
            return Ok(());
        }

        if total_padding <= MAX_PADDING_SIZE {
            // Single padding block
            let padding_data = vec![0u8; total_padding];
            blocks.push(MetadataBlock::new(1, padding_data));
        } else {
            // Split into multiple padding blocks
            let mut remaining = total_padding;

            while remaining > 0 {
                let chunk_size = remaining.min(MAX_PADDING_SIZE);
                let padding_data = vec![0u8; chunk_size];
                blocks.push(MetadataBlock::new(1, padding_data));
                remaining -= chunk_size;
            }
        }

        Ok(())
    }

    /// Load FLAC file asynchronously with non-blocking I/O.
    ///
    /// This method provides the same functionality as `from_file()` but uses
    /// async I/O operations suitable for use in async runtimes like Tokio.
    ///
    /// # Arguments
    /// * `path` - Path to the FLAC file to load
    ///
    /// # Returns
    /// * `Ok(Self)` - Successfully loaded FLAC file with metadata
    /// * `Err(AudexError)` - Error occurred during file loading or parsing
    #[cfg(feature = "async")]
    pub async fn from_file_async<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::from_file_with_options_async(path, FLACParseOptions::default()).await
    }

    /// Load FLAC file asynchronously with custom parsing options.
    ///
    /// Allows fine-tuned control over parsing behavior such as error handling
    /// and block size validation when loading files asynchronously.
    ///
    /// # Arguments
    /// * `path` - Path to the FLAC file to load
    /// * `options` - Custom parsing options for robustness control
    ///
    /// # Returns
    /// * `Ok(Self)` - Successfully loaded FLAC file
    /// * `Err(AudexError)` - Error during loading or parsing
    #[cfg(feature = "async")]
    pub async fn from_file_with_options_async<P: AsRef<Path>>(
        path: P,
        options: FLACParseOptions,
    ) -> Result<Self> {
        let path = path.as_ref();
        let file = TokioFile::open(path).await?;
        let mut flac = Self::with_options(options);
        flac.filename = path.to_string_lossy().to_string();

        // Use streaming parsing for async operations
        let mut reader = TokioBufReader::new(file);
        flac.parse_flac_streaming_async(&mut reader).await?;

        Ok(flac)
    }

    /// Convenience alias for from_file_async to match common API patterns.
    #[cfg(feature = "async")]
    pub async fn load_async<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::from_file_async(path).await
    }

    /// Parse FLAC file structure with streaming async I/O.
    ///
    /// Internal method that handles the actual parsing of FLAC metadata blocks
    /// using non-blocking I/O operations.
    #[cfg(feature = "async")]
    async fn parse_flac_streaming_async<R>(&mut self, reader: &mut TokioBufReader<R>) -> Result<()>
    where
        R: tokio::io::AsyncRead + tokio::io::AsyncSeek + Unpin,
    {
        use tokio::io::{AsyncReadExt, AsyncSeekExt};

        // Check for ID3 tags that may precede FLAC data
        let mut signature = [0u8; 4];
        reader.read_exact(&mut signature).await?;

        if &signature[..3] == b"ID3" {
            // Skip ID3v2 tag to find FLAC signature
            let mut id3_size_bytes = [0u8; 6];
            reader.read_exact(&mut id3_size_bytes).await?;
            let id3_size = self.decode_id3_size(&id3_size_bytes[2..])?;
            reader.seek(SeekFrom::Current(id3_size as i64)).await?;

            // Read FLAC signature after ID3 tag
            reader.read_exact(&mut signature).await?;
        }

        if &signature != b"fLaC" {
            let error = FLACError {
                kind: FLACErrorKind::InvalidHeader,
                position: reader.stream_position().await.ok(),
                context: "Missing or invalid FLAC signature".to_string(),
            };
            self.parse_errors.push(error);
            return Err(AudexError::FLACNoHeader);
        }

        // Store position after fLaC header for metadata capture
        let metadata_start = reader.stream_position().await?;

        // Parse all metadata blocks
        self.parse_metadata_blocks_streaming_async(reader).await?;

        // Store position after metadata blocks (before audio data)
        let metadata_end = reader.stream_position().await?;

        // Capture original metadata for change detection during save
        // Cap to actual file size to prevent OOM from crafted size fields
        let file_end = reader.seek(SeekFrom::End(0)).await?;
        let capped_end = metadata_end.min(file_end);
        // Guard against underflow when metadata_start exceeds the computed end
        // position (can happen with truncated or malformed files)
        let metadata_size_u64 = capped_end.checked_sub(metadata_start).ok_or_else(|| {
            AudexError::InvalidData("metadata region extends beyond file boundaries".to_string())
        })?;
        let metadata_size = usize::try_from(metadata_size_u64).map_err(|_| {
            AudexError::InvalidData("metadata region too large for this platform".to_string())
        })?;
        reader.seek(SeekFrom::Start(metadata_start)).await?;
        self.original_metadata = vec![0u8; metadata_size];

        // Use read_exact for byte-identical capture, tolerate EOF for truncated files
        match reader.read_exact(&mut self.original_metadata).await {
            Ok(_) => {}
            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => {
                // Truncated file - clear original_metadata to skip comparison
                self.original_metadata.clear();
            }
            Err(e) => return Err(e.into()),
        }

        // Calculate accurate bitrate from audio stream size
        // Use metadata_end (already computed) as the audio start position
        // instead of stream_position() which can be unreliable with BufReader
        if self.info.total_samples > 0 {
            if let Ok(end_pos) = reader.seek(SeekFrom::End(0)).await {
                if let Some(duration) = self.info.length {
                    if end_pos >= metadata_end {
                        let audio_size = end_pos - metadata_end;
                        let duration_secs = duration.as_secs_f64();
                        if duration_secs > 0.0 {
                            let bitrate = (audio_size * 8) as f64 / duration_secs;
                            self.info.bitrate = Some(bitrate as u32);
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Parse FLAC metadata blocks with streaming async I/O.
    ///
    /// Handles individual block parsing with error recovery based on parse options.
    #[cfg(feature = "async")]
    async fn parse_metadata_blocks_streaming_async<R>(
        &mut self,
        reader: &mut TokioBufReader<R>,
    ) -> Result<()>
    where
        R: tokio::io::AsyncRead + tokio::io::AsyncSeek + Unpin,
    {
        use tokio::io::{AsyncReadExt, AsyncSeekExt};

        let mut is_last = false;
        let mut vorbis_comment_count = 0;
        // Cap the number of metadata blocks to prevent excessive iteration
        // on crafted files where the is_last flag is never set.
        const MAX_METADATA_BLOCKS: usize = 1024;
        let mut block_count: usize = 0;

        while !is_last {
            block_count += 1;
            if block_count > MAX_METADATA_BLOCKS {
                return Err(AudexError::InvalidData(format!(
                    "Exceeded maximum metadata block count ({})",
                    MAX_METADATA_BLOCKS
                )));
            }
            let block_start_pos = reader.stream_position().await?;

            // Read 4-byte block header
            let mut header = [0u8; 4];
            if let Err(e) = reader.read_exact(&mut header).await {
                if self.parse_options.ignore_errors {
                    self.parse_errors.push(FLACError {
                        kind: FLACErrorKind::CorruptedBlock,
                        position: Some(block_start_pos),
                        context: format!("Failed to read block header: {}", e),
                    });
                    break;
                }
                return Err(e.into());
            }

            let block_type = header[0] & 0x7F;
            is_last = (header[0] & 0x80) != 0;
            let block_size = u32::from_be_bytes([0, header[1], header[2], header[3]]);

            // Track block order for byte-identical writes
            self.original_block_order.push(block_type);

            let block_data_start = reader.stream_position().await?;

            // Validate block size — always enforce the limit regardless of
            // distrust_size to prevent uncapped allocations from crafted files
            if block_size > self.parse_options.max_block_size {
                let error = FLACError {
                    kind: FLACErrorKind::BlockSizeError,
                    position: Some(block_start_pos),
                    context: format!(
                        "Block size {} exceeds maximum {}",
                        block_size, self.parse_options.max_block_size
                    ),
                };
                self.parse_errors.push(error);

                // VORBIS_COMMENT block size errors are always fatal to prevent OOM
                if block_type == 4 || !self.parse_options.ignore_errors {
                    return Err(AudexError::InvalidData(format!(
                        "Block size {} exceeds maximum {}",
                        block_size, self.parse_options.max_block_size
                    )));
                }

                // Skip oversized block for non-critical types
                let safe_skip_size = min(block_size, self.parse_options.max_block_size);
                reader
                    .seek(SeekFrom::Current(safe_skip_size as i64))
                    .await?;
                continue;
            }

            // Parse block based on type
            let parse_result = match block_type {
                0 => self.parse_streaminfo_block_async(reader, block_size).await,
                1 => self.parse_padding_block_async(reader, block_size).await,
                2 => self.parse_application_block_async(reader, block_size).await,
                3 => {
                    // SEEKTABLE block - check for duplicates
                    if self.seektable.is_some() {
                        self.parse_errors.push(FLACError {
                            kind: FLACErrorKind::MultipleSeekTableBlocks,
                            position: Some(block_start_pos),
                            context: "> 1 SeekTable block found".to_string(),
                        });

                        if !self.parse_options.ignore_errors {
                            return Err(AudexError::InvalidData(
                                "> 1 SeekTable block found".to_string(),
                            ));
                        }

                        // Skip duplicate SeekTable block
                        reader.seek(SeekFrom::Current(block_size as i64)).await?;
                        Ok(())
                    } else {
                        self.parse_seektable_block_async(reader, block_size).await
                    }
                }
                4 => {
                    // Handle VORBIS_COMMENT block with duplicate detection
                    vorbis_comment_count += 1;
                    if vorbis_comment_count > 1 {
                        self.parse_errors.push(FLACError {
                            kind: FLACErrorKind::MultipleVorbisBlocks,
                            position: Some(block_start_pos),
                            context: format!(
                                "Found {} VORBIS_COMMENT blocks, using first",
                                vorbis_comment_count
                            ),
                        });

                        if !self.parse_options.ignore_errors {
                            return Err(AudexError::FLACVorbis);
                        }

                        // Skip duplicate Vorbis block
                        reader.seek(SeekFrom::Current(block_size as i64)).await?;
                        Ok(())
                    } else {
                        self.parse_vorbis_comment_block_async(reader, block_size)
                            .await
                    }
                }
                5 => {
                    // CUESHEET block - check for duplicates
                    if self.cuesheet.is_some() {
                        self.parse_errors.push(FLACError {
                            kind: FLACErrorKind::MultipleCueSheetBlocks,
                            position: Some(block_start_pos),
                            context: "> 1 CueSheet block found".to_string(),
                        });

                        if !self.parse_options.ignore_errors {
                            return Err(AudexError::InvalidData(
                                "> 1 CueSheet block found".to_string(),
                            ));
                        }

                        // Skip duplicate CueSheet block
                        reader.seek(SeekFrom::Current(block_size as i64)).await?;
                        Ok(())
                    } else {
                        self.parse_cuesheet_block_async(reader, block_size).await
                    }
                }
                6 => self.parse_picture_block_async(reader, block_size).await,
                _ => {
                    // Unknown block type - skip it
                    reader.seek(SeekFrom::Current(block_size as i64)).await?;
                    Ok(())
                }
            };

            // Handle parse errors with recovery logic
            if let Err(e) = parse_result {
                let error = FLACError {
                    kind: FLACErrorKind::CorruptedBlock,
                    position: Some(block_start_pos),
                    context: format!("Block type {} parse error: {}", block_type, e),
                };
                self.parse_errors.push(error);

                // Determine if error is fatal
                let is_fatal_error = if self.parse_options.ignore_errors {
                    block_type == 4 && self.is_fatal_vorbis_error(&e)
                } else {
                    block_type == 0 || (block_type == 4 && self.is_fatal_vorbis_error(&e))
                };

                if is_fatal_error {
                    return Err(e);
                }

                // Try to skip corrupted block and continue
                let current_pos = reader.stream_position().await?;
                let expected_pos = block_start_pos + 4 + block_size as u64;
                if current_pos != expected_pos {
                    reader.seek(SeekFrom::Start(expected_pos)).await?;
                }
            } else {
                // Store successfully parsed block data
                let current_pos = reader.stream_position().await?;
                let bytes_to_read = current_pos.checked_sub(block_data_start).ok_or_else(|| {
                    AudexError::InvalidData(format!(
                        "FLAC block position underflow: current {} < start {}",
                        current_pos, block_data_start
                    ))
                })? as usize;

                // For VorbisComment (4) and Picture (6) blocks: if the real
                // content size exceeds the 24-bit max, record the original
                // header size so we can write it back on save (distrust_size
                // round-trip).
                if (block_type == 4 || block_type == 6) && bytes_to_read > 0xFFFFFF {
                    self.original_overflow_sizes.insert(block_type, block_size);
                }

                reader.seek(SeekFrom::Start(block_data_start)).await?;
                let mut block_data = vec![0u8; bytes_to_read];
                reader.read_exact(&mut block_data).await?;

                self.metadata_blocks
                    .push(MetadataBlock::new(block_type, block_data));
            }
        }

        Ok(())
    }

    /// Parse STREAMINFO metadata block asynchronously.
    #[cfg(feature = "async")]
    async fn parse_streaminfo_block_async<R>(
        &mut self,
        reader: &mut TokioBufReader<R>,
        block_size: u32,
    ) -> Result<()>
    where
        R: tokio::io::AsyncRead + tokio::io::AsyncSeek + Unpin,
    {
        use tokio::io::AsyncReadExt;

        if block_size != 34 {
            return Err(AudexError::InvalidData(format!(
                "Invalid STREAMINFO size: {} (expected 34)",
                block_size
            )));
        }

        let mut data = [0u8; 34];
        reader.read_exact(&mut data).await?;
        self.info = FLACStreamInfo::from_bytes(&data)?;

        Ok(())
    }

    /// Parse PADDING metadata block asynchronously.
    #[cfg(feature = "async")]
    async fn parse_padding_block_async<R>(
        &mut self,
        reader: &mut TokioBufReader<R>,
        block_size: u32,
    ) -> Result<()>
    where
        R: tokio::io::AsyncRead + tokio::io::AsyncSeek + Unpin,
    {
        use tokio::io::AsyncSeekExt;

        // Record padding size without reading actual null bytes
        let padding = Padding::new(block_size as usize);
        self.padding_blocks.push(padding);
        reader.seek(SeekFrom::Current(block_size as i64)).await?;
        Ok(())
    }

    /// Parse APPLICATION metadata block asynchronously.
    #[cfg(feature = "async")]
    async fn parse_application_block_async<R>(
        &mut self,
        reader: &mut TokioBufReader<R>,
        block_size: u32,
    ) -> Result<()>
    where
        R: tokio::io::AsyncRead + tokio::io::AsyncSeek + Unpin,
    {
        use tokio::io::{AsyncReadExt, AsyncSeekExt};

        let safe_size = if self.parse_options.distrust_size {
            min(block_size, self.parse_options.max_block_size)
        } else {
            block_size
        };

        let mut data = vec![0u8; safe_size as usize];
        reader.read_exact(&mut data).await?;

        let application_block = ApplicationBlock::from_bytes(&data)?;
        self.application_blocks.push(application_block);

        // Skip any remaining bytes if truncated
        if block_size > safe_size {
            reader
                .seek(SeekFrom::Current((block_size - safe_size) as i64))
                .await?;
        }

        Ok(())
    }

    /// Parse SEEKTABLE metadata block asynchronously.
    #[cfg(feature = "async")]
    async fn parse_seektable_block_async<R>(
        &mut self,
        reader: &mut TokioBufReader<R>,
        block_size: u32,
    ) -> Result<()>
    where
        R: tokio::io::AsyncRead + tokio::io::AsyncSeek + Unpin,
    {
        use tokio::io::{AsyncReadExt, AsyncSeekExt};

        let safe_size = if self.parse_options.distrust_size {
            min(block_size, self.parse_options.max_block_size)
        } else {
            block_size
        };

        let mut data = vec![0u8; safe_size as usize];
        let bytes_read = reader.read(&mut data).await?;

        if bytes_read < safe_size as usize {
            return Err(AudexError::InvalidData(
                "Truncated SEEKTABLE block".to_string(),
            ));
        }

        data.truncate(bytes_read);

        // Use robust seek table parsing with reasonable limits
        let max_seekpoints = Some(10000);
        let seektable = SeekTable::from_bytes_with_options(&data, max_seekpoints)?;
        self.seektable = Some(seektable);

        // Skip any remaining bytes if truncated
        if block_size > safe_size {
            reader
                .seek(SeekFrom::Current((block_size - safe_size) as i64))
                .await?;
        }

        Ok(())
    }

    /// Parse VORBIS_COMMENT metadata block asynchronously.
    #[cfg(feature = "async")]
    async fn parse_vorbis_comment_block_async<R>(
        &mut self,
        reader: &mut TokioBufReader<R>,
        block_size: u32,
    ) -> Result<()>
    where
        R: tokio::io::AsyncRead + tokio::io::AsyncSeek + Unpin,
    {
        use tokio::io::{AsyncReadExt, AsyncSeekExt};

        let safe_size = if self.parse_options.distrust_size {
            min(block_size, self.parse_options.max_block_size)
        } else {
            block_size
        };

        let mut data = vec![0u8; safe_size as usize];
        reader.read_exact(&mut data).await?;

        // FLAC files don't use framing bit in Vorbis comments
        let comment = VCommentDict::from_bytes_with_options(
            &data,
            self.parse_options.vorbis_error_mode,
            false,
        )?;
        self.tags = Some(comment);

        // Skip any remaining bytes if block was larger
        if block_size > safe_size {
            reader
                .seek(SeekFrom::Current((block_size - safe_size) as i64))
                .await?;
        }

        Ok(())
    }

    /// Parse CUESHEET metadata block asynchronously.
    #[cfg(feature = "async")]
    async fn parse_cuesheet_block_async<R>(
        &mut self,
        reader: &mut TokioBufReader<R>,
        block_size: u32,
    ) -> Result<()>
    where
        R: tokio::io::AsyncRead + tokio::io::AsyncSeek + Unpin,
    {
        use tokio::io::{AsyncReadExt, AsyncSeekExt};

        let safe_size = if self.parse_options.distrust_size {
            min(block_size, self.parse_options.max_block_size)
        } else {
            block_size
        };

        let mut data = vec![0u8; safe_size as usize];
        let bytes_read = reader.read(&mut data).await?;

        if bytes_read < safe_size as usize {
            return Err(AudexError::InvalidData(
                "Truncated CUESHEET block".to_string(),
            ));
        }

        data.truncate(bytes_read);
        let cuesheet = CueSheet::from_bytes(&data)?;
        self.cuesheet = Some(cuesheet);

        // Skip any remaining bytes if truncated
        if block_size > safe_size {
            reader
                .seek(SeekFrom::Current((block_size - safe_size) as i64))
                .await?;
        }

        Ok(())
    }

    /// Parse PICTURE metadata block asynchronously.
    #[cfg(feature = "async")]
    async fn parse_picture_block_async<R>(
        &mut self,
        reader: &mut TokioBufReader<R>,
        block_size: u32,
    ) -> Result<()>
    where
        R: tokio::io::AsyncRead + tokio::io::AsyncSeek + Unpin,
    {
        use tokio::io::{AsyncReadExt, AsyncSeekExt};

        let safe_size = if self.parse_options.distrust_size {
            min(block_size, self.parse_options.max_block_size)
        } else {
            block_size
        };

        let mut data = vec![0u8; safe_size as usize];
        let bytes_read = reader.read(&mut data).await?;

        // Handle truncated data based on error settings
        if bytes_read < safe_size as usize {
            if !self.parse_options.ignore_errors {
                return Err(AudexError::InvalidData(
                    "Truncated PICTURE block".to_string(),
                ));
            }
            if bytes_read == 0 {
                return Ok(());
            }
        }

        data.truncate(bytes_read);

        // Use robust picture parsing with size limits
        let max_picture_size = Some(self.parse_options.max_block_size as usize);

        match Picture::from_bytes_with_options(&data, max_picture_size) {
            Ok(picture) => self.pictures.push(picture),
            Err(_) if self.parse_options.ignore_errors => {
                // Skip corrupted picture when ignore_errors is enabled
            }
            Err(e) => return Err(e),
        }

        // Skip any remaining bytes if truncated
        if block_size > safe_size && bytes_read == safe_size as usize {
            reader
                .seek(SeekFrom::Current((block_size - safe_size) as i64))
                .await?;
        }

        Ok(())
    }

    /// Save FLAC file with metadata changes asynchronously.
    ///
    /// Writes modified metadata back to the file using non-blocking I/O.
    /// Supports in-place updates when possible, or resizes the file if needed.
    ///
    /// # Arguments
    /// * `path` - Optional path to save to (defaults to original file path)
    /// * `_delete_id3` - Whether to remove ID3 tags (reserved for future use)
    /// * `padding_func` - Optional custom padding calculation function
    #[cfg(feature = "async")]
    pub async fn save_to_file_async<P: AsRef<Path>>(
        &mut self,
        path: Option<P>,
        _delete_id3: bool,
        padding_func: Option<PaddingFunction>,
    ) -> Result<()> {
        use tokio::io::{AsyncSeekExt, AsyncWriteExt};

        let file_path = match path {
            Some(p) => p.as_ref().to_path_buf(),
            None => std::path::PathBuf::from(&self.filename),
        };

        if !tokio::fs::try_exists(&file_path).await.unwrap_or(false) {
            return Err(AudexError::InvalidData("File does not exist".to_string()));
        }

        // Open file for read/write operations
        let mut file = TokioOpenOptions::new()
            .read(true)
            .write(true)
            .open(&file_path)
            .await?;

        // Find where audio data starts in the file
        let audio_offset = self.find_audio_offset_async(&mut file).await?;

        // Calculate available space for metadata
        let header_size = 4u64; // "fLaC" signature
        let available = audio_offset.checked_sub(header_size).ok_or_else(|| {
            AudexError::InvalidData(
                "audio offset is smaller than FLAC header size, file may be corrupt".to_string(),
            )
        })?;

        // Calculate content (audio data) size for padding calculation
        let file_size = file.seek(SeekFrom::End(0)).await?;
        let content_size = file_size.checked_sub(audio_offset).ok_or_else(|| {
            AudexError::InvalidData(
                "file size is smaller than audio offset, file may be truncated".to_string(),
            )
        })? as usize;

        // Determine if we need to regenerate metadata or can skip unchanged data
        let (new_metadata, data_size) = if padding_func.is_none()
            && !self.original_metadata.is_empty()
            && self.original_metadata.len() as u64 == available
        {
            // Try to regenerate and compare with original
            let regenerated =
                self.generate_metadata_blocks(None, available as usize, content_size)?;
            if regenerated == self.original_metadata {
                // No changes detected - skip write for efficiency
                self.dirty = false;
                return Ok(());
            }
            let size = regenerated.len() as u64;
            (regenerated, size)
        } else {
            let regenerated =
                self.generate_metadata_blocks(padding_func, available as usize, content_size)?;
            let size = regenerated.len() as u64;
            (regenerated, size)
        };

        // Resize file in-place if metadata size changed
        resize_bytes_async(&mut file, available, data_size, header_size).await?;

        // Write FLAC signature and new metadata
        file.seek(SeekFrom::Start(0)).await?;
        file.write_all(b"fLaC").await?;
        file.write_all(&new_metadata).await?;

        // Ensure data is written to disk
        file.flush().await?;

        // Update state after successful save
        self.original_metadata = new_metadata;
        self.dirty = false;

        Ok(())
    }

    /// Save changes to the FLAC file asynchronously using default settings.
    #[cfg(feature = "async")]
    pub async fn save_async(&mut self) -> Result<()> {
        self.save_to_file_async::<&str>(None, false, None).await
    }

    /// Clear all tags from the FLAC file asynchronously.
    ///
    /// Removes the Vorbis comment block and saves the file.
    #[cfg(feature = "async")]
    pub async fn clear_async(&mut self) -> Result<()> {
        if self.tags.is_some() {
            self.tags = None;
            self.dirty = true;
            self.save_async().await?;
        }
        Ok(())
    }

    /// Delete the FLAC file from disk asynchronously.
    #[cfg(feature = "async")]
    pub async fn delete_async(&mut self) -> Result<()> {
        if !self.filename.is_empty() {
            tokio::fs::remove_file(&self.filename).await?;
        }
        Ok(())
    }

    /// Find where audio data starts in the file asynchronously.
    ///
    /// Internal method that scans through metadata blocks to find audio offset.
    #[cfg(feature = "async")]
    async fn find_audio_offset_async(&self, file: &mut TokioFile) -> Result<u64> {
        use tokio::io::{AsyncReadExt, AsyncSeekExt};

        file.seek(SeekFrom::Start(0)).await?;

        // Check for ID3 tags first
        let mut signature = [0u8; 4];
        file.read_exact(&mut signature).await?;

        if &signature[..3] == b"ID3" {
            // Skip ID3v2 tag
            let mut id3_size_bytes = [0u8; 6];
            file.read_exact(&mut id3_size_bytes).await?;
            let id3_size = self.decode_id3_size(&id3_size_bytes[2..])?;
            file.seek(SeekFrom::Current(id3_size as i64)).await?;

            // Read FLAC signature after ID3
            file.read_exact(&mut signature).await?;
        }

        if &signature != b"fLaC" {
            return Err(AudexError::FLACNoHeader);
        }

        // Cap the number of metadata blocks to prevent crafted files from
        // spinning forever when the last-block flag is never set.
        const MAX_METADATA_BLOCKS: usize = 1024;
        let mut block_count = 0usize;

        // Scan through all metadata blocks to find audio start
        loop {
            block_count += 1;
            if block_count > MAX_METADATA_BLOCKS {
                return Err(AudexError::InvalidData(format!(
                    "Exceeded maximum metadata block count ({}) in audio offset search",
                    MAX_METADATA_BLOCKS
                )));
            }

            let mut header = [0u8; 4];
            file.read_exact(&mut header).await?;

            let is_last = (header[0] & 0x80) != 0;
            let block_type = header[0] & 0x7F;
            let block_size = u32::from_be_bytes([0, header[1], header[2], header[3]]) as u64;

            if block_type == 4 {
                // Vorbis comment: read actual content and validate every seek
                // against the real file size instead of trusting embedded lengths.
                Self::skip_vorbis_comment_content_async(file).await?;
            } else if block_type == 6 {
                // Picture: validate all internal lengths against the real file size.
                Self::skip_picture_content_async(file).await?;
            } else {
                file.seek(SeekFrom::Current(block_size as i64)).await?;
            }

            if is_last {
                break;
            }
        }

        Ok(file.stream_position().await?)
    }

    #[cfg(feature = "async")]
    async fn skip_vorbis_comment_content_async(file: &mut TokioFile) -> Result<()> {
        use tokio::io::{AsyncReadExt, AsyncSeekExt};

        let cur = file.stream_position().await?;
        let file_end = file.seek(SeekFrom::End(0)).await?;
        file.seek(SeekFrom::Start(cur)).await?;

        let mut len_buf = [0u8; 4];

        file.read_exact(&mut len_buf).await?;
        let vendor_len = u32::from_le_bytes(len_buf) as u64;
        if file.stream_position().await? + vendor_len > file_end {
            return Err(AudexError::InvalidData(
                "Vorbis vendor length exceeds file size".to_string(),
            ));
        }
        file.seek(SeekFrom::Current(vendor_len as i64)).await?;

        file.read_exact(&mut len_buf).await?;
        let count = u32::from_le_bytes(len_buf);
        if count > 100_000 {
            return Err(AudexError::InvalidData(format!(
                "Vorbis comment count {} too large",
                count
            )));
        }

        for _ in 0..count {
            file.read_exact(&mut len_buf).await?;
            let comment_len = u32::from_le_bytes(len_buf) as u64;
            if file.stream_position().await? + comment_len > file_end {
                return Err(AudexError::InvalidData(
                    "Vorbis comment length exceeds file size".to_string(),
                ));
            }
            file.seek(SeekFrom::Current(comment_len as i64)).await?;
        }

        Ok(())
    }

    #[cfg(feature = "async")]
    async fn skip_picture_content_async(file: &mut TokioFile) -> Result<()> {
        use tokio::io::{AsyncReadExt, AsyncSeekExt};

        let cur = file.stream_position().await?;
        let file_end = file.seek(SeekFrom::End(0)).await?;
        file.seek(SeekFrom::Start(cur)).await?;

        let mut buf4 = [0u8; 4];

        file.read_exact(&mut buf4).await?; // picture type

        file.read_exact(&mut buf4).await?;
        let mime_len = u32::from_be_bytes(buf4) as u64;
        if file.stream_position().await? + mime_len > file_end {
            return Err(AudexError::InvalidData(
                "Picture MIME length exceeds file size".to_string(),
            ));
        }
        file.seek(SeekFrom::Current(mime_len as i64)).await?;

        file.read_exact(&mut buf4).await?;
        let desc_len = u32::from_be_bytes(buf4) as u64;
        if file.stream_position().await? + desc_len > file_end {
            return Err(AudexError::InvalidData(
                "Picture description length exceeds file size".to_string(),
            ));
        }
        file.seek(SeekFrom::Current(desc_len as i64)).await?;

        if file.stream_position().await? + 16 > file_end {
            return Err(AudexError::InvalidData(
                "Picture dimensions exceed file size".to_string(),
            ));
        }
        file.seek(SeekFrom::Current(16)).await?;

        file.read_exact(&mut buf4).await?;
        let data_len = u32::from_be_bytes(buf4) as u64;
        if file.stream_position().await? + data_len > file_end {
            return Err(AudexError::InvalidData(
                "Picture data length exceeds file size".to_string(),
            ));
        }
        file.seek(SeekFrom::Current(data_len as i64)).await?;

        Ok(())
    }
}

impl Default for FLAC {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for Picture {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for SeekTable {
    fn default() -> Self {
        Self::new()
    }
}

impl Default for CueSheet {
    fn default() -> Self {
        Self::new()
    }
}

impl FileType for FLAC {
    type Tags = VCommentDict;
    type Info = FLACStreamInfo;

    fn format_id() -> &'static str {
        "FLAC"
    }

    fn load<P: AsRef<Path>>(path: P) -> Result<Self> {
        Self::from_file(path)
    }

    fn load_from_reader(reader: &mut dyn crate::ReadSeek) -> Result<Self> {
        debug_event!("parsing FLAC file from reader");
        let mut flac = Self::new();
        let mut reader = reader;
        flac.parse_flac_streaming(&mut reader)?;
        Ok(flac)
    }

    fn save(&mut self) -> Result<()> {
        debug_event!("saving FLAC metadata");
        self.save_to_file::<&str>(None, false, None)
    }

    fn save_to_writer(&mut self, writer: &mut dyn crate::ReadWriteSeek) -> Result<()> {
        self.save_to_writer_impl(writer, None)
    }

    fn clear(&mut self) -> Result<()> {
        if self.tags.is_some() {
            self.tags = None;
            self.dirty = true;
            self.save()?;
        }
        Ok(())
    }

    fn clear_writer(&mut self, writer: &mut dyn crate::ReadWriteSeek) -> Result<()> {
        if self.tags.is_some() {
            self.tags = None;
            self.dirty = true;
        }
        self.save_to_writer_impl(writer, None)
    }

    fn save_to_path(&mut self, path: &Path) -> Result<()> {
        self.save_to_file(Some(path), false, None)
    }

    /// Adds empty Vorbis comment block to the file.
    ///
    /// Creates a new empty tag structure if none exists. If tags already exist,
    /// returns an error (unless parse_options.ignore_errors is set).
    ///
    /// # Errors
    ///
    /// Returns `AudexError::FLACVorbis` if tags already exist and ignore_errors is false.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use audex::flac::FLAC;
    /// use audex::FileType;
    ///
    /// let mut flac = FLAC::load("song.flac")?;
    /// if flac.tags.is_none() {
    ///     flac.add_tags()?;
    /// }
    /// flac.set("title", vec!["My Song".to_string()])?;
    /// flac.save()?;
    /// # Ok::<(), audex::AudexError>(())
    /// ```
    fn add_tags(&mut self) -> Result<()> {
        if self.tags.is_some() && !self.parse_options.ignore_errors {
            return Err(AudexError::FLACVorbis);
        }
        // With ignore_errors, replace existing tags
        self.tags = Some(VCommentDict::with_framing(false));
        self.dirty = true;
        Ok(())
    }

    fn tags(&self) -> Option<&Self::Tags> {
        self.tags.as_ref()
    }

    fn tags_mut(&mut self) -> Option<&mut Self::Tags> {
        self.tags.as_mut()
    }

    fn info(&self) -> &Self::Info {
        &self.info
    }

    fn score(filename: &str, header: &[u8]) -> i32 {
        let mut score = 0;

        // Check for FLAC signature - can be directly at start or after ID3
        if header.len() >= 4 {
            if &header[0..4] == b"fLaC" {
                score += 10; // Direct FLAC signature
            } else if header.len() >= 10 && &header[0..3] == b"ID3" {
                // Check for FLAC signature after ID3 tag
                for i in 10..header.len().saturating_sub(4) {
                    if &header[i..i + 4] == b"fLaC" {
                        score += 10;
                        break;
                    }
                }
            }
        }

        // Check file extension
        if filename.to_lowercase().ends_with(".flac") {
            score += 3;
        }

        score
    }

    fn mime_types() -> &'static [&'static str] {
        &["audio/flac", "audio/x-flac", "application/x-flac"]
    }
}

/// FLAC audio stream information from the STREAMINFO metadata block.
///
/// This struct contains essential audio properties extracted from the mandatory
/// STREAMINFO block that appears at the beginning of every FLAC file. It provides
/// both basic playback information (sample rate, channels, bit depth) and technical
/// details (block sizes, frame sizes, MD5 signature).
///
/// # STREAMINFO Block
///
/// The STREAMINFO block is always present as the first metadata block in a FLAC file.
/// It contains the minimum information needed to decode the audio stream.
///
/// # Examples
///
/// ```no_run
/// use audex::flac::FLAC;
/// use audex::FileType;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     let flac = FLAC::load("song.flac")?;
///     let info = &flac.info;
///
///     // Basic audio properties
///     println!("Sample rate: {} Hz", info.sample_rate);
///     println!("Bit depth: {} bits", info.bits_per_sample);
///     println!("Channels: {}", info.channels);
///     println!("Total samples: {}", info.total_samples);
///
///     // Calculate duration
///     if let Some(duration) = info.length {
///         println!("Duration: {:.2} seconds", duration.as_secs_f64());
///     }
///
///     // Check if file has been decoded correctly (MD5 verification)
///     println!("MD5 signature: {}", hex::encode(&info.md5_signature));
///     Ok(())
/// }
/// ```
///
/// # Technical Details
///
/// FLAC uses variable block sizes for compression. The `min_blocksize` and `max_blocksize`
/// fields indicate the range of block sizes used in the file. Most FLAC files use a
/// constant block size of 4096 samples.
///
/// The MD5 signature is calculated over the unencoded audio data and can be used to
/// verify that the file has been decoded correctly.
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct FLACStreamInfo {
    /// Total audio duration, calculated from total_samples and sample_rate
    #[cfg_attr(
        feature = "serde",
        serde(with = "crate::serde_helpers::duration_as_secs_f64")
    )]
    pub length: Option<Duration>,

    /// Average bitrate in bits per second, if calculable
    ///
    /// This is an estimate based on file size and duration. FLAC uses variable
    /// bitrate compression, so the actual bitrate varies throughout the file.
    pub bitrate: Option<u32>,

    /// Sample rate in Hz (e.g., 44100, 48000, 96000)
    ///
    /// Valid range: 1 Hz to 655,350 Hz (though practical range is much narrower).
    /// Common values: 44100 (CD quality), 48000 (DAT/DVD), 96000 (high-resolution).
    pub sample_rate: u32,

    /// Number of audio channels (1 = mono, 2 = stereo, etc.)
    ///
    /// Valid range: 1 to 8 channels. FLAC supports up to 8 independent channels.
    pub channels: u16,

    /// Bits per sample (bit depth)
    ///
    /// Valid range: 1 to 32 bits per sample.
    /// Common values: 16 (CD quality), 24 (high-resolution), 32 (float or int).
    pub bits_per_sample: u16,

    /// Total number of audio samples in the stream
    ///
    /// To calculate duration: `duration = total_samples / sample_rate`
    /// A value of 0 means the total is unknown (not recommended but allowed).
    pub total_samples: u64,

    /// MD5 signature of the unencoded audio data (16 bytes)
    ///
    /// This signature is computed over the raw PCM audio data and can be used
    /// to verify that decoding was performed correctly. All zeros means the
    /// signature was not calculated.
    pub md5_signature: [u8; 16],

    /// Minimum block size in samples used in the stream
    ///
    /// Must be at least 16 and at most 65535. Most files use 4096.
    pub min_blocksize: u16,

    /// Maximum block size in samples used in the stream
    ///
    /// Must be at least 16 and at most 65535. For constant block size encoding,
    /// this equals `min_blocksize`. Most files use 4096.
    pub max_blocksize: u16,

    /// Minimum frame size in bytes used in the stream
    ///
    /// A value of 0 means the value is unknown. Useful for buffer allocation.
    pub min_framesize: u32,

    /// Maximum frame size in bytes used in the stream
    ///
    /// A value of 0 means the value is unknown. Useful for buffer allocation.
    pub max_framesize: u32,
}

impl StreamInfo for FLACStreamInfo {
    fn length(&self) -> Option<Duration> {
        self.length
    }

    fn bitrate(&self) -> Option<u32> {
        self.bitrate
    }

    fn sample_rate(&self) -> Option<u32> {
        Some(self.sample_rate)
    }

    fn channels(&self) -> Option<u16> {
        Some(self.channels)
    }

    fn bits_per_sample(&self) -> Option<u16> {
        Some(self.bits_per_sample)
    }
}

impl FLACStreamInfo {
    /// Parse StreamInfo from raw 34-byte STREAMINFO block data
    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        if data.len() != 34 {
            return Err(AudexError::InvalidData(format!(
                "STREAMINFO must be exactly 34 bytes, got {}",
                data.len()
            )));
        }

        let mut cursor = Cursor::new(data);

        // Parse STREAMINFO fields
        let min_blocksize = cursor.read_u16::<BigEndian>()?;
        let max_blocksize = cursor.read_u16::<BigEndian>()?;

        let min_framesize_bytes = [cursor.read_u8()?, cursor.read_u8()?, cursor.read_u8()?];
        let min_framesize = u32::from_be_bytes([
            0,
            min_framesize_bytes[0],
            min_framesize_bytes[1],
            min_framesize_bytes[2],
        ]);

        let max_framesize_bytes = [cursor.read_u8()?, cursor.read_u8()?, cursor.read_u8()?];
        let max_framesize = u32::from_be_bytes([
            0,
            max_framesize_bytes[0],
            max_framesize_bytes[1],
            max_framesize_bytes[2],
        ]);

        // Parse sample rate, channels, bits per sample, total samples (20 + 3 + 5 + 36 = 64 bits)
        let combined = cursor.read_u64::<BigEndian>()?;

        let sample_rate = ((combined >> 44) & 0xFFFFF) as u32; // 20 bits
        let channels = (((combined >> 41) & 0x07) as u16) + 1; // 3 bits, +1 because encoded as channels-1
        let bits_per_sample = (((combined >> 36) & 0x1F) as u16) + 1; // 5 bits, +1 because encoded as bps-1
        let total_samples = combined & 0xFFFFFFFFF; // 36 bits

        // MD5 signature (16 bytes)
        let mut md5_signature = [0u8; 16];
        cursor.read_exact(&mut md5_signature)?;

        if sample_rate == 0 {
            return Err(AudexError::InvalidData(
                "A sample rate value of 0 is invalid".to_string(),
            ));
        }

        // Calculate length and initial bitrate estimate
        let (length, bitrate) = if sample_rate > 0 && total_samples > 0 {
            let duration_secs = total_samples as f64 / sample_rate as f64;
            let len = Some(Duration::from_secs_f64(duration_secs));

            // Initial estimate from uncompressed rate; overwritten with accurate
            // bitrate from file size after loading
            let bits_per_second = sample_rate as u64 * channels as u64 * bits_per_sample as u64;
            // Saturate to u32::MAX instead of silently truncating
            let br = Some(u32::try_from(bits_per_second).unwrap_or(u32::MAX));
            (len, br)
        } else {
            (Some(Duration::from_secs(0)), Some(0))
        };

        Ok(Self {
            length,
            bitrate,
            sample_rate,
            channels,
            bits_per_sample,
            total_samples,
            md5_signature,
            min_blocksize,
            max_blocksize,
            min_framesize,
            max_framesize,
        })
    }

    /// Convert StreamInfo to bytes for writing
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        let mut buffer = Vec::with_capacity(34);
        let mut writer = Cursor::new(&mut buffer);

        // Min/max block size (2 bytes each)
        writer.write_u16::<BigEndian>(self.min_blocksize)?;
        writer.write_u16::<BigEndian>(self.max_blocksize)?;

        // Min/max frame size (3 bytes each)
        let min_frame_bytes = self.min_framesize.to_be_bytes();
        writer.write_all(&min_frame_bytes[1..])?;
        let max_frame_bytes = self.max_framesize.to_be_bytes();
        writer.write_all(&max_frame_bytes[1..])?;

        // Sample rate (20 bits), channels (3 bits), bits per sample (5 bits), total samples (36 bits)
        let combined = ((self.sample_rate as u64) << 44)
            | ((self.channels.saturating_sub(1) as u64) << 41)
            | ((self.bits_per_sample.saturating_sub(1) as u64) << 36)
            | (self.total_samples & 0xFFFFFFFFF);
        writer.write_u64::<BigEndian>(combined)?;

        // MD5 signature (16 bytes)
        writer.write_all(&self.md5_signature)?;

        Ok(buffer)
    }

    /// Write StreamInfo block to bytes (wrapper for compatibility with test API)
    pub fn write(&self) -> Result<Vec<u8>> {
        self.to_bytes()
    }
}

/// Robust file I/O wrapper for FLAC parsing.
///
/// Wraps a `Read + Seek` reader with position tracking and optional size
/// validation, providing better error messages when reads exceed expected
/// bounds. Used internally during FLAC metadata block parsing.
pub struct StrictReader<R: Read + Seek> {
    reader: R,
    position: u64,
    total_size: Option<u64>,
}

impl<R: Read + Seek> StrictReader<R> {
    pub fn new(mut reader: R) -> std::io::Result<Self> {
        // Get total size if possible
        let total_size = match reader.seek(SeekFrom::End(0)) {
            Ok(size) => {
                reader.seek(SeekFrom::Start(0))?;
                Some(size)
            }
            Err(_) => None,
        };

        Ok(Self {
            reader,
            position: 0,
            total_size,
        })
    }

    /// Read exact number of bytes with improved error messages
    pub fn read_exact(&mut self, buf: &mut [u8]) -> std::io::Result<()> {
        let bytes_to_read = buf.len();

        // Check if we have enough data remaining
        if let Some(total_size) = self.total_size {
            if self.position + bytes_to_read as u64 > total_size {
                return Err(std::io::Error::new(
                    ErrorKind::UnexpectedEof,
                    format!(
                        "Attempted to read {} bytes at position {}, but only {} bytes available",
                        bytes_to_read,
                        self.position,
                        total_size - self.position
                    ),
                ));
            }
        }

        match self.reader.read_exact(buf) {
            Ok(()) => {
                self.position += bytes_to_read as u64;
                Ok(())
            }
            Err(e) => {
                if e.kind() == ErrorKind::UnexpectedEof {
                    Err(std::io::Error::new(
                        ErrorKind::UnexpectedEof,
                        format!(
                            "Unexpected EOF at position {} while reading {} bytes: {}",
                            self.position, bytes_to_read, e
                        ),
                    ))
                } else {
                    Err(e)
                }
            }
        }
    }

    /// Seek to position with validation
    pub fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        match self.reader.seek(pos) {
            Ok(new_pos) => {
                self.position = new_pos;

                // Validate position is within bounds
                if let Some(total_size) = self.total_size {
                    if new_pos > total_size {
                        return Err(std::io::Error::new(
                            ErrorKind::InvalidInput,
                            format!("Seek position {} exceeds file size {}", new_pos, total_size),
                        ));
                    }
                }

                Ok(new_pos)
            }
            Err(e) => Err(e),
        }
    }

    /// Get current stream position
    pub fn stream_position(&self) -> std::io::Result<u64> {
        Ok(self.position)
    }

    /// Read bytes with partial read support and validation
    pub fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        match self.reader.read(buf) {
            Ok(bytes_read) => {
                self.position += bytes_read as u64;
                Ok(bytes_read)
            }
            Err(e) => Err(e),
        }
    }

    /// Check if more data is available
    pub fn has_data_remaining(&self) -> bool {
        if let Some(total_size) = self.total_size {
            self.position < total_size
        } else {
            true // Unknown size, assume data might be available
        }
    }
}

impl<R: Read + Seek> Read for StrictReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.read(buf)
    }
}

impl<R: Read + Seek> Seek for StrictReader<R> {
    fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
        self.seek(pos)
    }
}

/// A FLAC application block for preserving application-specific metadata.
///
/// Application blocks allow third-party tools to store proprietary data within
/// FLAC files without affecting playback. Each application block is identified
/// by a unique 4-byte ID registered with the FLAC project.
///
/// # Registered Application IDs
///
/// Some commonly used application IDs include:
///
/// | ID (ASCII) | Application                         |
/// |------------|-------------------------------------|
/// | `RIFF`     | RIFF-based audio information        |
/// | `aiff`     | AIFF audio metadata                 |
/// | `riff`     | RIFF INFO chunk                     |
/// | `seektable`| Seeking information                 |
///
/// # Size Limits
///
/// The data payload can be up to 16,777,211 bytes (2²⁴ - 1 minus the 4-byte ID).
/// The total block size including the ID must not exceed 16,777,215 bytes.
///
/// # Example
///
/// ```rust
/// use audex::flac::ApplicationBlock;
///
/// // Create an application block with a custom ID
/// let app_id = *b"TEST";
/// let custom_data = vec![0x01, 0x02, 0x03, 0x04];
/// let block = ApplicationBlock::new(app_id, custom_data);
///
/// assert_eq!(block.application_id, *b"TEST");
/// assert_eq!(block.data.len(), 4);
/// ```
///
/// # See Also
///
/// - [`MetadataBlock`] - Generic container for all metadata block types
/// - [FLAC Application ID Registry](https://xiph.org/flac/id.html) - Official list of registered IDs
#[derive(Debug, Clone)]
pub struct ApplicationBlock {
    /// The 4-byte application identifier.
    ///
    /// This should be a registered ID from the FLAC project or a unique identifier
    /// for custom applications. IDs are typically printable ASCII characters.
    pub application_id: [u8; 4],

    /// The raw binary data specific to the application.
    ///
    /// The format and interpretation of this data is entirely determined by
    /// the application identified by `application_id`. This library preserves
    /// the data verbatim during read/write operations.
    pub data: Vec<u8>,
}

impl ApplicationBlock {
    /// Create new Application block with ID and data
    pub fn new(application_id: [u8; 4], data: Vec<u8>) -> Self {
        Self {
            application_id,
            data,
        }
    }

    /// Parse Application block from raw block data
    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        if data.len() < 4 {
            return Err(AudexError::InvalidData(
                "Application block too short".to_string(),
            ));
        }

        let mut application_id = [0u8; 4];
        application_id.copy_from_slice(&data[0..4]);

        let app_data = data[4..].to_vec();

        Ok(Self {
            application_id,
            data: app_data,
        })
    }

    /// Convert Application block back to raw bytes for writing
    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        let mut buffer = Vec::with_capacity(4 + self.data.len());
        buffer.extend_from_slice(&self.application_id);
        buffer.extend_from_slice(&self.data);
        Ok(buffer)
    }

    /// Get application ID as string (if valid ASCII)
    pub fn application_id_str(&self) -> Option<String> {
        std::str::from_utf8(&self.application_id)
            .ok()
            .map(|s| s.to_string())
    }

    /// Get the total size of the Application block
    pub fn total_size(&self) -> usize {
        4 + self.data.len()
    }
}

/// A generic FLAC metadata block for storing arbitrary metadata.
///
/// FLAC files consist of a series of metadata blocks followed by audio frames.
/// This struct represents a single metadata block with its type identifier and
/// raw byte data, allowing preservation of unknown or application-specific blocks.
///
/// # Block Types
///
/// The FLAC specification defines the following metadata block types:
///
/// | Type | Name          | Description                                    |
/// |------|---------------|------------------------------------------------|
/// | 0    | STREAMINFO    | Audio stream information (required, first)     |
/// | 1    | PADDING       | Reserved space for future metadata expansion   |
/// | 2    | APPLICATION   | Application-specific data                      |
/// | 3    | SEEKTABLE     | Seek points for random access                  |
/// | 4    | VORBIS_COMMENT| Vorbis-style metadata tags                     |
/// | 5    | CUESHEET      | CD table of contents                           |
/// | 6    | PICTURE       | Embedded picture (album art, etc.)             |
/// | 7-126| Reserved      | Reserved for future use                        |
/// | 127  | Invalid       | Invalid, used to mark invalid blocks           |
///
/// # Size Limits
///
/// Metadata block sizes are encoded as 24-bit values, allowing a maximum size
/// of 16,777,215 bytes (approximately 16 MB) per block.
///
/// # Example
///
/// ```
/// use audex::flac::MetadataBlock;
///
/// // Create a custom metadata block
/// let block = MetadataBlock::new(2, vec![0x41, 0x50, 0x50, 0x4C]); // APPLICATION block
///
/// assert_eq!(block.block_type, 2);
/// ```
#[derive(Debug, Clone)]
pub struct MetadataBlock {
    /// The metadata block type identifier (0-127).
    ///
    /// See the Block Types table above for standard type definitions.
    pub block_type: u8,

    /// The raw byte data contained within this metadata block.
    ///
    /// The interpretation of this data depends on the `block_type`.
    pub data: Vec<u8>,

    /// If set, the 3-byte size written into the block header will be this
    /// value instead of `data.len()`. Used for round-tripping oversized
    /// VorbisComment / Picture blocks whose real size exceeds the 24-bit
    /// limit -- we preserve the original (wrong) header size from the file
    /// rather than refusing to save.
    pub override_header_size: Option<u32>,
}

impl MetadataBlock {
    pub fn new(block_type: u8, data: Vec<u8>) -> Self {
        Self {
            block_type,
            data,
            override_header_size: None,
        }
    }

    /// Write metadata block to writer with header
    pub fn write_to<W: Write>(&self, writer: &mut W, is_last: bool) -> Result<()> {
        // Block type occupies bits 1-7 of the header byte (0-126 valid).
        // Type 127 is reserved as invalid by the FLAC spec, and values
        // >= 128 would collide with the is-last flag in bit 0.
        if self.block_type >= 127 {
            return Err(AudexError::InvalidData(format!(
                "FLAC block type {} is out of valid range (0-126)",
                self.block_type
            )));
        }

        // Header byte (1 bit last flag + 7 bits block type)
        let header_byte = self.block_type | if is_last { 0x80 } else { 0x00 };
        writer.write_u8(header_byte)?;

        // Block size (24 bits).
        // If override_header_size is set, use that value (round-tripping an
        // already-oversized block). Otherwise enforce the spec limit.
        let size: u32 = if let Some(overridden) = self.override_header_size {
            overridden
        } else {
            let sz = self.data.len() as u64;
            if sz > 0xFFFFFF {
                return Err(AudexError::InvalidData(format!(
                    "Block too large: {} bytes (max: {} bytes)",
                    sz, 0xFFFFFF
                )));
            }
            sz as u32
        };

        let size_bytes = size.to_be_bytes();
        writer.write_all(&size_bytes[1..])?;

        // Block data - write in chunks for very large blocks
        if self.data.len() > 1024 * 1024 {
            // 1MB threshold
            const CHUNK_SIZE: usize = 64 * 1024; // 64KB chunks
            for chunk in self.data.chunks(CHUNK_SIZE) {
                writer.write_all(chunk)?;
            }
        } else {
            writer.write_all(&self.data)?;
        }

        Ok(())
    }
}

/// A seek point entry within a FLAC seek table.
///
/// Seek points enable fast random access to specific positions within a FLAC stream.
/// Each seek point maps a sample number to a byte offset in the audio data, allowing
/// decoders to jump directly to a specific position without scanning from the beginning.
///
/// # Structure
///
/// Each seek point occupies exactly 18 bytes in the FLAC file:
/// - 8 bytes: First sample number in the target frame
/// - 8 bytes: Byte offset from the first frame header
/// - 2 bytes: Number of samples in the target frame
///
/// # Placeholder Points
///
/// A seek point with `first_sample` set to `0xFFFFFFFFFFFFFFFF` is a placeholder.
/// Placeholders reserve space in the seek table for future use and should be
/// ignored by decoders. Use [`SeekPoint::is_placeholder()`] to check.
///
/// # Example
///
/// ```
/// use audex::flac::SeekPoint;
///
/// // Create a seek point at sample 44100 (1 second at 44.1kHz)
/// let point = SeekPoint::new(44100, 8192, 4096);
/// assert!(!point.is_placeholder());
///
/// // Create a placeholder for future use
/// let placeholder = SeekPoint::placeholder();
/// assert!(placeholder.is_placeholder());
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct SeekPoint {
    /// The sample number of the first sample in the target frame.
    ///
    /// For placeholder points, this value is `0xFFFFFFFFFFFFFFFF`.
    pub first_sample: u64,

    /// The byte offset from the first byte of the first frame header to the
    /// first byte of the target frame's header.
    pub byte_offset: u64,

    /// The number of samples in the target frame.
    pub num_samples: u16,
}

impl SeekPoint {
    const PLACEHOLDER_SAMPLE: u64 = 0xFFFFFFFFFFFFFFFF;

    pub fn new(first_sample: u64, byte_offset: u64, num_samples: u16) -> Self {
        Self {
            first_sample,
            byte_offset,
            num_samples,
        }
    }

    pub fn placeholder() -> Self {
        Self::new(Self::PLACEHOLDER_SAMPLE, 0, 0)
    }

    pub fn is_placeholder(&self) -> bool {
        self.first_sample == Self::PLACEHOLDER_SAMPLE
    }
}

/// A FLAC seek table containing indexed seek points for random access.
///
/// The seek table is an optional metadata block that enables fast seeking within
/// a FLAC stream. It contains an ordered list of [`SeekPoint`] entries, each mapping
/// a sample number to a byte offset in the audio data.
///
/// # Purpose
///
/// Without a seek table, seeking to a specific position in a FLAC file requires
/// scanning from the beginning or using binary search on frame headers. The seek
/// table provides pre-computed offsets for quick random access, which is especially
/// valuable for:
///
/// - Large audio files where scanning would be slow
/// - Streaming applications requiring immediate seeks
/// - Audio players with seek bar interfaces
///
/// # Structure
///
/// The seek table metadata block contains:
/// - A sequence of 18-byte seek point entries
/// - Points must be sorted in ascending order by sample number
/// - Placeholder points (sample number = `0xFFFFFFFFFFFFFFFF`) may be included
///   for future expansion
///
/// # Example
///
/// ```
/// use audex::flac::{SeekTable, SeekPoint};
///
/// let mut table = SeekTable::new();
///
/// // Add seek points at regular intervals (every second at 44.1kHz)
/// table.seekpoints.push(SeekPoint::new(0, 0, 4096));
/// table.seekpoints.push(SeekPoint::new(44100, 8192, 4096));
/// table.seekpoints.push(SeekPoint::new(88200, 16384, 4096));
///
/// assert_eq!(table.seekpoints.len(), 3);
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct SeekTable {
    /// The ordered list of seek points in this table.
    ///
    /// Seek points should be sorted by `first_sample` in ascending order.
    /// Placeholder points should appear at the end of the list.
    pub seekpoints: Vec<SeekPoint>,
}

impl SeekTable {
    pub fn new() -> Self {
        Self {
            seekpoints: Vec::new(),
        }
    }

    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        Self::from_bytes_with_options(data, None)
    }

    /// Parse seek table with optional limits for robustness
    pub fn from_bytes_with_options(data: &[u8], max_seekpoints: Option<usize>) -> Result<Self> {
        let mut cursor = Cursor::new(data);
        let mut seekpoints = Vec::new();

        // Each seekpoint is exactly 18 bytes
        let max_points = max_seekpoints.unwrap_or(100000); // Reasonable limit
        let expected_points = data.len() / 18;

        if expected_points > max_points {
            return Err(AudexError::InvalidData(format!(
                "Too many seek points: {} (max: {})",
                expected_points, max_points
            )));
        }

        while cursor.position() + 18 <= data.len() as u64 {
            let first_sample = cursor.read_u64::<BigEndian>()?;
            let byte_offset = cursor.read_u64::<BigEndian>()?;
            let num_samples = cursor.read_u16::<BigEndian>()?;

            seekpoints.push(SeekPoint::new(first_sample, byte_offset, num_samples));

            // Safety check
            if seekpoints.len() > max_points {
                break;
            }
        }

        Ok(Self { seekpoints })
    }

    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        let mut buffer = Vec::new();
        let mut writer = Cursor::new(&mut buffer);

        for seekpoint in &self.seekpoints {
            writer.write_u64::<BigEndian>(seekpoint.first_sample)?;
            writer.write_u64::<BigEndian>(seekpoint.byte_offset)?;
            writer.write_u16::<BigEndian>(seekpoint.num_samples)?;
        }

        Ok(buffer)
    }

    /// Write seek table to bytes (wrapper for compatibility with test API)
    pub fn write(&self) -> Result<Vec<u8>> {
        self.to_bytes()
    }
}

/// An index point within a FLAC cue sheet track.
///
/// Index points mark significant positions within a track, following the CD-DA
/// standard. Each index provides a sample offset within the containing track.
///
/// # CD-DA Standard
///
/// In the CD-DA specification:
/// - **Index 00**: Pre-gap or hidden track area before the main audio
/// - **Index 01**: Start of the main audio content (always present)
/// - **Index 02+**: Additional markers for live recordings, medleys, etc.
///
/// # Example
///
/// ```
/// use audex::flac::CueSheetTrackIndex;
///
/// // Index 01 at the track start (offset 0)
/// let main_start = CueSheetTrackIndex {
///     index_number: 1,
///     index_offset: 0,
/// };
///
/// // Index 02 at a specific position within the track
/// let marker = CueSheetTrackIndex {
///     index_number: 2,
///     index_offset: 441000, // 10 seconds at 44.1kHz
/// };
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct CueSheetTrackIndex {
    /// The index number (0-99 per CD-DA specification).
    ///
    /// - Index 0: Pre-gap area
    /// - Index 1: Start of main audio (required)
    /// - Index 2-99: Additional markers
    pub index_number: u8,

    /// Sample offset from the track start to this index point.
    ///
    /// For CD-DA compatibility, this should be a multiple of 588 samples
    /// (one CD frame = 588 samples at 44.1kHz).
    pub index_offset: u64,
}

/// A track entry within a FLAC cue sheet.
///
/// Each track represents an individual song or data segment on a CD, containing
/// the track's position, identification, audio characteristics, and index points.
///
/// # CD-DA Compliance
///
/// For CD-DA (Compact Disc Digital Audio) compatibility:
/// - Track numbers range from 1 to 99 (track 170 is reserved for lead-out)
/// - ISRC codes must be exactly 12 characters
/// - Track offsets should be multiples of 588 samples (one CD frame)
///
/// # Example
///
/// ```
/// use audex::flac::{CueSheetTrack, CueSheetTrackIndex};
///
/// let track = CueSheetTrack {
///     track_number: 1,
///     start_offset: 0,
///     isrc: String::from("USRC17607839"),
///     track_type: 0, // Audio track
///     pre_emphasis: false,
///     indexes: vec![
///         CueSheetTrackIndex { index_number: 1, index_offset: 0 },
///     ],
/// };
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct CueSheetTrack {
    /// Track number (1-99 for audio, 170 for lead-out).
    pub track_number: u8,

    /// Sample offset from the beginning of the FLAC audio stream to the
    /// first sample of this track.
    pub start_offset: u64,

    /// International Standard Recording Code (12 ASCII characters).
    ///
    /// For CD-DA, this should be exactly 12 characters. An empty string
    /// indicates no ISRC is available for this track.
    pub isrc: String,

    /// Track type flag.
    ///
    /// - `0`: Audio track (CD-DA)
    /// - `1`: Digital data track (CD-ROM)
    pub track_type: u8,

    /// Whether pre-emphasis is applied to this track.
    ///
    /// Pre-emphasis is a form of audio equalization used on some older CDs
    /// to reduce high-frequency noise. Modern recordings typically do not
    /// use pre-emphasis.
    pub pre_emphasis: bool,

    /// Index points within this track.
    ///
    /// At minimum, index 01 (track start) should be present. Index 00
    /// represents the pre-gap area before the main audio.
    pub indexes: Vec<CueSheetTrackIndex>,
}

/// A FLAC cue sheet for storing CD table of contents and track information.
///
/// The cue sheet metadata block stores information about the CD structure from
/// which the FLAC file was ripped, including track boundaries, ISRCs (International
/// Standard Recording Codes), and index points.
///
/// # CD-DA Compliance
///
/// For files ripped from audio CDs, the cue sheet maintains CD-DA compliance:
/// - Sample offsets must be multiples of 588 (one CD frame at 44.1kHz)
/// - Lead-in must be at least 88200 samples (2 seconds) for CD-DA
/// - Track numbers range from 1-99, with track 170 reserved for lead-out
///
/// # Usage
///
/// Cue sheets are useful for:
/// - Preserving CD track information when ripping entire albums to single files
/// - Enabling accurate track splitting from a single FLAC file
/// - Storing ISRCs for proper track identification
/// - Maintaining CD-TEXT information compatibility
///
/// # Example
///
/// ```
/// use audex::flac::{CueSheet, CueSheetTrack, CueSheetTrackIndex};
///
/// let mut cuesheet = CueSheet::new();
/// cuesheet.media_catalog_number = "0012345678901".to_string();
/// cuesheet.is_compact_disc = true;
///
/// // Add a track
/// let track = CueSheetTrack {
///     track_number: 1,
///     start_offset: 0,
///     isrc: String::from("USRC17607839"),
///     track_type: 0, // Audio track
///     pre_emphasis: false,
///     indexes: vec![CueSheetTrackIndex { index_number: 1, index_offset: 0 }],
/// };
/// cuesheet.tracks.push(track);
/// ```
///
/// # See Also
///
/// - [`CueSheetTrack`] - Individual track entries
/// - [`CueSheetTrackIndex`] - Index points within tracks
#[derive(Debug, Clone, PartialEq)]
pub struct CueSheet {
    /// The media catalog number from the CD (UPC/EAN barcode).
    ///
    /// Up to 128 characters. Empty string if not available.
    /// For CD-DA, this is typically a 13-digit UPC/EAN code.
    pub media_catalog_number: String,

    /// Number of lead-in samples.
    ///
    /// For CD-DA, this must be at least 88200 samples (2 seconds at 44.1kHz).
    /// The lead-in is the silent area at the beginning of the disc.
    pub lead_in_samples: u64,

    /// Whether this cue sheet corresponds to a Compact Disc.
    ///
    /// When `true`, certain CD-DA constraints are expected to be followed
    /// (sample offsets as multiples of 588, etc.).
    pub is_compact_disc: bool,

    /// The list of tracks in the cue sheet.
    ///
    /// Should include all audio tracks plus a lead-out track (track 170).
    pub tracks: Vec<CueSheetTrack>,
}

impl CueSheet {
    pub fn new() -> Self {
        Self {
            media_catalog_number: String::new(),
            lead_in_samples: 88200, // Default for CD-DA
            is_compact_disc: true,
            tracks: Vec::new(),
        }
    }

    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        let mut cursor = Cursor::new(data);

        // Read media catalog number (128 bytes, null-terminated)
        let mut mcn_bytes = [0u8; 128];
        cursor.read_exact(&mut mcn_bytes)?;
        let mcn_end = mcn_bytes.iter().position(|&x| x == 0).unwrap_or(128);
        let media_catalog_number = String::from_utf8_lossy(&mcn_bytes[..mcn_end]).into_owned();

        // Lead-in samples (8 bytes)
        let lead_in_samples = cursor.read_u64::<BigEndian>()?;

        // Flags (1 byte) + reserved (258 bytes)
        let flags = cursor.read_u8()?;
        let is_compact_disc = (flags & 0x80) != 0;
        cursor.seek(SeekFrom::Current(258))?; // Skip reserved bytes

        // Number of tracks (1 byte). The FLAC spec allows at most 100
        // tracks in a CueSheet block (including the lead-out track).
        let num_tracks = cursor.read_u8()?;
        const MAX_CUESHEET_TRACKS: u8 = 100;
        if num_tracks > MAX_CUESHEET_TRACKS {
            return Err(AudexError::InvalidData(format!(
                "CueSheet track count {} exceeds FLAC spec limit of {}",
                num_tracks, MAX_CUESHEET_TRACKS
            )));
        }
        let mut tracks = Vec::new();

        for _ in 0..num_tracks {
            // Track offset (8 bytes)
            let start_offset = cursor.read_u64::<BigEndian>()?;

            // Track number (1 byte)
            let track_number = cursor.read_u8()?;

            // ISRC (12 bytes)
            let mut isrc_bytes = [0u8; 12];
            cursor.read_exact(&mut isrc_bytes)?;
            let isrc_end = isrc_bytes.iter().position(|&x| x == 0).unwrap_or(12);
            let isrc = String::from_utf8_lossy(&isrc_bytes[..isrc_end]).into_owned();

            // Flags (1 byte)
            let track_flags = cursor.read_u8()?;
            let track_type = (track_flags >> 7) & 1;
            let pre_emphasis = (track_flags & 0x40) != 0;

            // Reserved (13 bytes)
            cursor.seek(SeekFrom::Current(13))?;

            // Number of indexes (1 byte)
            let num_indexes = cursor.read_u8()?;
            let mut indexes = Vec::new();

            for _ in 0..num_indexes {
                let index_offset = cursor.read_u64::<BigEndian>()?;
                let index_number = cursor.read_u8()?;
                cursor.seek(SeekFrom::Current(3))?; // Reserved

                indexes.push(CueSheetTrackIndex {
                    index_number,
                    index_offset,
                });
            }

            tracks.push(CueSheetTrack {
                track_number,
                start_offset,
                isrc,
                track_type,
                pre_emphasis,
                indexes,
            });
        }

        Ok(Self {
            media_catalog_number,
            lead_in_samples,
            is_compact_disc,
            tracks,
        })
    }

    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        let mut buffer = Vec::new();
        let mut writer = Cursor::new(&mut buffer);

        // Media catalog number (128 bytes, null-padded)
        let mut mcn_bytes = [0u8; 128];
        let mcn_copy_len = self.media_catalog_number.len().min(128);
        mcn_bytes[..mcn_copy_len]
            .copy_from_slice(&self.media_catalog_number.as_bytes()[..mcn_copy_len]);
        writer.write_all(&mcn_bytes)?;

        // Lead-in samples
        writer.write_u64::<BigEndian>(self.lead_in_samples)?;

        // Flags + reserved
        let flags = if self.is_compact_disc { 0x80 } else { 0x00 };
        writer.write_u8(flags)?;
        writer.write_all(&[0u8; 258])?; // Reserved bytes

        // Number of tracks (must fit in a single byte per the FLAC CueSheet format)
        let track_count = u8::try_from(self.tracks.len()).map_err(|_| {
            AudexError::InvalidData(format!(
                "CueSheet track count {} exceeds maximum of 255",
                self.tracks.len()
            ))
        })?;
        writer.write_u8(track_count)?;

        // Write tracks
        for track in &self.tracks {
            writer.write_u64::<BigEndian>(track.start_offset)?;
            writer.write_u8(track.track_number)?;

            // ISRC (12 bytes, null-padded)
            let mut isrc_bytes = [0u8; 12];
            let isrc_copy_len = track.isrc.len().min(12);
            isrc_bytes[..isrc_copy_len].copy_from_slice(&track.isrc.as_bytes()[..isrc_copy_len]);
            writer.write_all(&isrc_bytes)?;

            // Track flags
            let track_flags =
                (track.track_type << 7) | if track.pre_emphasis { 0x40 } else { 0x00 };
            writer.write_u8(track_flags)?;

            // Reserved
            writer.write_all(&[0u8; 13])?;

            // Number of indexes (must fit in a single byte per the FLAC CueSheet format)
            let index_count = u8::try_from(track.indexes.len()).map_err(|_| {
                AudexError::InvalidData(format!(
                    "CueSheet track index count {} exceeds maximum of 255",
                    track.indexes.len()
                ))
            })?;
            writer.write_u8(index_count)?;

            // Write indexes
            for index in &track.indexes {
                writer.write_u64::<BigEndian>(index.index_offset)?;
                writer.write_u8(index.index_number)?;
                writer.write_all(&[0u8; 3])?; // Reserved
            }
        }

        Ok(buffer)
    }

    /// Write cue sheet to bytes (wrapper for compatibility with test API)
    pub fn write(&self) -> Result<Vec<u8>> {
        self.to_bytes()
    }
}

/// A FLAC padding block for metadata alignment and future expansion.
///
/// Padding blocks reserve empty space within the metadata section of a FLAC file,
/// allowing future edits (such as adding tags or pictures) without rewriting the
/// entire file. When metadata changes, the padding can absorb size differences.
///
/// # Purpose
///
/// Padding is useful for:
/// - **In-place editing**: Modify tags without rewriting audio data
/// - **Future expansion**: Reserve space for additional metadata
/// - **Alignment**: Align audio data to sector boundaries for optimal I/O
///
/// # Structure
///
/// A padding block consists entirely of zero bytes. The content is never read
/// during playback—only the size matters for reserving space.
///
/// # Size Limits
///
/// Padding block size is limited to 16,777,215 bytes (2²⁴ - 1) like all FLAC
/// metadata blocks. For very large padding requirements, multiple padding blocks
/// can be used.
///
/// # Example
///
/// ```
/// use audex::flac::Padding;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     // Create 4KB of padding for future tag expansion
///     let padding = Padding::new(4096);
///     assert_eq!(padding.size, 4096);
///
///     // Serialize to bytes (all zeros)
///     let bytes = padding.to_bytes()?;
///     assert_eq!(bytes.len(), 4096);
///     assert!(bytes.iter().all(|&b| b == 0));
///     Ok(())
/// }
/// ```
///
/// # See Also
///
/// - [`FLAC::add_padding`] - Add padding to a FLAC file
/// - [`FLAC::total_padding_size`] - Get total padding across all blocks
/// - [`FLAC::optimize_padding`] - Consolidate fragmented padding
#[derive(Debug, Clone, PartialEq)]
pub struct Padding {
    /// The size of the padding block in bytes.
    ///
    /// This represents the number of null bytes reserved for future use.
    /// A size of 0 creates an empty padding block (valid but not useful).
    pub size: usize,
}

impl Padding {
    pub fn new(size: usize) -> Self {
        Self { size }
    }

    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        // Padding blocks should contain only null bytes
        // We don't need to validate the content, just store the size
        Ok(Self { size: data.len() })
    }

    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        // Padding blocks are filled with null bytes
        Ok(vec![0u8; self.size])
    }

    /// Write padding to bytes (wrapper for compatibility with test API)
    pub fn write(&self) -> Result<Vec<u8>> {
        self.to_bytes()
    }

    /// Write padding block efficiently for large sizes
    pub fn write_to<W: Write>(&self, writer: &mut W) -> Result<()> {
        // For very large padding blocks, write in chunks to avoid memory issues
        if self.size > 64 * 1024 {
            // 64KB threshold
            const CHUNK_SIZE: usize = 64 * 1024;
            let chunk = vec![0u8; CHUNK_SIZE];
            let full_chunks = self.size / CHUNK_SIZE;
            let remainder = self.size % CHUNK_SIZE;

            // Write full chunks
            for _ in 0..full_chunks {
                writer.write_all(&chunk)?;
            }

            // Write remainder
            if remainder > 0 {
                let remainder_chunk = vec![0u8; remainder];
                writer.write_all(&remainder_chunk)?;
            }
        } else {
            // Small padding blocks, write directly
            let padding_data = vec![0u8; self.size];
            writer.write_all(&padding_data)?;
        }

        Ok(())
    }
}

impl Default for Padding {
    fn default() -> Self {
        Self::new(0)
    }
}

/// FLAC picture metadata for embedded album art and other images.
///
/// The Picture struct represents embedded image data within a FLAC file,
/// following the FLAC METADATA_BLOCK_PICTURE format which is compatible with
/// ID3v2 APIC frame picture types.
///
/// # Picture Types
///
/// The `picture_type` field uses ID3v2 APIC picture type values:
///
/// | Type | Description                              |
/// |------|------------------------------------------|
/// | 0    | Other                                    |
/// | 1    | 32x32 pixel file icon (PNG only)         |
/// | 2    | Other file icon                          |
/// | 3    | Cover (front)                            |
/// | 4    | Cover (back)                             |
/// | 5    | Leaflet page                             |
/// | 6    | Media (e.g., CD label)                   |
/// | 7    | Lead artist/performer                    |
/// | 8    | Artist/performer                         |
/// | 9    | Conductor                                |
/// | 10   | Band/Orchestra                           |
/// | 11   | Composer                                 |
/// | 12   | Lyricist/text writer                     |
/// | 13   | Recording location                       |
/// | 14   | During recording                         |
/// | 15   | During performance                       |
/// | 16   | Movie/video screen capture               |
/// | 17   | A bright colored fish                    |
/// | 18   | Illustration                             |
/// | 19   | Band/artist logotype                     |
/// | 20   | Publisher/Studio logotype                |
///
/// # Size Limits
///
/// The total picture block size (metadata + image data) must not exceed
/// 16,777,215 bytes (2²⁴ - 1). For practical use, keep embedded images
/// under a few megabytes to avoid excessive file sizes.
///
/// # Supported Formats
///
/// While FLAC supports any image format, the following are most common:
/// - **JPEG** (`image/jpeg`): Best for photographs
/// - **PNG** (`image/png`): Best for graphics, required for 32x32 icons
/// - **GIF** (`image/gif`): For animated or indexed color images
///
/// # Example
///
/// ```no_run
/// use audex::flac::{FLAC, Picture};
/// use audex::FileType;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
///     // Create a front cover picture
///     let mut picture = Picture::new();
///     picture.picture_type = 3; // Front cover
///     picture.mime_type = "image/jpeg".to_string();
///     picture.description = "Album Cover".to_string();
///     picture.width = 500;
///     picture.height = 500;
///     picture.color_depth = 24;
///     picture.colors_used = 0; // Not indexed
///     picture.data = std::fs::read("cover.jpg")?;
///
///     // Add to FLAC file
///     let mut flac = FLAC::load("song.flac")?;
///     flac.add_picture(picture);
///     flac.save()?;
///     Ok(())
/// }
/// ```
///
/// # See Also
///
/// - [`FLAC::add_picture`] - Add a picture to a FLAC file
/// - [`FLAC::clear_pictures`] - Remove all pictures
#[derive(Debug, Clone, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Picture {
    /// The picture type following ID3v2 APIC conventions.
    ///
    /// Common values: 0 (Other), 3 (Front cover), 4 (Back cover).
    /// See the Picture Types table above for all values.
    pub picture_type: u32,

    /// The MIME type of the image (e.g., "image/jpeg", "image/png").
    ///
    /// This should accurately reflect the image format in `data`.
    pub mime_type: String,

    /// A human-readable description of the picture.
    ///
    /// Typically used for accessibility or to distinguish between multiple
    /// pictures of the same type (e.g., "Front Cover", "CD Label").
    pub description: String,

    /// Image width in pixels.
    pub width: u32,

    /// Image height in pixels.
    pub height: u32,

    /// Color depth in bits per pixel (e.g., 24 for RGB, 32 for RGBA).
    pub color_depth: u32,

    /// Number of colors in the palette for indexed images.
    ///
    /// Set to 0 for non-indexed (true color) images like JPEG.
    /// For GIF or paletted PNG, this is the number of colors in the palette.
    pub colors_used: u32,

    /// The raw image data in the format specified by `mime_type`.
    #[cfg_attr(
        feature = "serde",
        serde(with = "crate::serde_helpers::bytes_as_base64")
    )]
    pub data: Vec<u8>,
}

impl Picture {
    /// Maximum allowed size for picture data (16MB)
    pub const MAX_SIZE: usize = (1 << 24) - 1; // 2^24 - 1 = 16777215

    pub fn new() -> Self {
        Self {
            picture_type: 0,
            mime_type: String::new(),
            description: String::new(),
            width: 0,
            height: 0,
            color_depth: 0,
            colors_used: 0,
            data: Vec::new(),
        }
    }

    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        Self::from_bytes_with_options(data, None)
    }

    /// Parse picture from bytes with optional size limits for robustness
    pub fn from_bytes_with_options(data: &[u8], max_picture_size: Option<usize>) -> Result<Self> {
        let mut cursor = Cursor::new(data);

        // Picture type (4 bytes)
        let picture_type = cursor.read_u32::<BigEndian>()?;

        // MIME type length and string
        let mime_len = cursor.read_u32::<BigEndian>()? as usize;

        // Validate MIME type length
        if mime_len > 256 {
            // Reasonable limit for MIME types
            return Err(AudexError::InvalidData(format!(
                "MIME type too long: {} bytes",
                mime_len
            )));
        }

        let mut mime_bytes = vec![0u8; mime_len];
        cursor.read_exact(&mut mime_bytes)?;
        let mime_type = String::from_utf8(mime_bytes)
            .map_err(|e| AudexError::InvalidData(format!("Invalid MIME type: {}", e)))?;

        // Description length and string
        let desc_len = cursor.read_u32::<BigEndian>()? as usize;

        // Validate description length
        if desc_len > 65536 {
            // 64KB limit for descriptions
            return Err(AudexError::InvalidData(format!(
                "Description too long: {} bytes",
                desc_len
            )));
        }

        let mut desc_bytes = vec![0u8; desc_len];
        cursor.read_exact(&mut desc_bytes)?;
        let description = String::from_utf8(desc_bytes)
            .map_err(|e| AudexError::InvalidData(format!("Invalid description: {}", e)))?;

        // Image properties
        let width = cursor.read_u32::<BigEndian>()?;
        let height = cursor.read_u32::<BigEndian>()?;
        let color_depth = cursor.read_u32::<BigEndian>()?;
        let colors_used = cursor.read_u32::<BigEndian>()?;

        // Picture data
        let data_len = cursor.read_u32::<BigEndian>()? as usize;

        // Apply the format-specific limit if provided, otherwise fall back
        // to the library-wide image allocation ceiling
        let global_limit = crate::limits::ParseLimits::default().max_image_size as usize;
        let max_size = max_picture_size.unwrap_or(global_limit);
        if data_len > max_size {
            return Err(AudexError::InvalidData(format!(
                "Picture data too large: {} bytes (max: {} bytes)",
                data_len, max_size
            )));
        }

        // Check if we have enough data left
        let remaining = data.len() - cursor.position() as usize;
        if data_len > remaining {
            return Err(AudexError::InvalidData(format!(
                "Picture data truncated: expected {} bytes, have {} bytes",
                data_len, remaining
            )));
        }

        let mut picture_data = vec![0u8; data_len];
        cursor.read_exact(&mut picture_data)?;

        // Validate image dimensions are reasonable
        if width > 100000 || height > 100000 {
            return Err(AudexError::InvalidData(format!(
                "Image dimensions too large: {}x{}",
                width, height
            )));
        }

        Ok(Self {
            picture_type,
            mime_type,
            description,
            width,
            height,
            color_depth,
            colors_used,
            data: picture_data,
        })
    }

    /// Parse picture directly from a reader (field-by-field), ignoring any
    /// external block size. Used when distrust_size is enabled.
    pub fn from_reader<R: Read>(reader: &mut R, max_picture_size: Option<usize>) -> Result<Self> {
        let picture_type = reader.read_u32::<BigEndian>()?;

        let mime_len = reader.read_u32::<BigEndian>()? as usize;
        if mime_len > 256 {
            return Err(AudexError::InvalidData(format!(
                "MIME type too long: {} bytes",
                mime_len
            )));
        }
        let mut mime_bytes = vec![0u8; mime_len];
        reader.read_exact(&mut mime_bytes)?;
        let mime_type = String::from_utf8(mime_bytes)
            .map_err(|e| AudexError::InvalidData(format!("Invalid MIME type: {}", e)))?;

        let desc_len = reader.read_u32::<BigEndian>()? as usize;
        if desc_len > 65536 {
            return Err(AudexError::InvalidData(format!(
                "Description too long: {} bytes",
                desc_len
            )));
        }
        let mut desc_bytes = vec![0u8; desc_len];
        reader.read_exact(&mut desc_bytes)?;
        let description = String::from_utf8(desc_bytes)
            .map_err(|e| AudexError::InvalidData(format!("Invalid description: {}", e)))?;

        let width = reader.read_u32::<BigEndian>()?;
        let height = reader.read_u32::<BigEndian>()?;
        let color_depth = reader.read_u32::<BigEndian>()?;
        let colors_used = reader.read_u32::<BigEndian>()?;

        let data_len = reader.read_u32::<BigEndian>()? as usize;
        let global_limit = crate::limits::ParseLimits::default().max_image_size as usize;
        let max_size = max_picture_size.unwrap_or(global_limit);
        if data_len > max_size {
            return Err(AudexError::InvalidData(format!(
                "Picture data too large: {} bytes (max: {} bytes)",
                data_len, max_size
            )));
        }

        let mut data = vec![0u8; data_len];
        reader.read_exact(&mut data)?;

        Ok(Self {
            picture_type,
            mime_type,
            description,
            width,
            height,
            color_depth,
            colors_used,
            data,
        })
    }

    pub fn to_bytes(&self) -> Result<Vec<u8>> {
        let mut buffer = Vec::new();
        let mut writer = Cursor::new(&mut buffer);

        // Picture type
        writer.write_u32::<BigEndian>(self.picture_type)?;

        // MIME type
        let mime_bytes = self.mime_type.as_bytes();
        writer.write_u32::<BigEndian>(mime_bytes.len() as u32)?;
        writer.write_all(mime_bytes)?;

        // Description
        let desc_bytes = self.description.as_bytes();
        writer.write_u32::<BigEndian>(desc_bytes.len() as u32)?;
        writer.write_all(desc_bytes)?;

        // Image properties
        writer.write_u32::<BigEndian>(self.width)?;
        writer.write_u32::<BigEndian>(self.height)?;
        writer.write_u32::<BigEndian>(self.color_depth)?;
        writer.write_u32::<BigEndian>(self.colors_used)?;

        // Picture data
        writer.write_u32::<BigEndian>(self.data.len() as u32)?;
        writer.write_all(&self.data)?;

        Ok(buffer)
    }

    /// Serialize picture metadata to bytes
    ///
    /// This method converts the Picture struct to its binary representation.
    /// It serializes the picture metadata into the binary format used for METADATA_BLOCK_PICTURE
    /// in OGG/Opus files and FLAC picture metadata blocks.
    pub fn write(&self) -> Result<Vec<u8>> {
        self.to_bytes()
    }
}

/// Clear all tags from a FLAC file.
///
/// Args:
///     path: Path to the FLAC file
///
/// Raises:
///     AudexError on failure
pub fn clear<P: AsRef<Path>>(path: P) -> Result<()> {
    let mut flac = FLAC::load(path)?;
    flac.clear()
}