moosicbox_player 0.2.0

MoosicBox player package
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
//! Audio playback engine for `MoosicBox`.
//!
//! This crate provides the core playback functionality for the `MoosicBox` music player,
//! handling audio decoding, streaming, and playback control. It supports both local file
//! playback and remote streaming from various audio sources.
//!
//! # Features
//!
//! * Playback session management with [`Playback`] and [`PlaybackHandler`]
//! * Multiple audio formats (AAC, FLAC, MP3, Opus) via feature flags
//! * Audio streaming and buffering with configurable quality settings
//! * Retry logic for robust playback with [`PlaybackRetryOptions`]
//! * Volume control and seeking capabilities
//! * Support for both local and remote playback sources
//!
//! # Main Entry Points
//!
//! * [`PlaybackHandler`] - Manages playback operations for tracks and albums
//! * [`Player`] - Trait for implementing custom playback players
//! * [`Playback`] - Represents an active playback session
//! * [`PlayerError`] - Error types for player operations
//!
//! # Examples
//!
//! ```rust,no_run
//! # use moosicbox_player::{PlaybackHandler, Player};
//! # use moosicbox_music_models::{Track, PlaybackQuality};
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # struct MyPlayer;
//! # impl std::fmt::Debug for MyPlayer {
//! #     fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
//! #         write!(f, "MyPlayer")
//! #     }
//! # }
//! # #[async_trait::async_trait]
//! # impl Player for MyPlayer {
//! #     async fn trigger_play(&self, _seek: Option<f64>) -> Result<(), moosicbox_player::PlayerError> { Ok(()) }
//! #     async fn trigger_stop(&self) -> Result<(), moosicbox_player::PlayerError> { Ok(()) }
//! #     async fn trigger_seek(&self, _seek: f64) -> Result<(), moosicbox_player::PlayerError> { Ok(()) }
//! #     async fn trigger_pause(&self) -> Result<(), moosicbox_player::PlayerError> { Ok(()) }
//! #     async fn trigger_resume(&self) -> Result<(), moosicbox_player::PlayerError> { Ok(()) }
//! #     fn player_status(&self) -> Result<moosicbox_player::ApiPlaybackStatus, moosicbox_player::PlayerError> { unimplemented!() }
//! #     fn get_source(&self) -> &moosicbox_player::PlayerSource { unimplemented!() }
//! # }
//! # let player = MyPlayer;
//! # let session_id = 1;
//! # let profile = "default".to_string();
//! # let track = Track::default();
//! # let quality = PlaybackQuality::default();
//! // Create a playback handler with a custom player implementation
//! let mut handler = PlaybackHandler::new(player);
//!
//! // Play a track
//! handler.play_track(
//!     session_id,
//!     profile,
//!     track,
//!     None,           // seek position
//!     Some(0.8),      // volume
//!     quality,
//!     None,           // playback target
//!     None,           // retry options
//! ).await?;
//! # Ok(())
//! # }
//! ```

#![cfg_attr(feature = "fail-on-warnings", deny(warnings))]
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::multiple_crate_versions)]

use std::{
    collections::BTreeMap,
    fs::File,
    path::Path,
    sync::{Arc, LazyLock, RwLock},
};

use ::symphonia::core::{io::MediaSource, probe::Hint};
use async_trait::async_trait;
use atomic_float::AtomicF64;
use flume::SendError;
use futures::{Future, StreamExt as _, TryStreamExt as _};
use local_ip_address::local_ip;
use moosicbox_audio_decoder::media_sources::{
    bytestream_source::ByteStreamSource, remote_bytestream::RemoteByteStreamMediaSource,
};
use moosicbox_audio_output::AudioOutputFactory;
use moosicbox_json_utils::{ParseError, database::DatabaseFetchError};
use moosicbox_music_api::{MusicApi, models::TrackAudioQuality};
use moosicbox_music_models::{ApiSource, AudioFormat, PlaybackQuality, Track, id::Id};
use moosicbox_session::{
    get_session_playlist,
    models::{ApiSession, PlaybackTarget, Session, UpdateSession, UpdateSessionPlaylist},
};
use moosicbox_stream_utils::{
    remote_bytestream::RemoteByteStream, stalled_monitor::StalledReadMonitor,
};
use regex::Regex;
use serde::{Deserialize, Serialize};
use switchy_async::util::CancellationToken;
use switchy_database::profiles::LibraryDatabase;
use thiserror::Error;
use tokio_util::codec::{BytesCodec, FramedRead};

use crate::{
    signal_chain::{SignalChain, SignalChainError},
    symphonia::PlaybackError,
};

#[cfg(feature = "api")]
/// HTTP API endpoints for playback control.
///
/// This module provides `RESTful` API endpoints for controlling playback, including
/// play, pause, stop, seek, and status operations. It uses Actix-web for HTTP handling
/// and integrates with the core playback functionality.
pub mod api;

#[cfg(feature = "local")]
/// Local audio player implementation.
///
/// This module provides a local player implementation that uses the Symphonia decoder
/// for audio playback. It handles audio output, volume control, seeking, and playback
/// state management for local audio files and streams.
pub mod local;

/// Audio signal processing chain for encoding and decoding.
pub mod signal_chain;
/// Asynchronous audio file playback using Symphonia.
pub mod symphonia;
/// Synchronous audio decoding using Symphonia.
pub mod symphonia_unsync;
/// Volume control and mixing utilities.
pub mod volume_mixer;

/// Default retry options for seek operations.
///
/// Configures 10 attempts with 100ms delay between retries.
pub const DEFAULT_SEEK_RETRY_OPTIONS: PlaybackRetryOptions = PlaybackRetryOptions {
    max_attempts: 10,
    retry_delay: std::time::Duration::from_millis(100),
};

/// Default retry options for playback operations.
///
/// Configures 10 attempts with 500ms delay between retries.
pub const DEFAULT_PLAYBACK_RETRY_OPTIONS: PlaybackRetryOptions = PlaybackRetryOptions {
    max_attempts: 10,
    retry_delay: std::time::Duration::from_millis(500),
};

/// Global HTTP client for making requests.
pub static CLIENT: LazyLock<switchy_http::Client> = LazyLock::new(switchy_http::Client::new);

/// Errors that can occur during player operations.
#[derive(Debug, Error)]
pub enum PlayerError {
    #[error(transparent)]
    Send(#[from] SendError<()>),
    #[error(transparent)]
    Http(#[from] switchy_http::Error),
    #[error(transparent)]
    Parse(#[from] ParseError),
    #[error(transparent)]
    DatabaseFetch(#[from] DatabaseFetchError),
    #[error(transparent)]
    Join(#[from] switchy_async::task::JoinError),
    #[error(transparent)]
    Acquire(#[from] switchy_async::sync::AcquireError),
    #[error(transparent)]
    IO(#[from] std::io::Error),
    #[error("Format not supported: {0:?}")]
    UnsupportedFormat(AudioFormat),
    #[error(transparent)]
    PlaybackError(#[from] PlaybackError),
    #[error("Track fetch failed: {0}")]
    TrackFetchFailed(String),
    #[error("Album fetch failed: {0}")]
    AlbumFetchFailed(Id),
    #[error("Track not found: {0}")]
    TrackNotFound(Id),
    #[error("Track not locally stored: {0}")]
    TrackNotLocal(Id),
    #[error("Failed to seek: {0}")]
    Seek(String),
    #[error("No players playing")]
    NoPlayersPlaying,
    #[error("Position out of bounds: {0}")]
    PositionOutOfBounds(u16),
    #[error("No audio outputs")]
    NoAudioOutputs,
    #[error("Playback not playing: {0}")]
    PlaybackNotPlaying(u64),
    #[error("Playback already playing: {0}")]
    PlaybackAlreadyPlaying(u64),
    #[error("Invalid Playback Type")]
    InvalidPlaybackType,
    #[error("Invalid state")]
    InvalidState,
    #[error("Invalid source")]
    InvalidSource,
    #[error("Playback retry requested")]
    RetryRequested,
    #[error("Playback cancelled")]
    Cancelled,
    #[error("Invalid session with id {session_id}: {message}")]
    InvalidSession { session_id: u64, message: String },
    #[error("Missing session ID")]
    MissingSessionId,
    #[error("Missing profile")]
    MissingProfile,
    #[error("Audio output error: {0}")]
    AudioOutput(#[from] moosicbox_audio_output::AudioError),
}

impl std::fmt::Debug for PlayableTrack {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PlayableTrack")
            .field("track_id", &self.track_id)
            .field("source", &"{{source}}")
            .finish_non_exhaustive()
    }
}

/// Represents an active playback session.
#[derive(Debug, Clone)]
pub struct Playback {
    /// Unique identifier for this playback session
    pub id: u64,
    /// Session ID this playback belongs to
    pub session_id: u64,
    /// Profile name for this playback
    pub profile: String,
    /// List of tracks in the playback queue
    pub tracks: Vec<Track>,
    /// Whether playback is currently active
    pub playing: bool,
    /// Current position in the track list
    pub position: u16,
    /// Audio quality settings for playback
    pub quality: PlaybackQuality,
    /// Current playback progress in seconds
    pub progress: f64,
    /// Playback volume (0.0 to 1.0)
    pub volume: Arc<AtomicF64>,
    /// Target device or zone for playback
    pub playback_target: Option<PlaybackTarget>,
    /// Cancellation token for stopping playback
    pub abort: CancellationToken,
}

impl Playback {
    /// Creates a new playback session.
    #[must_use]
    pub fn new(
        tracks: Vec<Track>,
        position: Option<u16>,
        volume: AtomicF64,
        quality: PlaybackQuality,
        session_id: u64,
        profile: String,
        playback_target: Option<PlaybackTarget>,
    ) -> Self {
        Self {
            id: switchy_random::rng().next_u64(),
            session_id,
            profile,
            tracks,
            playing: false,
            position: position.unwrap_or_default(),
            quality,
            progress: 0.0,
            volume: Arc::new(volume),
            playback_target,
            abort: CancellationToken::new(),
        }
    }
}

/// API representation of a playback session.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct ApiPlayback {
    /// IDs of tracks in the playback queue
    pub track_ids: Vec<String>,
    /// Whether playback is currently active
    pub playing: bool,
    /// Current position in the track list
    pub position: u16,
    /// Current seek position in seconds
    pub seek: f64,
}

impl From<Playback> for ApiPlayback {
    fn from(value: Playback) -> Self {
        Self {
            track_ids: value.tracks.iter().map(|t| t.id.to_string()).collect(),
            playing: value.playing,
            position: value.position,
            seek: value.progress,
        }
    }
}

/// API representation of playback status.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct ApiPlaybackStatus {
    /// Currently active playback session, if any
    pub active_playbacks: Option<ApiPlayback>,
}

/// Status response for playback operations.
#[derive(Serialize, Debug, Clone, Copy)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "openapi", derive(utoipa::ToSchema))]
pub struct PlaybackStatus {
    /// Whether the operation succeeded
    pub success: bool,
}

/// Constructs the URL for streaming a track.
///
/// This function builds the complete URL for accessing a track's audio stream,
/// including query parameters for format, quality, and authentication.
///
/// # Panics
///
/// * If the `SERVICE_PORT` `RwLock` is poisoned
///
/// # Errors
///
/// * If an HTTP request fails
/// * If failed to fetch the track
#[allow(clippy::too_many_lines, clippy::unused_async)]
pub async fn get_track_url(
    track_id: &Id,
    api_source: &ApiSource,
    player_source: &PlayerSource,
    format: PlaybackQuality,
    quality: TrackAudioQuality,
    use_local_network_ip: bool,
) -> Result<(String, Option<BTreeMap<String, String>>), PlayerError> {
    let (host, query, headers) = match player_source {
        PlayerSource::Remote {
            host,
            query,
            headers,
        } => {
            static LOCALHOST: LazyLock<Regex> =
                LazyLock::new(|| Regex::new(r"^http://localhost[:/].*?").unwrap());

            let host = if use_local_network_ip && LOCALHOST.is_match(host) {
                host.replacen(
                    "localhost",
                    &local_ip().map_or_else(
                        |e| {
                            log::warn!("Failed to get local ip address: {e:?}");
                            "127.0.0.1".to_string()
                        },
                        |x| x.to_string(),
                    ),
                    1,
                )
            } else {
                host.clone()
            };
            (host, query, headers.to_owned())
        }
        PlayerSource::Local => {
            let ip = if use_local_network_ip {
                local_ip().map_or_else(
                    |e| {
                        log::warn!("Failed to get local ip address: {e:?}");
                        "127.0.0.1".to_string()
                    },
                    |x| x.to_string(),
                )
            } else {
                "127.0.0.1".to_string()
            };
            (
                format!(
                    "http://{ip}:{}",
                    SERVICE_PORT
                        .read()
                        .unwrap()
                        .expect("Missing SERVICE_PORT value")
                ),
                &None,
                None,
            )
        }
    };

    let query_params = {
        let mut serializer = url::form_urlencoded::Serializer::new(String::new());

        if let Some(query) = query {
            for (key, value) in query {
                serializer.append_pair(key, value);
            }
        }

        serializer
            .append_pair("trackId", &track_id.to_string())
            .append_pair("quality", quality.as_ref());

        if let Some(profile) = headers
            .as_ref()
            .and_then(|x| x.get("moosicbox-profile").cloned())
        {
            serializer.append_pair("moosicboxProfile", &profile);
        }

        if format.format != AudioFormat::Source {
            serializer.append_pair("format", format.format.as_ref());
        }
        if !api_source.is_library() {
            serializer.append_pair("source", api_source.as_ref());
        }

        serializer.finish()
    };

    let query_string = format!("?{query_params}");

    Ok((format!("{host}/files/track{query_string}"), headers))
}

/// Retrieves the playlist ID associated with a session ID.
///
/// # Errors
///
/// * If the session playlist is missing
#[cfg_attr(feature = "profiling", profiling::function)]
pub async fn get_session_playlist_id_from_session_id(
    db: &LibraryDatabase,
    session_id: Option<u64>,
) -> Result<Option<u64>, PlayerError> {
    Ok(if let Some(session_id) = session_id {
        Some(
            get_session_playlist(db, session_id)
                .await?
                .ok_or(PlayerError::DatabaseFetch(
                    DatabaseFetchError::InvalidRequest,
                ))?
                .id,
        )
    } else {
        None
    })
}

/// A track ready for playback with its media source.
///
/// This struct wraps a track identifier along with the media source for
/// reading audio data and format hints for the decoder.
pub struct PlayableTrack {
    /// ID of the track
    pub track_id: Id,
    /// Media source for reading audio data
    pub source: Box<dyn MediaSource>,
    /// Format hint for the decoder
    pub hint: Hint,
}

/// Specifies the type of playback method to use.
#[derive(Copy, Clone, Default, Deserialize, Serialize, Debug)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum PlaybackType {
    /// Play from local file on disk
    File,
    /// Stream from remote source
    Stream,
    /// Use default playback method based on source
    #[default]
    Default,
}

/// Configuration for retry behavior during playback operations.
///
/// Controls how many times an operation will be retried on failure
/// and the delay between retry attempts.
#[derive(Copy, Clone)]
pub struct PlaybackRetryOptions {
    /// Maximum number of retry attempts before giving up
    pub max_attempts: u32,
    /// Duration to wait between retry attempts
    pub retry_delay: std::time::Duration,
}

/// Identifies the source of playback.
#[derive(Debug, Clone)]
pub enum PlayerSource {
    /// Local playback using the service port
    Local,
    /// Remote playback from a specified host
    Remote {
        /// Remote host URL
        host: String,
        /// Optional query parameters
        query: Option<BTreeMap<String, String>>,
        /// Optional HTTP headers
        headers: Option<BTreeMap<String, String>>,
    },
}

/// Manages playback operations for a player.
#[derive(Debug, Clone)]
pub struct PlaybackHandler {
    /// Unique identifier for this handler
    pub id: u64,
    /// Current playback session state
    pub playback: Arc<std::sync::RwLock<Option<Playback>>>,
    /// Audio output factory for creating audio streams
    pub output: Option<Arc<std::sync::Mutex<AudioOutputFactory>>>,
    /// The underlying player implementation
    pub player: Arc<Box<dyn Player + Sync>>,
}

#[cfg_attr(feature = "profiling", profiling::all_functions)]
impl PlaybackHandler {
    /// Creates a new playback handler with the given player.
    #[must_use]
    pub fn new(player: impl Player + Sync + 'static) -> Self {
        Self::new_boxed(Box::new(player))
    }

    /// Creates a new playback handler with a boxed player.
    #[must_use]
    pub fn new_boxed(player: Box<dyn Player + Sync>) -> Self {
        let playback = Arc::new(std::sync::RwLock::new(None));
        let output = None;

        Self {
            id: switchy_random::rng().next_u64(),
            playback,
            output,
            player: Arc::new(player),
        }
    }

    /// Sets the playback state for this handler.
    #[must_use]
    pub fn with_playback(mut self, playback: Arc<std::sync::RwLock<Option<Playback>>>) -> Self {
        self.playback = playback;
        self
    }

    /// Sets the audio output factory for this handler.
    #[must_use]
    pub fn with_output(
        mut self,
        output: Option<Arc<std::sync::Mutex<AudioOutputFactory>>>,
    ) -> Self {
        self.output = output;
        self
    }
}

impl PlaybackHandler {
    /// Initializes the playback handler from an API session.
    ///
    /// This updates the playback state to match the provided API session configuration,
    /// including tracks, position, volume, and playback target settings.
    ///
    /// # Errors
    ///
    /// * If failed to update the playback from the session
    pub async fn init_from_api_session(
        &mut self,
        profile: String,
        session: ApiSession,
    ) -> Result<(), PlayerError> {
        let session_id = session.session_id;
        if let Err(err) = self
            .update_playback(
                false,
                None,
                None,
                Some(session.playing),
                session.position,
                session.seek,
                session.volume,
                Some(
                    session
                        .playlist
                        .tracks
                        .into_iter()
                        .map(Into::into)
                        .collect::<Vec<_>>(),
                ),
                None,
                Some(session.session_id),
                Some(profile),
                session.playback_target,
                true,
                None,
            )
            .await
        {
            return Err(PlayerError::InvalidSession {
                session_id,
                message: format!("Failed to update playback: {err:?}"),
            });
        }

        Ok(())
    }

    /// Initializes the playback handler from a database session.
    ///
    /// This updates the playback state to match the provided session from the database,
    /// applying any initialization updates specified in the `UpdateSession` parameter.
    ///
    /// # Errors
    ///
    /// * If failed to update the playback from the session
    pub async fn init_from_session(
        &mut self,
        profile: String,
        session: Session,
        init: &UpdateSession,
    ) -> Result<(), PlayerError> {
        moosicbox_logging::debug_or_trace!(
            (
                "init_from_session: Initializing player from session_id={}",
                session.id
            ),
            (
                "init_from_session: Initializing player from session_id={} init={init:?}",
                session.id
            )
        );
        let session_id = init.session_id;
        if let Err(err) = self
            .update_playback(
                false,
                None,
                None,
                init.playing.or(Some(session.playing)),
                init.position.or(session.position),
                init.seek,
                init.volume.or(session.volume),
                Some(
                    session
                        .playlist
                        .tracks
                        .into_iter()
                        .map(Into::into)
                        .collect::<Vec<_>>(),
                ),
                None,
                Some(session.id),
                Some(profile),
                session.playback_target,
                true,
                None,
            )
            .await
        {
            return Err(PlayerError::InvalidSession {
                session_id,
                message: format!("Failed to update playback: {err:?}"),
            });
        }

        Ok(())
    }

    /// Plays all tracks from an album.
    ///
    /// Fetches all tracks from the specified album via the music API and begins playback,
    /// optionally starting at a specific track position with seek and volume settings.
    ///
    /// # Errors
    ///
    /// * If failed to fetch the album tracks
    /// * If failed to play the tracks
    #[allow(clippy::too_many_arguments)]
    pub async fn play_album(
        &mut self,
        api: &dyn MusicApi,
        session_id: u64,
        profile: String,
        album_id: &Id,
        position: Option<u16>,
        seek: Option<f64>,
        volume: Option<f64>,
        quality: PlaybackQuality,
        playback_target: Option<PlaybackTarget>,
        retry_options: Option<PlaybackRetryOptions>,
    ) -> Result<(), PlayerError> {
        let tracks = {
            api.album_tracks(album_id, None, None, None, None)
                .await
                .map_err(|e| {
                    log::error!("Failed to fetch album tracks: {e:?}");
                    PlayerError::AlbumFetchFailed(album_id.to_owned())
                })?
                .with_rest_of_items_in_batches()
                .await
                .map_err(|e| {
                    log::error!("Failed to fetch album tracks: {e:?}");
                    PlayerError::AlbumFetchFailed(album_id.to_owned())
                })?
        };

        self.play_tracks(
            session_id,
            profile,
            tracks,
            position,
            seek,
            volume,
            quality,
            playback_target,
            retry_options,
        )
        .await
    }

    /// Plays a single track.
    ///
    /// Begins playback of the specified track with optional seek position and volume settings.
    ///
    /// # Errors
    ///
    /// * If failed to play the track
    #[allow(clippy::too_many_arguments)]
    pub async fn play_track(
        &mut self,
        session_id: u64,
        profile: String,
        track: Track,
        seek: Option<f64>,
        volume: Option<f64>,
        quality: PlaybackQuality,
        playback_target: Option<PlaybackTarget>,
        retry_options: Option<PlaybackRetryOptions>,
    ) -> Result<(), PlayerError> {
        self.play_tracks(
            session_id,
            profile,
            vec![track],
            None,
            seek,
            volume,
            quality,
            playback_target,
            retry_options,
        )
        .await
    }

    /// Plays multiple tracks in sequence.
    ///
    /// Begins playback of the specified tracks with optional starting position,
    /// seek offset, and volume settings. If a playback is already active, it will
    /// be stopped before starting the new one.
    ///
    /// # Panics
    ///
    /// * If the `playback` `RwLock` is poisoned
    ///
    /// # Errors
    ///
    /// * If failed to play the tracks
    /// * If failed to stop an existing playback
    #[allow(clippy::too_many_arguments)]
    pub async fn play_tracks(
        &mut self,
        session_id: u64,
        profile: String,
        tracks: Vec<Track>,
        position: Option<u16>,
        seek: Option<f64>,
        volume: Option<f64>,
        quality: PlaybackQuality,
        playback_target: Option<PlaybackTarget>,
        retry_options: Option<PlaybackRetryOptions>,
    ) -> Result<(), PlayerError> {
        let playback = { self.playback.read().unwrap().clone() };

        if let Some(playback) = playback {
            log::debug!("Stopping existing playback {}", playback.id);
            self.stop(retry_options).await?;
        }

        {
            let playback = Playback::new(
                tracks,
                position,
                AtomicF64::new(volume.unwrap_or(1.0)),
                quality,
                session_id,
                profile,
                playback_target,
            );

            self.playback.write().unwrap().replace(playback);
        }

        self.play_playback(seek, retry_options).await
    }

    /// Starts playback for the current playback session.
    ///
    /// This internal method initiates playback of all tracks in the session's playlist,
    /// automatically advancing through tracks until completion or cancellation.
    ///
    /// # Panics
    ///
    /// * If the `playback` `RwLock` is poisoned
    ///
    /// # Errors
    ///
    /// * If failed to play the existing playback
    pub async fn play_playback(
        &mut self,
        seek: Option<f64>,
        retry_options: Option<PlaybackRetryOptions>,
    ) -> Result<(), PlayerError> {
        self.player.before_play_playback(seek).await?;

        let (playback, old) = {
            let mut binding = self.playback.write().unwrap();
            let playback = binding.as_mut().ok_or(PlayerError::NoPlayersPlaying)?;
            log::info!("play_playback: playback={playback:?}");

            if playback.tracks.is_empty() {
                log::debug!("No tracks to play for {playback:?}");
                return Ok(());
            }

            let old = playback.clone();

            playback.playing = true;
            let playback = playback.clone();
            drop(binding);

            (playback, old)
        };

        trigger_playback_event(&playback, &old);

        log::debug!(
            "Playing playback: position={} tracks={:?}",
            playback.position,
            playback.tracks.iter().map(|t| &t.id).collect::<Vec<_>>()
        );

        let mut player = self.clone();

        switchy_async::runtime::Handle::current().spawn_with_name(
            "player: Play playback",
            async move {
                let mut seek = seek;

                let mut playback = player
                    .playback
                    .read()
                    .unwrap()
                    .clone()
                    .ok_or(PlayerError::NoPlayersPlaying)?;

                #[allow(clippy::redundant_pub_crate)]
                while playback.playing && (playback.position as usize) < playback.tracks.len() {
                    let track_or_id = &playback.tracks[playback.position as usize];
                    log::debug!("play_playback: track={track_or_id:?} seek={seek:?}");

                    let seek = if seek.is_some() { seek.take() } else { None };

                    log::debug!("player cancelled={}", playback.abort.is_cancelled());
                    switchy_async::select! {
                        () = playback.abort.cancelled() => {
                            log::debug!("play_playback: Playback cancelled");
                            return Err(PlayerError::Cancelled);
                        }
                        resp = player.play(seek, retry_options) => {
                            if let Err(err) = resp {
                                log::error!("Playback error occurred: {err:?}");

                                {
                                    let old = playback.clone();
                                        playback.playing = false;
                                        player.playback.write().unwrap().replace(playback.clone());
                                    trigger_playback_event(&playback, &old);
                                }


                                return Err(err);
                            }
                        }
                    }

                    log::debug!(
                        "play_playback: playback finished track={track_or_id:?} cancelled={}",
                        playback.abort.is_cancelled()
                    );

                    if playback.abort.is_cancelled() {
                        break;
                    }

                    if ((playback.position + 1) as usize) >= playback.tracks.len() {
                        log::debug!("Playback position at end of tracks. Breaking");
                        break;
                    }

                    let old = playback.clone();
                    playback.position += 1;
                    playback.progress = 0.0;
                    player.playback.write().unwrap().replace(playback.clone());
                    trigger_playback_event(&playback, &old);
                }

                log::debug!(
                    "Finished playback on all tracks. playing={} position={} len={}",
                    playback.playing,
                    playback.position,
                    playback.tracks.len()
                );

                {
                    let old = playback.clone();
                    playback.playing = false;
                    player.playback.write().unwrap().replace(playback.clone());
                    trigger_playback_event(&playback, &old);
                }

                Ok::<_, PlayerError>(0)
            },
        );

        Ok(())
    }

    /// Triggers playback of the current track.
    ///
    /// Starts or resumes playback at the current position with optional seek offset.
    /// This is the internal method that handles actual playback triggering with retry logic.
    ///
    /// # Errors
    ///
    /// * If failed to play the existing playback
    pub async fn play(
        &mut self,
        seek: Option<f64>,
        retry_options: Option<PlaybackRetryOptions>,
    ) -> Result<(), PlayerError> {
        log::debug!("play: seek={seek:?}");

        handle_retry(retry_options, {
            let this = self.clone();

            move || {
                let this = this.clone();
                async move { this.player.trigger_play(seek).await }
            }
        })
        .await?;

        Ok(())
    }

    /// Stops the current playback.
    ///
    /// Halts playback completely and releases playback resources.
    ///
    /// # Errors
    ///
    /// * If failed to stop the existing playback
    pub async fn stop(
        &mut self,
        retry_options: Option<PlaybackRetryOptions>,
    ) -> Result<(), PlayerError> {
        log::debug!("stop: Stopping playback");

        handle_retry(retry_options, {
            let this = self.clone();

            move || {
                let this = this.clone();
                async move { this.player.trigger_stop().await }
            }
        })
        .await?;

        Ok(())
    }

    /// Seeks to a specific position in the current track.
    ///
    /// Changes the playback position to the specified time offset in seconds.
    ///
    /// # Errors
    ///
    /// * If failed to seek the current playback
    pub async fn seek(
        &mut self,
        seek: f64,
        retry_options: Option<PlaybackRetryOptions>,
    ) -> Result<(), PlayerError> {
        log::debug!("seek: seek={seek:?}");

        handle_retry(retry_options, {
            let this = self.clone();

            move || {
                let this = this.clone();
                async move { this.player.trigger_seek(seek).await }
            }
        })
        .await?;

        Ok(())
    }

    /// Skips to the next track in the playlist.
    ///
    /// Advances playback to the next track in the current playlist with optional
    /// seek position. Returns an error if already at the end of the playlist.
    ///
    /// # Panics
    ///
    /// * If the `playback` `RwLock` is poisoned
    ///
    /// # Errors
    ///
    /// * If failed to change to the next track
    pub async fn next_track(
        &mut self,
        seek: Option<f64>,
        retry_options: Option<PlaybackRetryOptions>,
    ) -> Result<(), PlayerError> {
        log::info!("Playing next track seek {seek:?}");
        let playback = {
            self.playback
                .read()
                .unwrap()
                .clone()
                .ok_or(PlayerError::NoPlayersPlaying)?
        };

        if playback.position + 1 >= u16::try_from(playback.tracks.len()).unwrap() {
            return Err(PlayerError::PositionOutOfBounds(playback.position + 1));
        }

        self.update_playback(
            true,
            Some(true),
            None,
            None,
            Some(playback.position + 1),
            seek,
            None,
            None,
            None,
            None,
            None,
            None,
            true,
            retry_options,
        )
        .await
    }

    /// Skips to the previous track in the playlist.
    ///
    /// Returns playback to the previous track in the current playlist with optional
    /// seek position. Returns an error if already at the beginning of the playlist.
    ///
    /// # Panics
    ///
    /// * If the `playback` `RwLock` is poisoned
    ///
    /// # Errors
    ///
    /// * If failed to change to the previous track
    pub async fn previous_track(
        &mut self,
        seek: Option<f64>,
        retry_options: Option<PlaybackRetryOptions>,
    ) -> Result<(), PlayerError> {
        log::info!("Playing next track seek {seek:?}");
        let playback = {
            self.playback
                .read()
                .unwrap()
                .clone()
                .ok_or(PlayerError::NoPlayersPlaying)?
        };

        if playback.position == 0 {
            return Err(PlayerError::PositionOutOfBounds(0));
        }

        self.update_playback(
            true,
            Some(true),
            None,
            None,
            Some(playback.position - 1),
            seek,
            None,
            None,
            None,
            None,
            None,
            None,
            true,
            retry_options,
        )
        .await
    }

    /// Performs pre-update operations before playback state changes.
    ///
    /// This hook allows the player implementation to prepare for upcoming playback state updates.
    ///
    /// # Errors
    ///
    /// * If failed to handle logic in the `before_update_playback`
    #[allow(clippy::unused_async)]
    pub async fn before_update_playback(&mut self) -> Result<(), PlayerError> {
        self.player.before_update_playback().await?;

        Ok(())
    }

    /// Performs post-update operations after playback state changes.
    ///
    /// This hook allows the player implementation to synchronize state after playback updates.
    ///
    /// # Errors
    ///
    /// * If failed to handle logic in the `after_update_playback`
    #[allow(clippy::unused_async)]
    pub async fn after_update_playback(&mut self) -> Result<(), PlayerError> {
        self.player.after_update_playback().await?;

        Ok(())
    }

    /// Updates playback state with multiple configuration options.
    ///
    /// This is the primary method for modifying playback state, including playing,
    /// stopping, seeking, volume control, and playlist changes. It handles complex
    /// state transitions like pause/resume and play/stop logic.
    ///
    /// # Panics
    ///
    /// * If the `playback` `RwLock` is poisoned
    ///
    /// # Errors
    ///
    /// * If any of the playback actions failed
    /// * If failed to handle logic in the `before_update_playback`
    #[allow(
        clippy::too_many_arguments,
        clippy::too_many_lines,
        clippy::cognitive_complexity
    )]
    pub async fn update_playback(
        &mut self,
        modify_playback: bool,
        play: Option<bool>,
        stop: Option<bool>,
        playing: Option<bool>,
        position: Option<u16>,
        seek: Option<f64>,
        volume: Option<f64>,
        tracks: Option<Vec<Track>>,
        quality: Option<PlaybackQuality>,
        session_id: Option<u64>,
        profile: Option<String>,
        playback_target: Option<PlaybackTarget>,
        trigger_event: bool,
        retry_options: Option<PlaybackRetryOptions>,
    ) -> Result<(), PlayerError> {
        log::debug!(
            "\
            update_playback:\n\t\
            modify_playback={modify_playback:?}\n\t\
            play={play:?}\n\t\
            stop={stop:?}\n\t\
            playing={playing:?}\n\t\
            position={position:?}\n\t\
            seek={seek:?}\n\t\
            volume={volume:?}\n\t\
            tracks={tracks:?}\n\t\
            quality={quality:?}\n\t\
            session_id={session_id:?}\n\t\
            profile={profile:?}\n\t\
            playback_target={playback_target:?}\n\t\
            trigger_event={trigger_event}\
            "
        );

        self.before_update_playback().await?;

        let original = self.playback.read().unwrap().clone();

        let (session_id, profile) = if let Some(original) = &original {
            log::trace!("update_playback: existing playback={original:?}");
            (
                session_id.unwrap_or(original.session_id),
                profile.unwrap_or_else(|| original.profile.clone()),
            )
        } else {
            (
                session_id.ok_or(PlayerError::MissingSessionId)?,
                profile.ok_or(PlayerError::MissingProfile)?,
            )
        };

        let original = original.unwrap_or_else(|| {
            Playback::new(
                tracks.clone().unwrap_or_default(),
                position,
                AtomicF64::new(volume.unwrap_or(1.0)),
                quality.unwrap_or_default(),
                session_id,
                profile.clone(),
                playback_target.clone(),
            )
        });

        let playing = playing.unwrap_or(original.playing);
        let same_track = same_active_track(position, tracks.as_deref(), &original);
        let wants_to_play = play.unwrap_or(false) || playing;
        let should_start = wants_to_play && (!original.playing || !same_track);
        let should_seek = tracks.is_none() && seek.is_some();
        let should_stop = stop.unwrap_or(false);
        let is_playing = (playing || should_start) && !should_stop;
        let should_resume = same_track && !original.playing && playing && seek.is_none();
        let should_pause = same_track && original.playing && !playing;

        let playback = Playback {
            id: original.id,
            session_id,
            profile,
            playback_target: playback_target.or_else(|| original.playback_target.clone()),
            tracks: tracks.clone().unwrap_or_else(|| original.tracks.clone()),
            playing: is_playing,
            quality: quality.unwrap_or(original.quality),
            position: position.unwrap_or(original.position),
            progress: if play.unwrap_or(false) {
                seek.unwrap_or(0.0)
            } else {
                seek.unwrap_or(original.progress)
            },
            volume: original.volume.clone(),
            abort: if original.abort.is_cancelled() {
                CancellationToken::new()
            } else {
                original.abort.clone()
            },
        };

        if let Some(volume) = volume {
            playback
                .volume
                .store(volume, std::sync::atomic::Ordering::SeqCst);
        }

        log::debug!("update_playback: updating active playback to {playback:?}");
        self.playback.write().unwrap().replace(playback.clone());

        // Call after_update_playback AFTER the volume has been updated
        // This ensures the player can sync the correct volume to shared atomics
        self.after_update_playback().await?;

        if !modify_playback {
            return Ok(());
        }

        log::debug!(
            "\
            update_playback:\n\t\
            should_start_playback={should_start}\n\t\
            should_stop={should_stop}\n\t\
            should_resume={should_resume}\n\t\
            should_pause={should_pause}\n\t\
            should_seek={should_seek}\
            "
        );

        if trigger_event {
            trigger_playback_event(&playback, &original);
        }

        let progress = if let Some(seek) = seek {
            Some(seek)
        } else if playback.progress != 0.0 {
            Some(playback.progress)
        } else {
            None
        };

        if should_seek && let Some(seek) = seek {
            log::debug!("update_playback: Seeking track to seek={seek}");
            self.seek(seek, Some(DEFAULT_SEEK_RETRY_OPTIONS)).await?;
        }
        if should_stop {
            self.stop(retry_options).await?;
        } else if should_resume {
            if let Err(e) = self.resume(retry_options).await {
                log::error!("Failed to resume playback: {e:?}");
                self.play_playback(progress, retry_options).await?;
            }
        } else if should_start {
            self.play_playback(progress, retry_options).await?;
        } else if should_pause {
            self.pause(retry_options).await?;
        }

        Ok(())
    }

    /// Pauses the current playback.
    ///
    /// Temporarily halts playback while maintaining the current position.
    ///
    /// # Errors
    ///
    /// * If failed to pause the current `Playback`
    pub async fn pause(
        &mut self,
        retry_options: Option<PlaybackRetryOptions>,
    ) -> Result<(), PlayerError> {
        log::debug!("pause: Pausing playback");

        handle_retry(retry_options, {
            let this = self.clone();

            move || {
                let this = this.clone();
                async move { this.player.trigger_pause().await }
            }
        })
        .await?;

        Ok(())
    }

    /// Resumes playback from a paused state.
    ///
    /// Continues playback from the position where it was paused.
    ///
    /// # Errors
    ///
    /// * If failed to resume the current `Playback`
    pub async fn resume(
        &mut self,
        retry_options: Option<PlaybackRetryOptions>,
    ) -> Result<(), PlayerError> {
        log::debug!("resume: Resuming playback");

        handle_retry(retry_options, {
            let this = self.clone();

            move || {
                let this = this.clone();
                async move { this.player.trigger_resume().await }
            }
        })
        .await?;

        Ok(())
    }
}

/// Trait for implementing custom playback players.
#[async_trait]
pub trait Player: std::fmt::Debug + Send {
    /// Hook called before starting a playback session.
    ///
    /// This allows implementations to perform setup or cleanup before playback begins.
    ///
    /// # Errors
    ///
    /// * If setup operations fail
    async fn before_play_playback(&self, _seek: Option<f64>) -> Result<(), PlayerError> {
        Ok(())
    }

    /// Initiates playback at the current position with optional seek.
    ///
    /// # Errors
    ///
    /// * If playback cannot be started
    /// * If the audio output fails
    async fn trigger_play(&self, seek: Option<f64>) -> Result<(), PlayerError>;

    /// Stops the current playback.
    ///
    /// # Errors
    ///
    /// * If stopping playback fails
    async fn trigger_stop(&self) -> Result<(), PlayerError>;

    /// Seeks to a specific position in the current track.
    ///
    /// # Errors
    ///
    /// * If seeking fails
    /// * If the seek position is invalid
    async fn trigger_seek(&self, seek: f64) -> Result<(), PlayerError>;

    /// Hook called before updating playback state.
    ///
    /// This allows implementations to prepare for state changes.
    ///
    /// # Errors
    ///
    /// * If preparation operations fail
    async fn before_update_playback(&self) -> Result<(), PlayerError> {
        Ok(())
    }

    /// Hook called after updating playback state.
    ///
    /// This allows implementations to synchronize state after changes.
    ///
    /// # Errors
    ///
    /// * If synchronization operations fail
    async fn after_update_playback(&self) -> Result<(), PlayerError> {
        Ok(())
    }

    /// Pauses the current playback.
    ///
    /// # Errors
    ///
    /// * If pausing fails
    async fn trigger_pause(&self) -> Result<(), PlayerError>;

    /// Resumes playback from a paused state.
    ///
    /// # Errors
    ///
    /// * If resuming fails
    async fn trigger_resume(&self) -> Result<(), PlayerError>;

    /// Retrieves the current playback status.
    ///
    /// # Errors
    ///
    /// * If failed to access the player status
    fn player_status(&self) -> Result<ApiPlaybackStatus, PlayerError>;

    /// Returns the player's source configuration.
    #[must_use]
    fn get_source(&self) -> &PlayerSource;
}

#[cfg_attr(feature = "profiling", profiling::function)]
fn same_active_track(position: Option<u16>, tracks: Option<&[Track]>, playback: &Playback) -> bool {
    match (position, tracks) {
        (None, None) => true,
        (Some(position), None) => playback.position == position,
        (None, Some(tracks)) => {
            tracks
                .get(playback.position as usize)
                .map(|x: &Track| &x.id)
                == playback
                    .tracks
                    .get(playback.position as usize)
                    .map(|x: &Track| &x.id)
        }
        (Some(position), Some(tracks)) => {
            tracks.get(position as usize).map(|x: &Track| &x.id)
                == playback
                    .tracks
                    .get(playback.position as usize)
                    .map(|x: &Track| &x.id)
        }
    }
}

/// Global service port configuration.
pub static SERVICE_PORT: LazyLock<RwLock<Option<u16>>> = LazyLock::new(|| RwLock::new(None));

/// Sets the service port for local playback.
///
/// # Panics
///
/// * If the `SERVICE_PORT` `RwLock` is poisoned
pub fn set_service_port(service_port: u16) {
    SERVICE_PORT.write().unwrap().replace(service_port);
}

/// Callback function type for playback state change events.
///
/// Functions of this type receive notifications when playback state changes,
/// including play, pause, seek, volume, and track position updates.
type PlaybackEventCallback = fn(&UpdateSession, &Playback);

static PLAYBACK_EVENT_LISTENERS: LazyLock<Arc<RwLock<Vec<PlaybackEventCallback>>>> =
    LazyLock::new(|| Arc::new(RwLock::new(Vec::new())));

/// Registers a callback to be invoked when playback state changes.
///
/// The callback receives updates about playback events like play, pause,
/// seek, and volume changes.
///
/// # Panics
///
/// * If the `PLAYBACK_EVENT_LISTENERS` `RwLock` is poisoned
pub fn on_playback_event(listener: PlaybackEventCallback) {
    PLAYBACK_EVENT_LISTENERS.write().unwrap().push(listener);
}

/// Triggers playback events for registered listeners when playback state changes.
#[cfg_attr(feature = "profiling", profiling::function)]
pub fn trigger_playback_event(current: &Playback, previous: &Playback) {
    let Some(playback_target) = current.playback_target.clone() else {
        return;
    };

    let mut has_change = false;

    let playing = if current.playing == previous.playing {
        None
    } else {
        has_change = true;
        Some(current.playing)
    };
    let position = if current.position == previous.position {
        None
    } else {
        has_change = true;
        Some(current.position)
    };
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let seek = if current.progress as usize == previous.progress as usize {
        None
    } else {
        has_change = true;
        Some(current.progress)
    };
    let current_volume = current.volume.load(std::sync::atomic::Ordering::SeqCst);
    let volume = if (current_volume - previous.volume.load(std::sync::atomic::Ordering::SeqCst))
        .abs()
        < 0.001
    {
        None
    } else {
        has_change = true;
        Some(current_volume)
    };
    let quality = if current.quality == previous.quality {
        None
    } else {
        has_change = true;
        Some(current.quality)
    };
    let tracks = current
        .tracks
        .iter()
        .cloned()
        .map(Into::into)
        .collect::<Vec<_>>();
    let prev_tracks = previous
        .tracks
        .iter()
        .cloned()
        .map(Into::into)
        .collect::<Vec<_>>();
    let playlist = if tracks == prev_tracks {
        None
    } else {
        has_change = true;
        Some(UpdateSessionPlaylist {
            session_playlist_id: 0,
            tracks,
        })
    };

    if !has_change {
        return;
    }

    log::debug!(
        "\
        Triggering playback event:\n\t\
        playing={playing:?}\n\t\
        position={position:?}\n\t\
        seek={seek:?}\n\t\
        quality={quality:?}\n\t\
        volume={volume:?}\n\t\
        playback_target={playback_target:?}\n\t\
        playlist={playlist:?}\
        "
    );

    let update = UpdateSession {
        session_id: current.session_id,
        profile: current.profile.clone(),
        playback_target,
        play: None,
        stop: None,
        name: None,
        active: None,
        playing,
        position,
        seek,
        volume,
        playlist,
        quality,
    };

    send_playback_event(&update, current);
}

#[allow(unused, clippy::too_many_lines)]
async fn track_to_playable_file(
    track: &Track,
    format: PlaybackQuality,
    quality: TrackAudioQuality,
) -> Result<PlayableTrack, PlayerError> {
    log::trace!("track_to_playable_file track={track:?} format={format:?} quality={quality:?}");

    let mut hint = Hint::new();

    let file = track.file.clone().unwrap();
    let path = Path::new(&file);

    // Provide the file extension as a hint.
    if let Some(extension) = path.extension()
        && let Some(extension_str) = extension.to_str()
    {
        hint.with_extension(extension_str);
    }

    #[allow(clippy::match_wildcard_for_single_variants)]
    let same_source = match format.format {
        AudioFormat::Source => true,
        #[allow(unreachable_patterns)]
        _ => track.format.is_none_or(|x| x == format.format),
    };

    let source: Box<dyn MediaSource> = if same_source {
        Box::new(File::open(path)?)
    } else {
        #[allow(unused_mut)]
        let mut signal_chain = SignalChain::new();

        match format.format {
            #[cfg(feature = "format-aac")]
            AudioFormat::Aac => {
                #[cfg(feature = "encoder-aac")]
                {
                    use moosicbox_audio_output::encoder::aac::AacEncoder;
                    log::debug!("Encoding playback with AacEncoder");
                    let mut hint = Hint::new();
                    hint.with_extension("m4a");
                    signal_chain = signal_chain
                        .add_encoder_step(|| Box::new(AacEncoder::new()))
                        .with_hint(hint);
                }
                #[cfg(not(feature = "encoder-aac"))]
                panic!("No encoder-aac feature");
            }
            #[cfg(feature = "format-flac")]
            AudioFormat::Flac => {
                #[cfg(feature = "encoder-flac")]
                {
                    use moosicbox_audio_output::encoder::flac::FlacEncoder;
                    log::debug!("Encoding playback with FlacEncoder");
                    let mut hint = Hint::new();
                    hint.with_extension("flac");
                    signal_chain = signal_chain
                        .add_encoder_step(|| Box::new(FlacEncoder::new()))
                        .with_hint(hint);
                }
                #[cfg(not(feature = "encoder-flac"))]
                panic!("No encoder-flac feature");
            }
            #[cfg(feature = "format-mp3")]
            AudioFormat::Mp3 => {
                #[cfg(feature = "encoder-mp3")]
                {
                    use moosicbox_audio_output::encoder::mp3::Mp3Encoder;
                    log::debug!("Encoding playback with Mp3Encoder");
                    let mut hint = Hint::new();
                    hint.with_extension("mp3");
                    signal_chain = signal_chain
                        .add_encoder_step(|| Box::new(Mp3Encoder::new()))
                        .with_hint(hint);
                }
                #[cfg(not(feature = "encoder-mp3"))]
                panic!("No encoder-mp3 feature");
            }
            #[cfg(feature = "format-opus")]
            AudioFormat::Opus => {
                #[cfg(feature = "encoder-opus")]
                {
                    use moosicbox_audio_output::encoder::opus::OpusEncoder;
                    log::debug!("Encoding playback with OpusEncoder");
                    let mut hint = Hint::new();
                    hint.with_extension("opus");
                    signal_chain = signal_chain
                        .add_encoder_step(|| Box::new(OpusEncoder::new()))
                        .with_hint(hint);
                }
                #[cfg(not(feature = "encoder-opus"))]
                panic!("No encoder-opus feature");
            }
            #[allow(unreachable_patterns)]
            _ => {
                moosicbox_assert::die!("Invalid format {}", format.format);
            }
        }

        log::trace!(
            "track_to_playable_file: getting file at path={}",
            path.display()
        );
        let file = tokio::fs::File::open(path.to_path_buf()).await?;

        log::trace!("track_to_playable_file: Creating ByteStreamSource");
        let ms = Box::new(ByteStreamSource::new(
            Box::new(
                StalledReadMonitor::new(
                    FramedRead::new(file, BytesCodec::new())
                        .map_ok(bytes::BytesMut::freeze)
                        .boxed(),
                )
                .map(|x| match x {
                    Ok(Ok(x)) => Ok(x),
                    Ok(Err(err)) | Err(err) => Err(err),
                }),
            ),
            None,
            true,
            false,
            CancellationToken::new(),
        ));

        match signal_chain.process(ms) {
            Ok(stream) => stream,
            Err(SignalChainError::Playback(e)) => {
                return Err(PlayerError::PlaybackError(match e {
                    symphonia_unsync::PlaybackError::Symphonia(e) => PlaybackError::Symphonia(e),
                    symphonia_unsync::PlaybackError::Decode(e) => PlaybackError::Decode(e),
                }));
            }
            Err(SignalChainError::Empty) => unreachable!("Empty signal chain"),
        }
    };

    Ok(PlayableTrack {
        track_id: track.id.clone(),
        source,
        hint,
    })
}

#[allow(unused)]
async fn track_to_playable_stream(
    track: &Track,
    format: PlaybackQuality,
    quality: TrackAudioQuality,
    player_source: &PlayerSource,
    abort: CancellationToken,
) -> Result<PlayableTrack, PlayerError> {
    track_id_to_playable_stream(
        &track.id,
        &track.api_source,
        format,
        quality,
        player_source,
        abort,
    )
    .await
}

#[allow(unused)]
async fn track_id_to_playable_stream(
    track_id: &Id,
    source: &ApiSource,
    format: PlaybackQuality,
    quality: TrackAudioQuality,
    player_source: &PlayerSource,
    abort: CancellationToken,
) -> Result<PlayableTrack, PlayerError> {
    let (url, headers) =
        get_track_url(track_id, source, player_source, format, quality, false).await?;

    log::debug!("Fetching track bytes from url: {url}");

    let mut client = CLIENT.head(&url);

    if let Some(headers) = headers {
        for (key, value) in headers {
            client = client.header(&key, &value);
        }
    }

    let mut res = client.send().await.unwrap();
    let headers = res.headers();
    let size = headers
        .get("content-length")
        .map(|length| length.parse::<u64>().unwrap());

    let source: RemoteByteStreamMediaSource = RemoteByteStream::new(
        url,
        size,
        true,
        size.is_some(), // HTTP range requests work for any format when size is known
        abort,
    )
    .into();

    let mut hint = Hint::new();

    if let Some(content_type) = headers.get("content-type") {
        if let Some(audio_type) = content_type.strip_prefix("audio/") {
            log::debug!("Setting hint extension to {audio_type}");
            hint.with_extension(audio_type);
        } else {
            log::warn!("Invalid audio content_type: {content_type}");
        }
    }

    Ok(PlayableTrack {
        track_id: track_id.to_owned(),
        source: Box::new(source),
        hint,
    })
}

#[allow(unused)]
async fn track_or_id_to_playable(
    playback_type: PlaybackType,
    track: &Track,
    format: PlaybackQuality,
    quality: TrackAudioQuality,
    player_source: &PlayerSource,
    abort: CancellationToken,
) -> Result<PlayableTrack, PlayerError> {
    log::trace!(
        "track_or_id_to_playable playback_type={playback_type:?} track={track:?} quality={format:?}"
    );
    Ok(
        if track.api_source.is_library()
            && matches!(playback_type, PlaybackType::File | PlaybackType::Default)
        {
            track_to_playable_file(track, format, quality).await?
        } else {
            track_to_playable_stream(track, format, quality, player_source, abort).await?
        },
    )
}

async fn handle_retry<
    T,
    E: std::fmt::Debug + Into<PlayerError>,
    F: Future<Output = Result<T, E>> + Send,
>(
    retry_options: Option<PlaybackRetryOptions>,
    func: impl Fn() -> F + Send,
) -> Result<T, PlayerError> {
    let mut retry_count = 0;

    loop {
        if retry_count > 0 {
            switchy_async::time::sleep(retry_options.unwrap().retry_delay).await;
        }

        match func().await {
            Ok(value) => {
                log::trace!("Finished action");
                return Ok(value);
            }
            Err(e) => {
                let e = e.into();
                if matches!(e, PlayerError::Cancelled) {
                    log::debug!("Action cancelled");
                    return Err(e);
                }
                log::error!("Action failed: {e:?}");
                if let Some(retry_options) = retry_options {
                    retry_count += 1;
                    if retry_count >= retry_options.max_attempts {
                        log::error!(
                            "Action retry failed after {retry_count} attempts. Not retrying"
                        );
                        return Err(e);
                    }
                    log::info!(
                        "Retrying action attempt {}/{}",
                        retry_count + 1,
                        retry_options.max_attempts
                    );
                    continue;
                }

                log::debug!("No retry options");
                break Err(e);
            }
        }
    }
}

/// Notifies all registered listeners of a playback event.
///
/// This function is called internally when playback state changes to broadcast
/// the update to all registered event listeners.
///
/// # Panics
///
/// * If the `PLAYBACK_EVENT_LISTENERS` `RwLock` is poisoned
#[cfg_attr(feature = "profiling", profiling::function)]
pub fn send_playback_event(update: &UpdateSession, playback: &Playback) {
    for listener in PLAYBACK_EVENT_LISTENERS.read().unwrap().iter() {
        listener(update, playback);
    }
}

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

    fn create_test_track(id: u64) -> Track {
        Track {
            id: id.into(),
            number: 1,
            title: format!("Track {id}"),
            duration: 180.0,
            album: "Test Album".to_string(),
            album_id: 1.into(),
            album_type: moosicbox_music_models::AlbumType::Lp,
            date_released: None,
            date_added: None,
            artist: "Test Artist".to_string(),
            artist_id: 1.into(),
            file: None,
            artwork: None,
            blur: false,
            bytes: 0,
            format: None,
            bit_depth: None,
            audio_bitrate: None,
            overall_bitrate: None,
            sample_rate: None,
            channels: None,
            track_source: moosicbox_music_models::TrackApiSource::Local,
            api_source: ApiSource::library(),
            sources: moosicbox_music_models::ApiSources::default(),
        }
    }

    #[test_log::test]
    fn test_same_active_track_no_changes() {
        let tracks = vec![create_test_track(1), create_test_track(2)];
        let playback = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None,
        );

        // No position change, no tracks change
        assert!(same_active_track(None, None, &playback));
    }

    #[test_log::test]
    fn test_same_active_track_same_position_no_tracks() {
        let tracks = vec![create_test_track(1), create_test_track(2)];
        let playback = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None,
        );

        // Same position, no new tracks
        assert!(same_active_track(Some(0), None, &playback));
    }

    #[test_log::test]
    fn test_same_active_track_different_position_no_tracks() {
        let tracks = vec![create_test_track(1), create_test_track(2)];
        let playback = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None,
        );

        // Different position, no new tracks
        assert!(!same_active_track(Some(1), None, &playback));
    }

    #[test_log::test]
    fn test_same_active_track_same_track_at_position() {
        let tracks = vec![create_test_track(1), create_test_track(2)];
        let playback = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None,
        );

        // Same track at current position
        assert!(same_active_track(None, Some(&playback.tracks), &playback));
    }

    #[test_log::test]
    fn test_same_active_track_different_track_at_position() {
        let tracks = vec![create_test_track(1), create_test_track(2)];
        let playback = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None,
        );

        // Different track at current position
        let new_tracks = vec![create_test_track(3), create_test_track(2)];
        assert!(!same_active_track(None, Some(&new_tracks), &playback));
    }

    #[test_log::test]
    fn test_same_active_track_with_position_and_tracks() {
        let tracks = vec![
            create_test_track(1),
            create_test_track(2),
            create_test_track(3),
        ];
        let playback = Playback::new(
            tracks.clone(),
            Some(1),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None,
        );

        // Position 1, same track at position 1
        assert!(same_active_track(Some(1), Some(&tracks), &playback));

        // Position 2, different from playback position 1
        assert!(!same_active_track(Some(2), Some(&tracks), &playback));
    }

    #[test_log::test]
    fn test_playback_new_creates_valid_instance() {
        let tracks = vec![create_test_track(1)];
        let playback = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(0.8),
            PlaybackQuality::default(),
            123,
            "test-profile".to_string(),
            None,
        );

        assert_eq!(playback.session_id, 123);
        assert_eq!(playback.profile, "test-profile");
        assert_eq!(playback.tracks.len(), 1);
        assert!(!playback.playing);
        assert_eq!(playback.position, 0);
        assert!((playback.volume.load(std::sync::atomic::Ordering::SeqCst) - 0.8).abs() < 0.001);
        assert!((playback.progress - 0.0).abs() < 0.001);
    }

    #[test_log::test]
    fn test_playback_new_defaults_position_to_zero() {
        let tracks = vec![create_test_track(1)];
        let playback = Playback::new(
            tracks,
            None,
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None,
        );

        assert_eq!(playback.position, 0);
    }

    #[test_log::test]
    fn test_playback_to_api_playback_conversion() {
        let tracks = vec![create_test_track(1), create_test_track(2)];
        let mut playback = Playback::new(
            tracks,
            Some(1),
            AtomicF64::new(0.7),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None,
        );
        playback.playing = true;
        playback.progress = 45.5;

        let api_playback: ApiPlayback = playback.into();

        assert_eq!(api_playback.track_ids.len(), 2);
        assert_eq!(api_playback.track_ids[0], "1");
        assert_eq!(api_playback.track_ids[1], "2");
        assert!(api_playback.playing);
        assert_eq!(api_playback.position, 1);
        assert!((api_playback.seek - 45.5).abs() < 0.001);
    }

    #[test_log::test]
    fn test_playback_status_struct() {
        let status = PlaybackStatus { success: true };
        assert!(status.success);

        let status = PlaybackStatus { success: false };
        assert!(!status.success);
    }

    #[test_log::test]
    fn test_playback_type_default_is_default() {
        let playback_type = PlaybackType::default();
        assert!(matches!(playback_type, PlaybackType::Default));
    }

    #[test_log::test]
    fn test_playback_retry_options_constants() {
        assert_eq!(DEFAULT_SEEK_RETRY_OPTIONS.max_attempts, 10);
        assert_eq!(
            DEFAULT_SEEK_RETRY_OPTIONS.retry_delay,
            std::time::Duration::from_millis(100)
        );

        assert_eq!(DEFAULT_PLAYBACK_RETRY_OPTIONS.max_attempts, 10);
        assert_eq!(
            DEFAULT_PLAYBACK_RETRY_OPTIONS.retry_delay,
            std::time::Duration::from_millis(500)
        );
    }

    #[test_log::test]
    fn test_player_source_debug_format() {
        let source = PlayerSource::Local;
        let debug_str = format!("{source:?}");
        assert!(debug_str.contains("Local"));

        let source = PlayerSource::Remote {
            host: "http://localhost:8080".to_string(),
            query: None,
            headers: None,
        };
        let debug_str = format!("{source:?}");
        assert!(debug_str.contains("Remote"));
        assert!(debug_str.contains("localhost"));
    }

    #[test_log::test]
    fn test_set_service_port() {
        set_service_port(9876);
        assert_eq!(*SERVICE_PORT.read().unwrap(), Some(9876));
    }

    #[test_log::test]
    fn test_playback_handler_new_creates_valid_instance() {
        #[derive(Debug)]
        struct MockPlayer;

        #[async_trait]
        impl Player for MockPlayer {
            async fn trigger_play(&self, _seek: Option<f64>) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_stop(&self) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_seek(&self, _seek: f64) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_pause(&self) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_resume(&self) -> Result<(), PlayerError> {
                Ok(())
            }
            fn player_status(&self) -> Result<ApiPlaybackStatus, PlayerError> {
                Ok(ApiPlaybackStatus {
                    active_playbacks: None,
                })
            }
            fn get_source(&self) -> &PlayerSource {
                &PlayerSource::Local
            }
        }

        let handler = PlaybackHandler::new(MockPlayer);
        assert!(handler.playback.read().unwrap().is_none());
        assert!(handler.output.is_none());
    }

    #[test_log::test]
    fn test_player_error_display() {
        let error = PlayerError::NoPlayersPlaying;
        assert_eq!(error.to_string(), "No players playing");

        let error = PlayerError::TrackNotFound(42.into());
        assert!(error.to_string().contains("Track not found"));
        assert!(error.to_string().contains("42"));

        let error = PlayerError::PositionOutOfBounds(99);
        assert!(error.to_string().contains("Position out of bounds"));
        assert!(error.to_string().contains("99"));
    }

    #[test_log::test]
    fn test_trigger_playback_event_with_no_changes() {
        let tracks = vec![create_test_track(1)];
        let playback = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            Some(PlaybackTarget::AudioZone { audio_zone_id: 1 }),
        );

        // Same playback state - should not trigger event
        trigger_playback_event(&playback, &playback);
        // No assertion needed - just verifying it doesn't panic
    }

    #[test_log::test]
    fn test_trigger_playback_event_with_playing_change() {
        let tracks = vec![create_test_track(1)];
        let mut playback1 = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            Some(PlaybackTarget::AudioZone { audio_zone_id: 1 }),
        );
        playback1.playing = false;

        let mut playback2 = playback1.clone();
        playback2.playing = true;

        // Different playing state - should trigger event
        trigger_playback_event(&playback2, &playback1);
        // No assertion needed - just verifying it doesn't panic
    }

    #[test_log::test]
    fn test_trigger_playback_event_without_target_does_nothing() {
        let tracks = vec![create_test_track(1)];
        let playback = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None, // No playback target
        );

        let mut playback2 = playback.clone();
        playback2.playing = true;

        // Should return early without triggering
        trigger_playback_event(&playback2, &playback);
    }

    #[test_log::test]
    fn test_trigger_playback_event_with_position_change() {
        let tracks = vec![create_test_track(1), create_test_track(2)];
        let playback1 = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            Some(PlaybackTarget::AudioZone { audio_zone_id: 1 }),
        );

        let mut playback2 = playback1.clone();
        playback2.position = 1;

        // Different position - should trigger event
        trigger_playback_event(&playback2, &playback1);
    }

    #[test_log::test]
    fn test_trigger_playback_event_with_volume_change() {
        let tracks = vec![create_test_track(1)];
        let playback1 = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            Some(PlaybackTarget::AudioZone { audio_zone_id: 1 }),
        );

        let playback2 = playback1.clone();
        // Volume change larger than 0.001 threshold
        playback2
            .volume
            .store(0.5, std::sync::atomic::Ordering::SeqCst);

        // Different volume - should trigger event
        trigger_playback_event(&playback2, &playback1);
    }

    #[test_log::test]
    fn test_trigger_playback_event_volume_within_threshold_no_change() {
        let tracks = vec![create_test_track(1)];
        let playback1 = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            Some(PlaybackTarget::AudioZone { audio_zone_id: 1 }),
        );

        let playback2 = playback1.clone();
        // Volume change smaller than 0.001 threshold - should not be detected as change
        playback2
            .volume
            .store(1.0005, std::sync::atomic::Ordering::SeqCst);

        // Volume within threshold - should NOT trigger event (returns early)
        trigger_playback_event(&playback2, &playback1);
    }

    #[test_log::test]
    fn test_trigger_playback_event_with_seek_change() {
        let tracks = vec![create_test_track(1)];
        let mut playback1 = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            Some(PlaybackTarget::AudioZone { audio_zone_id: 1 }),
        );
        playback1.progress = 10.0;

        let mut playback2 = playback1.clone();
        // Progress change that results in different integer (seek is compared as usize)
        playback2.progress = 15.0;

        // Different seek/progress - should trigger event
        trigger_playback_event(&playback2, &playback1);
    }

    #[test_log::test]
    fn test_trigger_playback_event_seek_same_second_no_change() {
        let tracks = vec![create_test_track(1)];
        let mut playback1 = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            Some(PlaybackTarget::AudioZone { audio_zone_id: 1 }),
        );
        playback1.progress = 10.3;

        let mut playback2 = playback1.clone();
        // Progress change within the same second (cast to usize)
        playback2.progress = 10.7;

        // Same second - should NOT trigger event (returns early due to has_change=false)
        trigger_playback_event(&playback2, &playback1);
    }

    #[cfg(feature = "format-flac")]
    #[test_log::test]
    fn test_trigger_playback_event_with_quality_change() {
        let tracks = vec![create_test_track(1)];
        let playback1 = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality {
                format: moosicbox_music_models::AudioFormat::Source,
            },
            1,
            "test".to_string(),
            Some(PlaybackTarget::AudioZone { audio_zone_id: 1 }),
        );

        let mut playback2 = playback1.clone();
        playback2.quality = PlaybackQuality {
            format: moosicbox_music_models::AudioFormat::Flac,
        };

        // Different quality - should trigger event
        trigger_playback_event(&playback2, &playback1);
    }

    #[test_log::test]
    fn test_trigger_playback_event_with_tracks_change() {
        let tracks1 = vec![create_test_track(1)];
        let playback1 = Playback::new(
            tracks1,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            Some(PlaybackTarget::AudioZone { audio_zone_id: 1 }),
        );

        let mut playback2 = playback1.clone();
        playback2.tracks = vec![create_test_track(1), create_test_track(2)];

        // Different tracks - should trigger event
        trigger_playback_event(&playback2, &playback1);
    }

    #[test_log::test(switchy_async::test)]
    async fn test_handle_retry_success_on_first_try() {
        let call_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let call_count_clone = call_count.clone();

        let result: Result<i32, PlayerError> = handle_retry(
            Some(PlaybackRetryOptions {
                max_attempts: 3,
                retry_delay: std::time::Duration::from_millis(1),
            }),
            move || {
                let count = call_count_clone.clone();
                async move {
                    count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    Ok::<i32, PlayerError>(42)
                }
            },
        )
        .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);
        assert_eq!(call_count.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    #[test_log::test(switchy_async::test(real_time))]
    async fn test_handle_retry_success_after_retries() {
        let call_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let call_count_clone = call_count.clone();

        let result: Result<i32, PlayerError> = handle_retry(
            Some(PlaybackRetryOptions {
                max_attempts: 5,
                retry_delay: std::time::Duration::from_millis(1),
            }),
            move || {
                let count = call_count_clone.clone();
                async move {
                    let current = count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    if current < 2 {
                        // Fail first two attempts
                        Err(PlayerError::RetryRequested)
                    } else {
                        // Succeed on third attempt
                        Ok::<i32, PlayerError>(42)
                    }
                }
            },
        )
        .await;

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);
        // Should have been called 3 times (2 failures + 1 success)
        assert_eq!(call_count.load(std::sync::atomic::Ordering::SeqCst), 3);
    }

    #[test_log::test(switchy_async::test(real_time))]
    async fn test_handle_retry_exhausts_max_attempts() {
        let call_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let call_count_clone = call_count.clone();

        let result: Result<i32, PlayerError> = handle_retry(
            Some(PlaybackRetryOptions {
                max_attempts: 3,
                retry_delay: std::time::Duration::from_millis(1),
            }),
            move || {
                let count = call_count_clone.clone();
                async move {
                    count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    // Always fail
                    Err(PlayerError::RetryRequested)
                }
            },
        )
        .await;

        assert!(result.is_err());
        assert!(matches!(result, Err(PlayerError::RetryRequested)));
        // Should have been called max_attempts times
        assert_eq!(call_count.load(std::sync::atomic::Ordering::SeqCst), 3);
    }

    #[test_log::test(switchy_async::test)]
    async fn test_handle_retry_cancelled_returns_immediately() {
        let call_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let call_count_clone = call_count.clone();

        let result: Result<i32, PlayerError> = handle_retry(
            Some(PlaybackRetryOptions {
                max_attempts: 5,
                retry_delay: std::time::Duration::from_millis(1),
            }),
            move || {
                let count = call_count_clone.clone();
                async move {
                    count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                    // Return Cancelled error - should not retry
                    Err(PlayerError::Cancelled)
                }
            },
        )
        .await;

        assert!(result.is_err());
        assert!(matches!(result, Err(PlayerError::Cancelled)));
        // Should have been called only once - cancellation doesn't retry
        assert_eq!(call_count.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    #[test_log::test(switchy_async::test)]
    async fn test_handle_retry_no_options_single_attempt() {
        let call_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0));
        let call_count_clone = call_count.clone();

        let result: Result<i32, PlayerError> = handle_retry(None, move || {
            let count = call_count_clone.clone();
            async move {
                count.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
                // Fail
                Err(PlayerError::RetryRequested)
            }
        })
        .await;

        assert!(result.is_err());
        // Without retry options, should only try once and fail
        assert_eq!(call_count.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    #[test_log::test]
    fn test_same_active_track_with_empty_tracks() {
        let playback = Playback::new(
            vec![],
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None,
        );

        // Empty tracks list should handle gracefully
        assert!(same_active_track(None, None, &playback));
        assert!(same_active_track(None, Some(&[]), &playback));
    }

    #[test_log::test]
    fn test_same_active_track_position_out_of_bounds() {
        let tracks = vec![create_test_track(1)];
        let playback = Playback::new(
            tracks.clone(),
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None,
        );

        // When position (5) is out of bounds in provided tracks, tracks.get(5) returns None
        // But playback has position 0, so playback.tracks.get(0) returns Some(track)
        // Comparison is: None == Some(track) => false (tracks differ)
        assert!(!same_active_track(Some(5), Some(&tracks), &playback));
    }

    #[test_log::test]
    fn test_playback_abort_token_starts_uncancelled() {
        let tracks = vec![create_test_track(1)];
        let playback = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None,
        );

        assert!(!playback.abort.is_cancelled());
    }

    #[test_log::test]
    fn test_playback_abort_token_can_be_cancelled() {
        let tracks = vec![create_test_track(1)];
        let playback = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None,
        );

        assert!(!playback.abort.is_cancelled());
        playback.abort.cancel();
        assert!(playback.abort.is_cancelled());
    }

    #[test_log::test]
    fn test_player_error_variants_display() {
        // Test additional error variants to ensure they display correctly
        let error = PlayerError::UnsupportedFormat(moosicbox_music_models::AudioFormat::Source);
        assert!(error.to_string().contains("Format not supported"));

        let error = PlayerError::Seek("seek failed".to_string());
        assert!(error.to_string().contains("Failed to seek"));
        assert!(error.to_string().contains("seek failed"));

        let error = PlayerError::InvalidSession {
            session_id: 123,
            message: "invalid".to_string(),
        };
        assert!(error.to_string().contains("123"));
        assert!(error.to_string().contains("invalid"));

        let error = PlayerError::MissingSessionId;
        assert!(error.to_string().contains("Missing session ID"));

        let error = PlayerError::MissingProfile;
        assert!(error.to_string().contains("Missing profile"));

        let error = PlayerError::InvalidState;
        assert!(error.to_string().contains("Invalid state"));

        let error = PlayerError::InvalidSource;
        assert!(error.to_string().contains("Invalid source"));

        let error = PlayerError::Cancelled;
        assert!(error.to_string().contains("cancelled"));

        let error = PlayerError::RetryRequested;
        assert!(error.to_string().contains("retry"));
    }

    #[test_log::test]
    fn test_playback_handler_with_playback_sets_playback() {
        #[derive(Debug)]
        struct MockPlayer;

        #[async_trait]
        impl Player for MockPlayer {
            async fn trigger_play(&self, _seek: Option<f64>) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_stop(&self) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_seek(&self, _seek: f64) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_pause(&self) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_resume(&self) -> Result<(), PlayerError> {
                Ok(())
            }
            fn player_status(&self) -> Result<ApiPlaybackStatus, PlayerError> {
                Ok(ApiPlaybackStatus {
                    active_playbacks: None,
                })
            }
            fn get_source(&self) -> &PlayerSource {
                &PlayerSource::Local
            }
        }

        let shared_playback = Arc::new(std::sync::RwLock::new(Some(Playback::new(
            vec![create_test_track(1)],
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            None,
        ))));

        let handler = PlaybackHandler::new(MockPlayer).with_playback(shared_playback.clone());

        // Verify the playback was set
        assert!(handler.playback.read().unwrap().is_some());

        // Verify it's the same Arc (shared reference)
        assert!(Arc::ptr_eq(&handler.playback, &shared_playback));
    }

    #[test_log::test]
    fn test_playback_handler_with_output_sets_output() {
        #[derive(Debug)]
        struct MockPlayer;

        #[async_trait]
        impl Player for MockPlayer {
            async fn trigger_play(&self, _seek: Option<f64>) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_stop(&self) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_seek(&self, _seek: f64) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_pause(&self) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_resume(&self) -> Result<(), PlayerError> {
                Ok(())
            }
            fn player_status(&self) -> Result<ApiPlaybackStatus, PlayerError> {
                Ok(ApiPlaybackStatus {
                    active_playbacks: None,
                })
            }
            fn get_source(&self) -> &PlayerSource {
                &PlayerSource::Local
            }
        }

        let handler = PlaybackHandler::new(MockPlayer);
        assert!(handler.output.is_none());

        let output: Option<Arc<std::sync::Mutex<AudioOutputFactory>>> = None;
        let handler = handler.with_output(output);
        assert!(handler.output.is_none());
    }

    #[test_log::test(switchy_async::test)]
    async fn test_get_track_url_with_remote_source() {
        use moosicbox_music_api::models::TrackAudioQuality;

        let track_id = 42.into();
        let api_source = ApiSource::library();
        let player_source = PlayerSource::Remote {
            host: "http://example.com:8080".to_string(),
            query: None,
            headers: None,
        };
        let format = PlaybackQuality::default();
        let quality = TrackAudioQuality::Low;

        let (url, headers) = get_track_url(
            &track_id,
            &api_source,
            &player_source,
            format,
            quality,
            false,
        )
        .await
        .expect("Failed to get track URL");

        // Should construct a URL with the remote host
        assert!(url.starts_with("http://example.com:8080/files/track"));
        assert!(url.contains("trackId=42"));
        assert!(url.contains("quality=LOW"));
        // Headers should be None when not provided
        assert!(headers.is_none());
    }

    #[test_log::test(switchy_async::test)]
    async fn test_get_track_url_with_remote_source_and_query_params() {
        use moosicbox_music_api::models::TrackAudioQuality;

        let track_id = 123.into();
        let api_source = ApiSource::library();

        let mut query = std::collections::BTreeMap::new();
        query.insert("customParam".to_string(), "customValue".to_string());

        let player_source = PlayerSource::Remote {
            host: "http://music.local:9000".to_string(),
            query: Some(query),
            headers: None,
        };
        let format = PlaybackQuality::default();
        let quality = TrackAudioQuality::FlacHighestRes;

        let (url, _headers) = get_track_url(
            &track_id,
            &api_source,
            &player_source,
            format,
            quality,
            false,
        )
        .await
        .expect("Failed to get track URL");

        // Should include custom query params
        assert!(url.contains("customParam=customValue"));
        assert!(url.contains("trackId=123"));
        assert!(url.contains("quality=FLAC_HIGHEST_RES"));
    }

    #[test_log::test(switchy_async::test)]
    async fn test_get_track_url_with_remote_source_and_headers() {
        use moosicbox_music_api::models::TrackAudioQuality;

        let track_id = 456.into();
        let api_source = ApiSource::library();

        let mut headers = std::collections::BTreeMap::new();
        headers.insert("moosicbox-profile".to_string(), "test-profile".to_string());

        let player_source = PlayerSource::Remote {
            host: "http://remote.server".to_string(),
            query: None,
            headers: Some(headers),
        };
        let format = PlaybackQuality::default();
        let quality = TrackAudioQuality::Low;

        let (url, returned_headers) = get_track_url(
            &track_id,
            &api_source,
            &player_source,
            format,
            quality,
            false,
        )
        .await
        .expect("Failed to get track URL");

        // Headers should be returned
        assert!(returned_headers.is_some());
        let headers = returned_headers.unwrap();
        assert_eq!(
            headers.get("moosicbox-profile"),
            Some(&"test-profile".to_string())
        );

        // Profile should be included in URL when header is present
        assert!(url.contains("moosicboxProfile=test-profile"));
    }

    #[cfg(feature = "format-flac")]
    #[test_log::test(switchy_async::test)]
    async fn test_get_track_url_with_non_source_format() {
        use moosicbox_music_api::models::TrackAudioQuality;

        let track_id = 789.into();
        let api_source = ApiSource::library();
        let player_source = PlayerSource::Remote {
            host: "http://test.host".to_string(),
            query: None,
            headers: None,
        };
        let format = PlaybackQuality {
            format: moosicbox_music_models::AudioFormat::Flac,
        };
        let quality = TrackAudioQuality::Low;

        let (url, _headers) = get_track_url(
            &track_id,
            &api_source,
            &player_source,
            format,
            quality,
            false,
        )
        .await
        .expect("Failed to get track URL");

        // Should include format when not Source
        assert!(url.contains("format=FLAC"));
    }

    #[test_log::test(switchy_async::test)]
    async fn test_get_track_url_with_source_format_omits_format_param() {
        use moosicbox_music_api::models::TrackAudioQuality;

        let track_id = 111.into();
        let api_source = ApiSource::library();
        let player_source = PlayerSource::Remote {
            host: "http://test.host".to_string(),
            query: None,
            headers: None,
        };
        let format = PlaybackQuality {
            format: moosicbox_music_models::AudioFormat::Source,
        };
        let quality = TrackAudioQuality::Low;

        let (url, _headers) = get_track_url(
            &track_id,
            &api_source,
            &player_source,
            format,
            quality,
            false,
        )
        .await
        .expect("Failed to get track URL");

        // Should NOT include format when it's Source
        assert!(!url.contains("format="));
    }

    #[test_log::test(switchy_async::test)]
    async fn test_get_track_url_library_source_omits_source_param() {
        use moosicbox_music_api::models::TrackAudioQuality;

        let track_id = 222.into();
        let api_source = ApiSource::library();
        let player_source = PlayerSource::Remote {
            host: "http://test.host".to_string(),
            query: None,
            headers: None,
        };
        let format = PlaybackQuality::default();
        let quality = TrackAudioQuality::Low;

        let (url, _headers) = get_track_url(
            &track_id,
            &api_source,
            &player_source,
            format,
            quality,
            false,
        )
        .await
        .expect("Failed to get track URL");

        // Should NOT include source when it's library
        assert!(!url.contains("source="));
    }

    #[test_log::test(switchy_async::test)]
    async fn test_get_track_url_with_local_source() {
        use moosicbox_music_api::models::TrackAudioQuality;

        // Set up SERVICE_PORT for local source
        set_service_port(8765);

        let track_id = 333.into();
        let api_source = ApiSource::library();
        let player_source = PlayerSource::Local;
        let format = PlaybackQuality::default();
        let quality = TrackAudioQuality::FlacLossless;

        let (url, headers) = get_track_url(
            &track_id,
            &api_source,
            &player_source,
            format,
            quality,
            false,
        )
        .await
        .expect("Failed to get track URL");

        // Should use local IP and configured port
        assert!(url.starts_with("http://127.0.0.1:8765/files/track"));
        assert!(url.contains("trackId=333"));
        assert!(url.contains("quality=FLAC_LOSSLESS"));
        // Headers should be None for local source
        assert!(headers.is_none());
    }

    #[test_log::test]
    fn test_on_playback_event_registers_listener() {
        use std::sync::atomic::AtomicBool;

        // Define the listener function first (before any statements)
        fn test_listener(_update: &UpdateSession, _playback: &Playback) {
            static LISTENER_CALLED: AtomicBool = AtomicBool::new(false);
            LISTENER_CALLED.store(true, std::sync::atomic::Ordering::SeqCst);
        }

        on_playback_event(test_listener);

        // Create playback with a target (required for events to fire)
        let tracks = vec![create_test_track(1)];
        let mut playback1 = Playback::new(
            tracks,
            Some(0),
            AtomicF64::new(1.0),
            PlaybackQuality::default(),
            1,
            "test".to_string(),
            Some(PlaybackTarget::AudioZone { audio_zone_id: 1 }),
        );
        playback1.playing = false;

        let mut playback2 = playback1.clone();
        playback2.playing = true;

        // Trigger event which should call our registered listener
        trigger_playback_event(&playback2, &playback1);

        // The listener was registered and can be called - this test verifies registration works
    }

    #[test_log::test]
    fn test_send_playback_event_calls_all_registered_listeners() {
        // Define the listener function first (before any statements)
        fn counter_listener(_update: &UpdateSession, _playback: &Playback) {
            // This function is registered as a listener
        }

        // Note: Since PLAYBACK_EVENT_LISTENERS is global and we can't easily clear it,
        // we just verify that registering and calling works. The call count will include
        // any previously registered listeners from other tests.
        let initial_count = PLAYBACK_EVENT_LISTENERS.read().unwrap().len();

        on_playback_event(counter_listener);

        // Verify registration increased the count
        assert_eq!(
            PLAYBACK_EVENT_LISTENERS.read().unwrap().len(),
            initial_count + 1
        );
    }

    #[test_log::test]
    fn test_playback_handler_new_boxed() {
        #[derive(Debug)]
        struct TestPlayer;

        #[async_trait]
        impl Player for TestPlayer {
            async fn trigger_play(&self, _seek: Option<f64>) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_stop(&self) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_seek(&self, _seek: f64) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_pause(&self) -> Result<(), PlayerError> {
                Ok(())
            }
            async fn trigger_resume(&self) -> Result<(), PlayerError> {
                Ok(())
            }
            fn player_status(&self) -> Result<ApiPlaybackStatus, PlayerError> {
                Ok(ApiPlaybackStatus {
                    active_playbacks: None,
                })
            }
            fn get_source(&self) -> &PlayerSource {
                &PlayerSource::Local
            }
        }

        let boxed_player: Box<dyn Player + Sync> = Box::new(TestPlayer);
        let handler = PlaybackHandler::new_boxed(boxed_player);

        // Verify it was created correctly
        assert!(handler.playback.read().unwrap().is_none());
        assert!(handler.output.is_none());

        // Verify player_status works through the handler
        let status = handler
            .player
            .player_status()
            .expect("Failed to get status");
        assert!(status.active_playbacks.is_none());
    }
}