File size: 119,044 Bytes
73859e0
8be3a16
8be0db8
 
8be3a16
8be0db8
8be3a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73859e0
 
 
 
 
8be0db8
259cc67
2640355
73859e0
 
 
8be3a16
 
73859e0
 
259cc67
73859e0
 
259cc67
78e796e
259cc67
73859e0
 
8be0db8
259cc67
 
 
a3f95cd
8be0db8
356bdae
2640355
8be3a16
259cc67
 
 
 
 
 
 
8be3a16
259cc67
 
8be3a16
2640355
 
8be3a16
 
 
 
 
 
 
2640355
259cc67
2640355
 
 
 
 
 
259cc67
8be3a16
8be0db8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2640355
259cc67
8be3a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259cc67
 
8be0db8
 
 
259cc67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be0db8
259cc67
 
8be3a16
 
 
 
259cc67
 
8be3a16
259cc67
 
 
8be3a16
259cc67
 
 
 
 
 
 
 
8be0db8
8be3a16
 
 
259cc67
 
 
8be0db8
259cc67
8be0db8
259cc67
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
 
 
 
 
 
259cc67
 
8be3a16
 
 
259cc67
 
8be0db8
 
 
 
 
 
78e796e
 
8be3a16
 
78e796e
 
 
 
 
 
8be3a16
259cc67
 
78e796e
259cc67
78e796e
8be3a16
259cc67
 
8be3a16
78e796e
8be3a16
 
78e796e
8be3a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259cc67
 
 
 
8be0db8
259cc67
 
8be0db8
259cc67
 
 
 
8be3a16
 
 
259cc67
8be3a16
259cc67
8be3a16
 
 
 
259cc67
 
73859e0
 
 
 
 
 
 
8be3a16
73859e0
8be3a16
 
73859e0
8be3a16
259cc67
73859e0
 
259cc67
 
8be3a16
8be0db8
73859e0
 
 
 
8be0db8
73859e0
 
 
8be3a16
8be0db8
73859e0
 
 
8be0db8
 
a3f95cd
 
 
8be0db8
 
73859e0
 
8be0db8
73859e0
 
259cc67
 
73859e0
8be0db8
73859e0
 
 
 
 
 
 
 
 
8be0db8
73859e0
 
 
 
 
78e796e
73859e0
6d4bc9f
 
73859e0
 
78e796e
6d4bc9f
 
73859e0
 
 
 
8be3a16
73859e0
 
 
8be0db8
73859e0
 
259cc67
73859e0
8be3a16
8be0db8
73859e0
 
259cc67
73859e0
 
 
259cc67
 
 
73859e0
 
 
 
 
 
 
 
 
 
 
 
 
 
8be0db8
73859e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
 
73859e0
8be3a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73859e0
 
8be3a16
73859e0
 
8be3a16
 
73859e0
8be3a16
 
 
 
 
73859e0
8be3a16
 
 
 
73859e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be0db8
73859e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be0db8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259cc67
8be3a16
 
259cc67
 
 
 
8be0db8
8be3a16
259cc67
8be3a16
259cc67
8be3a16
f32ea6a
8be3a16
259cc67
8be3a16
 
259cc67
8be0db8
 
 
 
259cc67
 
 
 
 
 
 
 
 
 
8be0db8
 
 
 
259cc67
8be3a16
259cc67
8be3a16
259cc67
 
 
8be3a16
 
8be0db8
 
 
 
 
8be3a16
f32ea6a
8be0db8
8be3a16
 
8be0db8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
259cc67
 
8be3a16
 
 
259cc67
 
8be0db8
259cc67
8be3a16
259cc67
8be3a16
259cc67
8be3a16
 
 
 
 
259cc67
 
 
8be0db8
8be3a16
 
 
259cc67
 
 
 
 
 
8be0db8
259cc67
 
 
8be0db8
259cc67
8be0db8
259cc67
 
 
8be3a16
 
8be0db8
 
8be3a16
 
 
 
 
8be0db8
8be3a16
 
 
 
8be0db8
 
 
 
 
 
 
 
8be3a16
 
 
 
8be0db8
259cc67
 
8be3a16
 
259cc67
 
 
8be0db8
8be3a16
259cc67
 
 
8be3a16
 
259cc67
 
8be0db8
 
259cc67
 
 
 
8be0db8
259cc67
 
 
 
 
 
8be3a16
259cc67
 
 
8be0db8
 
259cc67
 
 
8be3a16
 
 
 
 
259cc67
 
 
 
8be0db8
259cc67
 
 
 
 
8be0db8
259cc67
 
 
 
 
 
8be3a16
8be0db8
 
8be3a16
 
 
8be0db8
31fda9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be0db8
 
31fda9b
 
 
 
 
 
 
8be3a16
 
31fda9b
 
 
8be0db8
8be3a16
 
 
 
 
 
 
 
 
8be0db8
8be3a16
 
31fda9b
 
 
 
8be0db8
31fda9b
8be3a16
 
 
 
31fda9b
 
 
 
 
 
 
 
 
 
8be3a16
31fda9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be0db8
 
8be3a16
 
78e796e
 
8be3a16
78e796e
31fda9b
8be3a16
31fda9b
 
 
8be3a16
31fda9b
 
8be3a16
31fda9b
8be0db8
31fda9b
8be3a16
31fda9b
8be3a16
 
31fda9b
8be0db8
31fda9b
 
 
8be3a16
 
31fda9b
8be3a16
31fda9b
8be3a16
 
 
 
 
31fda9b
8be3a16
 
 
 
31fda9b
 
 
 
 
 
8be3a16
 
31fda9b
 
8be3a16
31fda9b
8be3a16
 
 
31fda9b
 
8be3a16
 
 
31fda9b
 
 
 
8be3a16
 
 
 
 
 
 
 
 
 
 
 
31fda9b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
 
 
 
 
31fda9b
8be0db8
8be3a16
 
 
259cc67
73859e0
 
8be3a16
73859e0
 
 
 
 
 
8be3a16
73859e0
 
8be3a16
 
 
 
 
 
 
 
 
 
 
 
 
259cc67
8be3a16
 
 
259cc67
8be3a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73859e0
8be3a16
73859e0
8be3a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73859e0
8be3a16
 
 
73859e0
8be3a16
 
 
 
 
8be0db8
 
8be3a16
8be0db8
8be3a16
 
8be0db8
 
 
 
8be3a16
 
 
 
8be0db8
8be3a16
 
 
 
 
 
 
 
 
 
 
8be0db8
8be3a16
 
 
 
 
 
 
 
 
73859e0
 
259cc67
8be3a16
 
 
 
 
 
 
8be0db8
 
8be3a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be0db8
259cc67
8be3a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259cc67
73859e0
8be0db8
73859e0
 
a3f95cd
 
8be3a16
a3f95cd
 
73859e0
 
259cc67
73859e0
8be3a16
 
 
 
 
 
259cc67
8be3a16
 
 
 
259cc67
8be3a16
 
 
 
259cc67
8be0db8
 
259cc67
 
73859e0
 
 
 
 
259cc67
73859e0
259cc67
 
 
 
8be3a16
259cc67
 
8be3a16
 
 
 
259cc67
 
73859e0
 
 
 
 
259cc67
 
 
 
 
 
 
 
 
 
 
8be3a16
259cc67
 
73859e0
 
 
 
8be0db8
259cc67
73859e0
259cc67
73859e0
259cc67
 
 
 
 
73859e0
259cc67
 
73859e0
 
 
 
 
 
259cc67
 
73859e0
 
 
 
 
 
 
259cc67
73859e0
259cc67
8be3a16
73859e0
 
8be0db8
 
73859e0
 
8be0db8
259cc67
73859e0
259cc67
73859e0
 
8be0db8
a3f95cd
73859e0
 
8be0db8
73859e0
 
8be0db8
73859e0
 
8be0db8
 
 
 
73859e0
8be3a16
73859e0
 
 
8be0db8
73859e0
 
8be0db8
259cc67
8be0db8
 
 
 
 
 
73859e0
8be0db8
 
73859e0
8be0db8
73859e0
8be0db8
73859e0
8be0db8
 
8be3a16
 
8be0db8
 
8be3a16
8be0db8
8be3a16
 
 
 
 
8be0db8
8be3a16
 
 
8be0db8
 
 
 
73859e0
 
8be3a16
73859e0
 
8be0db8
 
 
 
 
8be3a16
 
 
73859e0
8be0db8
8be3a16
 
 
8be0db8
8be3a16
 
73859e0
8be3a16
73859e0
 
8be3a16
 
 
 
 
 
 
73859e0
8be3a16
 
 
 
 
 
73859e0
8be3a16
8be0db8
73859e0
 
8be3a16
73859e0
 
8be0db8
 
 
 
 
 
 
 
8be3a16
73859e0
8be3a16
 
 
 
 
 
73859e0
8be3a16
 
 
 
 
8be0db8
8be3a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be0db8
8be3a16
 
 
8be0db8
8be3a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be0db8
8be3a16
 
 
8be0db8
73859e0
 
8be0db8
73859e0
 
8be0db8
259cc67
8be0db8
 
 
 
 
 
 
8be3a16
8be0db8
8be3a16
8be0db8
 
 
 
 
8be3a16
 
8be0db8
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
8be0db8
 
 
 
 
 
8be3a16
8be0db8
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
8be0db8
8be3a16
8be0db8
 
 
 
8be3a16
 
8be0db8
 
 
8be3a16
8be0db8
 
8be3a16
8be0db8
8be3a16
259cc67
73859e0
8be3a16
8be0db8
73859e0
8be3a16
 
 
 
 
73859e0
8be3a16
73859e0
8be3a16
78e796e
8be0db8
8be3a16
 
8be0db8
73859e0
 
 
 
 
8be0db8
259cc67
a3f95cd
 
 
 
 
 
 
73859e0
 
 
8be3a16
73859e0
 
a3f95cd
73859e0
 
 
 
 
 
 
 
8be3a16
73859e0
 
8be3a16
73859e0
 
 
8be0db8
259cc67
a3f95cd
 
 
 
 
 
 
73859e0
 
 
8be3a16
73859e0
 
a3f95cd
73859e0
 
 
8be0db8
 
 
73859e0
 
 
8be0db8
 
 
73859e0
 
 
 
 
 
 
 
 
 
 
8be3a16
73859e0
 
 
 
8be3a16
73859e0
 
 
8be0db8
259cc67
73859e0
259cc67
73859e0
 
 
 
 
 
 
 
 
8be3a16
73859e0
 
 
 
 
 
 
 
 
 
 
8be0db8
 
 
 
73859e0
 
8be0db8
 
73859e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
 
73859e0
 
 
8be0db8
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
8be0db8
 
 
 
 
 
 
 
8be3a16
 
8be0db8
 
8be3a16
8be0db8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
8be0db8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
8be0db8
 
 
 
 
 
 
 
8be3a16
8be0db8
 
 
 
8be3a16
8be0db8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
8be0db8
8be3a16
8be0db8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
8be0db8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
 
 
 
8be0db8
 
 
 
 
 
 
 
8be3a16
 
 
 
 
 
8be0db8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73859e0
8be0db8
 
73859e0
8be3a16
73859e0
 
 
8be0db8
73859e0
 
8be0db8
259cc67
8be0db8
 
 
 
 
 
73859e0
8be0db8
 
 
8be3a16
8be0db8
73859e0
8be0db8
 
 
 
 
 
 
8be3a16
8be0db8
 
 
73859e0
8be3a16
73859e0
 
 
 
 
 
8be0db8
259cc67
73859e0
259cc67
73859e0
 
 
 
 
a3f95cd
73859e0
 
 
a3f95cd
73859e0
 
 
 
 
 
a3f95cd
73859e0
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
73859e0
 
 
 
 
 
8be0db8
259cc67
73859e0
259cc67
73859e0
 
 
a3f95cd
73859e0
 
8be0db8
 
 
a3f95cd
73859e0
 
8be3a16
73859e0
 
a3f95cd
73859e0
 
 
 
8be3a16
73859e0
8be3a16
73859e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be0db8
73859e0
 
 
 
 
 
 
 
 
 
 
8be3a16
 
 
73859e0
8be3a16
 
 
 
 
 
 
 
73859e0
 
8be3a16
 
 
 
 
 
 
 
 
 
73859e0
8be3a16
 
73859e0
 
 
8be3a16
73859e0
 
8be3a16
259cc67
73859e0
8be3a16
 
 
 
 
 
73859e0
8be3a16
 
 
 
 
73859e0
8be3a16
 
 
 
 
 
 
 
 
 
 
 
 
73859e0
8be3a16
73859e0
 
 
8be3a16
 
a3f95cd
8be3a16
8be0db8
a3f95cd
8be0db8
 
a3f95cd
8be3a16
73859e0
 
8be3a16
73859e0
 
a3f95cd
8be3a16
 
 
73859e0
8be3a16
73859e0
 
 
8be3a16
73859e0
 
8be3a16
259cc67
8be3a16
259cc67
73859e0
 
 
8be3a16
73859e0
8be3a16
259cc67
73859e0
 
 
 
8be3a16
 
8be0db8
8be3a16
 
 
8be0db8
8be3a16
 
 
8be0db8
73859e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
259cc67
73859e0
 
259cc67
8be3a16
259cc67
 
 
 
 
 
 
 
 
 
 
8be3a16
259cc67
 
 
 
 
73859e0
259cc67
 
 
 
 
 
 
 
 
 
 
 
 
73859e0
8be0db8
 
259cc67
73859e0
 
 
 
259cc67
 
73859e0
 
 
 
 
 
 
8be0db8
73859e0
 
8be0db8
259cc67
73859e0
259cc67
73859e0
 
 
 
 
 
 
 
 
 
259cc67
 
 
 
8be0db8
259cc67
 
 
 
 
 
 
 
 
 
 
73859e0
 
 
 
8be3a16
73859e0
 
 
8be0db8
259cc67
73859e0
259cc67
73859e0
 
 
 
 
 
 
 
 
 
 
 
8be0db8
73859e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
73859e0
 
 
259cc67
73859e0
 
8be0db8
259cc67
73859e0
259cc67
73859e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8be3a16
73859e0
 
 
8be0db8
73859e0
 
8be0db8
73859e0
 
 
a3f95cd
73859e0
 
a3f95cd
73859e0
 
 
 
a3f95cd
73859e0
 
 
8be3a16
73859e0
 
 
8be0db8
73859e0
 
 
 
a3f95cd
73859e0
 
 
a3f95cd
73859e0
 
8be3a16
73859e0
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
"""
Musicanaz Backend API β€” v9  (HuggingFace Spaces Β· 16 GB RAM Β· 2 vCPU)
=======================================================================

CHANGES IN v9
─────────────────────────────────────────────────────────────────────
REMOVED
  β€’ Download feature (yt-dlp / download_bp.py) β€” fully stripped
  β€’ Last.fm β€” removed; it requires a paid plan for geo charts

ADDED β€” FREE TRENDING SOURCE
  β€’ Spotify Web API (Client Credentials, 100% free, no card needed)
      – Featured playlists + top tracks by country
      – Set SPOTIFY_CLIENT_ID + SPOTIFY_CLIENT_SECRET env vars
      – Token auto-refreshed every hour; falls back gracefully if unset
      – New endpoint: GET /spotify/trending?country=IN&limit=50

10-HOUR CHARTS & TRENDING CACHE
  β€’ _cache_charts: dedicated TTLCache (TTL = 36 000 s / 10 h)
  β€’ On first request for a new country β†’ fetch + cache
  β€’ All subsequent requests for that country β†’ served from cache instantly
  β€’ Disk write-through (diskcache) β†’ survives across uvicorn worker
    restarts within the same OS process
  β€’ Per-country asyncio.Lock prevents thundering-herd: if 50 users
    request "IN" charts simultaneously, only ONE fetch fires; the rest
    wait for the result

APPLE MUSIC PROXY
  β€’ Dedicated `_get_apple_client()` always routes through proxy
    (when PROXY_USERNAME / PROXY_PASSWORD are set)

SESSION / CONCURRENCY SAFETY
  β€’ Per-country asyncio.Lock (charts + trending separately)
  β€’ Global Semaphore caps concurrent external fetches to 20
  β€’ ThreadPoolExecutor stays at 8 workers (2 vCPU, I/O-bound YTM calls)
  β€’ All mutable shared state protected by threading.Lock or asyncio.Lock

LOGGING
  β€’ RequestIDMiddleware tags every request with a short UUID prefix
  β€’ Each external fetch logs source, country, count, latency
  β€’ HTTPException handler logs path + status + detail
  β€’ Full tracebacks logged at DEBUG level for unexpected exceptions
  β€’ Structured format:  HH:MM:SS  LEVEL  [req-id] message
"""

from __future__ import annotations

import asyncio
import base64
import logging
import os
import re
import time
import threading
import traceback
import uuid
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from contextlib import asynccontextmanager
from typing import Any, Dict, List, Optional

import diskcache
from curl_cffi import requests as cffi_requests
from fastapi import FastAPI, HTTPException, Query, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.responses import JSONResponse
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.errors import RateLimitExceeded
from slowapi.util import get_remote_address
from starlette.middleware.base import BaseHTTPMiddleware
from ytmusicapi import YTMusic

# ─────────────────────────────────────────────────────────────────────────────
#  Logging  β€” request-ID aware
# ─────────────────────────────────────────────────────────────────────────────

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s  %(levelname)-8s  %(message)s",
    datefmt="%H:%M:%S",
)
log = logging.getLogger("musicanaz")

# ─────────────────────────────────────────────────────────────────────────────
#  Environment / proxy config
# ─────────────────────────────────────────────────────────────────────────────

_PROXY_HOST          = "p.webshare.io"
_PROXY_PORT          = "80"
_PROXY_USER          = os.environ.get("PROXY_USERNAME", "")
_PROXY_PASS          = os.environ.get("PROXY_PASSWORD", "")
_SPOTIFY_CLIENT_ID   = os.environ.get("SPOTIFY_CLIENT_ID", "")
_SPOTIFY_CLIENT_SECRET = os.environ.get("SPOTIFY_CLIENT_SECRET", "")
DOCS_PASSWORD        = os.environ.get("DOCS_PASSWORD", "prakamya05")


def _build_proxies() -> dict | None:
    if not _PROXY_USER or not _PROXY_PASS:
        return None
    proxy_url = f"http://{_PROXY_USER}:{_PROXY_PASS}@{_PROXY_HOST}:{_PROXY_PORT}"
    return {"http": proxy_url, "https": proxy_url}


_PROXIES  = _build_proxies()
_PROXY_URL = (
    f"http://{_PROXY_USER}:{_PROXY_PASS}@{_PROXY_HOST}:{_PROXY_PORT}"
    if _PROXY_USER and _PROXY_PASS else None
)

# ─────────────────────────────────────────────────────────────────────────────
#  Docs Auth Middleware
# ─────────────────────────────────────────────────────────────────────────────

class DocsAuthMiddleware(BaseHTTPMiddleware):
    async def dispatch(self, request: Request, call_next):
        if request.url.path in ("/docs", "/openapi.json", "/redoc"):
            auth = request.headers.get("Authorization", "")
            if auth.startswith("Basic "):
                try:
                    decoded  = base64.b64decode(auth[6:]).decode()
                    _, password = decoded.split(":", 1)
                    if password == DOCS_PASSWORD:
                        return await call_next(request)
                except Exception:
                    pass
            return Response(
                "Unauthorized", status_code=401,
                headers={"WWW-Authenticate": 'Basic realm="Musicanaz Docs"'},
            )
        return await call_next(request)

# ─────────────────────────────────────────────────────────────────────────────
#  Request-ID Middleware  β€” adds X-Request-ID header + per-request log line
# ─────────────────────────────────────────────────────────────────────────────

class RequestIDMiddleware(BaseHTTPMiddleware):
    """Stamps every request with a short ID; logs method / path / status / ms."""
    async def dispatch(self, request: Request, call_next):
        rid = uuid.uuid4().hex[:8]
        request.state.request_id = rid
        t0 = time.monotonic()
        try:
            response = await call_next(request)
        except Exception as exc:
            elapsed = (time.monotonic() - t0) * 1000
            log.error("[%s] %s %s β†’ 500 (%.1f ms) β€” unhandled: %s",
                      rid, request.method, request.url.path, elapsed, exc)
            log.debug("[%s] traceback:\n%s", rid, traceback.format_exc())
            raise
        elapsed = (time.monotonic() - t0) * 1000
        lvl = logging.WARNING if response.status_code >= 400 else logging.INFO
        log.log(lvl, "[%s] %s %s β†’ %d (%.1f ms)",
                rid, request.method, request.url.path,
                response.status_code, elapsed)
        response.headers["X-Request-ID"] = rid
        return response

# ─────────────────────────────────────────────────────────────────────────────
#  Circuit breaker  (per external source)
# ─────────────────────────────────────────────────────────────────────────────

_CB_THRESHOLD  = 5
_CB_RESET_SECS = 60


class CircuitBreaker:
    def __init__(self, name: str):
        self.name       = name
        self._failures  = 0
        self._opened_at = 0.0
        self._lock      = threading.Lock()

    @property
    def available(self) -> bool:
        with self._lock:
            if self._failures < _CB_THRESHOLD:
                return True
            if time.monotonic() - self._opened_at > _CB_RESET_SECS:
                return True
            return False

    def success(self):
        with self._lock:
            self._failures  = 0
            self._opened_at = 0.0

    def failure(self):
        with self._lock:
            self._failures += 1
            if self._failures >= _CB_THRESHOLD:
                self._opened_at = time.monotonic()
                log.warning("Circuit breaker OPEN: %s", self.name)


_cb_ytm     = CircuitBreaker("ytmusicapi")
_cb_itunes  = CircuitBreaker("itunes")
_cb_deezer  = CircuitBreaker("deezer")
_cb_spotify = CircuitBreaker("spotify")

# ─────────────────────────────────────────────────────────────────────────────
#  Two-level cache  (L1 in-memory LRU + L2 disk)
# ─────────────────────────────────────────────────────────────────────────────

_DISK_CACHE_DIR  = os.environ.get("CACHE_DIR", "/tmp/ytm_cache")
_DISK_CACHE_SIZE = 600 * 1024 * 1024   # 600 MB (16 GB headroom)

_disk_cache = diskcache.Cache(
    _DISK_CACHE_DIR,
    size_limit=_DISK_CACHE_SIZE,
    eviction_policy="least-recently-used",
    statistics=True,
)

_DISK_TTL_SHORT  = 300
_DISK_TTL_MEDIUM = 1_800
_DISK_TTL_LONG   = 21_600
_DISK_TTL_CHARTS = 36_000   # 10 h β€” matches in-memory chart TTL


class TTLCache:
    """Thread-safe LRU in-memory cache with per-entry TTL + disk write-through."""

    def __init__(self, maxsize: int = 256, ttl: int = 300, disk_ttl: int = 0):
        self._store:   OrderedDict[str, tuple[Any, float]] = OrderedDict()
        self._maxsize  = maxsize
        self._ttl      = ttl
        self._disk_ttl = disk_ttl
        self._lock     = threading.Lock()

    def get(self, key: str) -> Any:
        with self._lock:
            if key in self._store:
                value, expires = self._store[key]
                if time.monotonic() <= expires:
                    self._store.move_to_end(key)
                    return value
                del self._store[key]
        if self._disk_ttl:
            try:
                value = _disk_cache.get(key)
                if value is not None:
                    self.set(key, value)
                    return value
            except Exception:
                pass
        return None

    def set(self, key: str, value: Any, ttl: int | None = None) -> None:
        mem_ttl = ttl or self._ttl
        with self._lock:
            if key in self._store:
                self._store.move_to_end(key)
            self._store[key] = (value, time.monotonic() + mem_ttl)
            while len(self._store) > self._maxsize:
                self._store.popitem(last=False)
        if self._disk_ttl:
            try:
                _disk_cache.set(key, value, expire=self._disk_ttl)
            except Exception:
                pass

    def delete(self, key: str) -> None:
        with self._lock:
            self._store.pop(key, None)
        try:
            _disk_cache.delete(key)
        except Exception:
            pass

    def __len__(self) -> int:
        with self._lock:
            return len(self._store)


# 16 GB optimised β€” generous sizes
_cache_short  = TTLCache(maxsize=192,  ttl=120,    disk_ttl=_DISK_TTL_SHORT)
_cache_medium = TTLCache(maxsize=288,  ttl=600,    disk_ttl=_DISK_TTL_MEDIUM)
_cache_long   = TTLCache(maxsize=480,  ttl=3_600,  disk_ttl=_DISK_TTL_LONG)
#  ↓ Charts & trending: one fetch per country every 10 hours
_cache_charts = TTLCache(maxsize=500,  ttl=36_000, disk_ttl=_DISK_TTL_CHARTS)

# ─────────────────────────────────────────────────────────────────────────────
#  Shared async HTTP clients
#  β€’ _get_http_client()   β€” general purpose (uses proxy when configured)
#  β€’ _get_apple_client()  β€” Apple Music RSS; explicitly routes via proxy
# ─────────────────────────────────────────────────────────────────────────────

_BROWSER_UA = (
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
    "AppleWebKit/537.36 (KHTML, like Gecko) "
    "Chrome/124.0.0.0 Safari/537.36"
)

_http_client:  cffi_requests.AsyncSession | None = None
_apple_client: cffi_requests.AsyncSession | None = None


def _make_client(proxy: str | None = None) -> cffi_requests.AsyncSession:
    proxies = {"http": proxy, "https": proxy} if proxy else None
    return cffi_requests.AsyncSession(
        impersonate="chrome",
        timeout=20.0,
        proxies=proxies,
    )


def _get_http_client() -> cffi_requests.AsyncSession:
    global _http_client
    if _http_client is None or getattr(_http_client, "_closed", False):
        _http_client = _make_client(_PROXY_URL)
    return _http_client


def _get_apple_client() -> cffi_requests.AsyncSession:
    """Always routes through proxy (when configured) for Apple Music RSS."""
    global _apple_client
    if _apple_client is None or getattr(_apple_client, "_closed", False):
        _apple_client = _make_client(_PROXY_URL)   # proxy if set, plain if not
    return _apple_client

# ─────────────────────────────────────────────────────────────────────────────
#  Global concurrency gate β€” caps simultaneous outbound fetches
# ─────────────────────────────────────────────────────────────────────────────

# Created lazily in async context (needs a running event loop)
_fetch_semaphore: asyncio.Semaphore | None = None


def _get_semaphore() -> asyncio.Semaphore:
    global _fetch_semaphore
    if _fetch_semaphore is None:
        _fetch_semaphore = asyncio.Semaphore(20)
    return _fetch_semaphore

# ─────────────────────────────────────────────────────────────────────────────
#  Per-country fetch locks β€” prevents thundering herd on cache miss
#  One lock dict for charts, one for trending (they fetch independently)
# ─────────────────────────────────────────────────────────────────────────────

_chart_locks:    Dict[str, asyncio.Lock] = {}
_trending_locks: Dict[str, asyncio.Lock] = {}


def _chart_lock(country: str) -> asyncio.Lock:
    key = country.upper()
    if key not in _chart_locks:
        _chart_locks[key] = asyncio.Lock()
    return _chart_locks[key]


def _trending_lock(country: str) -> asyncio.Lock:
    key = country.upper()
    if key not in _trending_locks:
        _trending_locks[key] = asyncio.Lock()
    return _trending_locks[key]

# ─────────────────────────────────────────────────────────────────────────────
#  Rate limiter
# ─────────────────────────────────────────────────────────────────────────────

limiter = Limiter(key_func=get_remote_address, default_limits=["300/minute"])

# ─────────────────────────────────────────────────────────────────────────────
#  Lifespan
# ─────────────────────────────────────────────────────────────────────────────

@asynccontextmanager
async def lifespan(app: FastAPI):
    log.info("═══ Musicanaz API v9 starting ═══")
    log.info("Proxy: %s", "enabled" if _PROXY_URL else "disabled")
    log.info("Spotify: %s", "configured" if _SPOTIFY_CLIENT_ID else "not configured")
    asyncio.create_task(_background_warmup())
    asyncio.create_task(_auto_refresh_charts())
    yield
    log.info("═══ Musicanaz API v9 shutting down ═══")
    for client in (_http_client, _apple_client):
        if client and not client.is_closed:
            await client.aclose()
    _disk_cache.close()

# ─────────────────────────────────────────────────────────────────────────────
#  App
# ─────────────────────────────────────────────────────────────────────────────

_START_TIME = time.monotonic()

app = FastAPI(
    title="Musicanaz API β€” v9",
    description=(
        "ytmusicapi + Apple Music + Deezer + Spotify. "
        "Per-country 10-hour chart cache. 2-vCPU / 16 GB optimised."
    ),
    version="9.0.0",
    lifespan=lifespan,
)

app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
app.add_middleware(RequestIDMiddleware)
app.add_middleware(DocsAuthMiddleware)
app.add_middleware(GZipMiddleware, minimum_size=300)
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["GET", "POST", "DELETE"],
    allow_headers=["*"],
)

# 8 workers β€” 2 vCPU, ytmusicapi is I/O-bound
_executor = ThreadPoolExecutor(max_workers=8)


async def run(fn, *args, **kwargs):
    loop = asyncio.get_running_loop()
    def _safe():
        try:
            return fn(*args, **kwargs)
        except StopIteration as exc:
            raise RuntimeError(f"ytmusicapi StopIteration: {exc}") from exc
    return await loop.run_in_executor(_executor, _safe)

# ─────────────────────────────────────────────────────────────────────────────
#  Per-locale YTMusic instance pool  (LRU, capped at 20)
# ─────────────────────────────────────────────────────────────────────────────

_ytm_pool:    Dict[str, YTMusic] = {}
_ytm_pool_od: OrderedDict        = OrderedDict()
_ytm_lock     = threading.Lock()
_YTM_POOL_MAX = 20


def get_ytm(country: str = "ZZ", language: str = "en") -> YTMusic:
    country  = (country  or "ZZ").upper().strip()
    language = (language or "en").lower().strip()
    key = f"{country}:{language}"

    with _ytm_lock:
        if key in _ytm_pool:
            _ytm_pool_od.move_to_end(key, last=True)
            return _ytm_pool[key]
        if len(_ytm_pool) >= _YTM_POOL_MAX:
            oldest_key, _ = _ytm_pool_od.popitem(last=False)
            _ytm_pool.pop(oldest_key, None)
        try:
            session = cffi_requests.Session(impersonate="chrome", proxies=_PROXIES)
            location = country if country != "ZZ" else ""
            instance = YTMusic(language=language, location=location)
            instance._session = session
        except Exception:
            try:
                session = cffi_requests.Session(impersonate="chrome", proxies=_PROXIES)
                instance = YTMusic()
                instance._session = session
            except Exception as exc:
                raise RuntimeError(f"YTMusic init failed: {exc}") from exc
        _ytm_pool[key]    = instance
        _ytm_pool_od[key] = True
        log.info("YTMusic instance created: locale=%s", key)
        return instance

# ─────────────────────────────────────────────────────────────────────────────
#  Up-Next store
# ─────────────────────────────────────────────────────────────────────────────

_upnext_store: OrderedDict[str, Dict] = OrderedDict()
_upnext_lock  = threading.Lock()
_UPNEXT_TTL   = 7_200
_UPNEXT_MAX   = 100

# ─────────────────────────────────────────────────────────────────────────────
#  Thumbnail helpers
# ─────────────────────────────────────────────────────────────────────────────

_YT_QUALITY_RANK: Dict[str, int] = {
    "maxresdefault": 100, "sddefault": 70, "0": 65,
    "hqdefault": 50,      "mqdefault": 30, "2": 20,
    "1": 15,              "3": 10,         "default": 5,
}
_LH3_SIZE_RE = re.compile(r"=(w\d+(-h\d+)?|h\d+|s\d+)(-[a-zA-Z0-9_\-]*)*$")


def upgrade_thumbnail_url(url: str) -> str:
    if not url:
        return url
    try:
        if "lh3.googleusercontent.com" in url:
            url = _LH3_SIZE_RE.sub("", url)
            return url + "=w576-h576-l90-rj"
        if "i.ytimg.com/vi/" in url:
            url = re.sub(
                r"/(maxresdefault|sddefault|hqdefault|mqdefault|default|[0-3])\.jpg",
                "/maxresdefault.jpg", url,
            )
            return url
    except Exception:
        pass
    return url


def _thumb_score(t: Any) -> int:
    if isinstance(t, str):
        url, w, h = t, 0, 0
    else:
        url = t.get("url", "")
        w   = int(t.get("width",  0) or 0)
        h   = int(t.get("height", 0) or 0)
    if w > 0 and h > 0:
        return w * h
    m = re.search(r"=w(\d+)", url)
    if m:
        side = int(m.group(1))
        return side * side
    try:
        fname = url.rsplit("/", 1)[-1].split("?")[0].split(".")[0]
        rank  = _YT_QUALITY_RANK.get(fname)
        if rank:
            return rank * 10_000
    except Exception:
        pass
    return 0


def best_thumbnails_list(raw: Any) -> list:
    if not raw:
        return []
    if isinstance(raw, str):
        raw = [{"url": raw, "width": 0, "height": 0}]
    if isinstance(raw, dict):
        raw = [raw]
    if not isinstance(raw, list):
        return []
    cleaned = []
    for t in raw:
        if isinstance(t, str):
            t = {"url": t, "width": 0, "height": 0}
        url = t.get("url", "") if isinstance(t, dict) else ""
        if not url:
            continue
        upgraded = upgrade_thumbnail_url(url)
        cleaned.append({
            "url":    upgraded,
            "width":  int(t.get("width",  0) or 0),
            "height": int(t.get("height", 0) or 0),
        })
    if not cleaned:
        return []
    cleaned.sort(key=_thumb_score, reverse=True)
    return cleaned

# ─────────────────────────────────────────────────────────────────────────────
#  Normalizers
# ─────────────────────────────────────────────────────────────────────────────

def _norm_artists(raw: Any) -> list:
    if not raw:
        return []
    if isinstance(raw, str):
        return [{"name": raw, "id": ""}]
    if isinstance(raw, dict):
        return [{"name": raw.get("name", "") or raw.get("artist", ""), "id": raw.get("id", "")}]
    if isinstance(raw, list):
        out = []
        for a in raw:
            if isinstance(a, dict):
                out.append({"name": a.get("name", "") or a.get("artist", ""), "id": a.get("id", "") or a.get("browseId", "")})
            elif isinstance(a, str):
                out.append({"name": a, "id": ""})
        return out
    return []


def norm_track(t: dict) -> dict:
    raw = t.get("thumbnails") or t.get("thumbnail") or []
    if isinstance(raw, str):
        raw = [{"url": raw, "width": 0, "height": 0}]
    thumbs     = best_thumbnails_list(raw)
    album      = t.get("album")
    album_name = album.get("name", "") if isinstance(album, dict) else (album or "")
    return {
        "videoId":    t.get("videoId", ""),
        "title":      t.get("title", ""),
        "artists":    _norm_artists(t.get("artists") or t.get("artist")),
        "album":      album_name,
        "duration":   t.get("duration", ""),
        "thumbnails": thumbs,
        "thumbnail":  thumbs[0]["url"] if thumbs else "",
        "isExplicit": t.get("isExplicit", False),
        "year":       t.get("year", ""),
        "source":     t.get("source", "ytm"),
    }


def norm_artist_result(a: dict) -> dict:
    thumbs = best_thumbnails_list(a.get("thumbnails") or [])
    return {
        "browseId":    a.get("browseId", "") or a.get("channelId", ""),
        "name":        a.get("artist", "") or a.get("name", "") or a.get("title", ""),
        "subscribers": a.get("subscribers", ""),
        "thumbnails":  thumbs,
        "thumbnail":   thumbs[0]["url"] if thumbs else "",
    }


def norm_album_result(a: dict) -> dict:
    thumbs = best_thumbnails_list(a.get("thumbnails") or [])
    return {
        "browseId":   a.get("browseId", ""),
        "title":      a.get("title", ""),
        "artists":    _norm_artists(a.get("artists")),
        "year":       a.get("year", ""),
        "type":       a.get("type", "Album"),
        "thumbnails": thumbs,
        "thumbnail":  thumbs[0]["url"] if thumbs else "",
    }


def norm_playlist_result(p: dict) -> dict:
    thumbs = best_thumbnails_list(p.get("thumbnails") or [])
    return {
        "browseId":   p.get("browseId", "") or p.get("playlistId", ""),
        "title":      p.get("title", ""),
        "author":     p.get("author", ""),
        "itemCount":  p.get("itemCount", ""),
        "thumbnails": thumbs,
        "thumbnail":  thumbs[0]["url"] if thumbs else "",
    }


def norm_podcast_result(p: dict) -> dict:
    thumbs    = best_thumbnails_list(p.get("thumbnails") or [])
    browse_id = p.get("browseId") or p.get("podcastId") or p.get("channelId") or ""
    author    = p.get("author", "") or ", ".join(
        a.get("name", "") for a in _norm_artists(p.get("artists"))
    )
    return {
        "browseId":   browse_id,
        "title":      p.get("title", ""),
        "author":     author,
        "thumbnails": thumbs,
        "thumbnail":  thumbs[0]["url"] if thumbs else "",
    }


def norm_search_results(raw: list, filter_type: str | None) -> list:
    if not isinstance(raw, list):
        return []
    out = []
    for item in raw:
        if not isinstance(item, dict):
            continue
        rt = (item.get("resultType") or filter_type or "").lower()
        if rt in ("song", "songs", "video", "videos"):
            n = norm_track(item)
            n["resultType"] = "video" if "video" in rt else "song"
            out.append(n)
        elif rt in ("artist", "artists"):
            n = norm_artist_result(item); n["resultType"] = "artist"; out.append(n)
        elif rt in ("album", "albums", "single", "singles", "ep"):
            n = norm_album_result(item); n["resultType"] = "album"; out.append(n)
        elif rt in ("playlist", "playlists"):
            n = norm_playlist_result(item); n["resultType"] = "playlist"; out.append(n)
        elif rt in ("podcast", "podcasts", "episode", "episodes"):
            n = norm_podcast_result(item); n["resultType"] = "podcast"; out.append(n)
        else:
            thumbs = best_thumbnails_list(item.get("thumbnails") or [])
            item["thumbnails"] = thumbs
            item["thumbnail"]  = thumbs[0]["url"] if thumbs else ""
            out.append(item)
    return out


def _normalise_home(raw: list) -> list:
    shelves = []
    for shelf in raw:
        if not isinstance(shelf, dict):
            continue
        contents = []
        for item in (shelf.get("contents") or []):
            if not isinstance(item, dict):
                continue
            if item.get("videoId"):
                contents.append(norm_track(item))
            else:
                thumbs = best_thumbnails_list(item.get("thumbnails") or [])
                item["thumbnails"] = thumbs
                item["thumbnail"]  = thumbs[0]["url"] if thumbs else ""
                contents.append(item)
        if contents:
            shelves.append({"title": shelf.get("title", "For You"), "contents": contents})
    return shelves


def _extract_chart_section(section: Any) -> list:
    if not section:
        return []
    items = section if isinstance(section, list) else (
        section.get("items") or section.get("results") or []
    )
    out = []
    for item in items:
        if not isinstance(item, dict):
            continue
        thumbs = best_thumbnails_list(item.get("thumbnails") or [])
        item["thumbnails"] = thumbs
        item["thumbnail"]  = thumbs[0]["url"] if thumbs else ""
        out.append(item)
    return out


def _normalise_charts(raw: dict, country: str) -> dict:
    return {
        "country":  country,
        "songs":    [norm_track(t) for t in _extract_chart_section(raw.get("songs"))],
        "videos":   [norm_track(t) for t in _extract_chart_section(raw.get("videos"))
                     if t.get("videoId")],
        "artists":  [norm_artist_result(a) for a in _extract_chart_section(raw.get("artists"))],
        "trending": [norm_track(t) for t in _extract_chart_section(raw.get("trending"))
                     if t.get("videoId")],
    }


def _flatten_mood_categories(raw: Any) -> list:
    categories: list = []
    if isinstance(raw, dict):
        for section_title, items in raw.items():
            if isinstance(items, list):
                for item in items:
                    if not isinstance(item, dict):
                        continue
                    thumbs = best_thumbnails_list(item.get("thumbnails") or [])
                    categories.append({
                        "title":      item.get("title", ""),
                        "params":     item.get("params", ""),
                        "section":    section_title,
                        "thumbnails": thumbs,
                        "thumbnail":  thumbs[0]["url"] if thumbs else "",
                    })
    elif isinstance(raw, list):
        for item in raw:
            if not isinstance(item, dict):
                continue
            thumbs = best_thumbnails_list(item.get("thumbnails") or [])
            categories.append({
                "title":      item.get("title", ""),
                "params":     item.get("params", ""),
                "thumbnails": thumbs,
                "thumbnail":  thumbs[0]["url"] if thumbs else "",
            })
    return categories

# ─────────────────────────────────────────────────────────────────────────────
#  External API helpers β€” Apple Music
# ─────────────────────────────────────────────────────────────────────────────

_ITUNES_COUNTRY_FALLBACK = "us"


async def _fetch_itunes_trending(country: str, limit: int = 50) -> list:
    """Apple Music RSS top songs β€” country-aware, free, uses dedicated proxy client."""
    if not _cb_itunes.available:
        log.debug("Apple Music circuit breaker open β€” skipping fetch")
        return []
    c   = country.lower() if country and country not in ("ZZ", "zz") else _ITUNES_COUNTRY_FALLBACK
    url = f"https://rss.applemarketingtools.com/api/v2/{c}/music/most-played/{limit}/songs.json"
    t0  = time.monotonic()
    try:
        async with _get_semaphore():
            resp = await _get_apple_client().get(url)
        resp.raise_for_status()
        results = resp.json().get("feed", {}).get("results") or []
        tracks  = []
        for i, item in enumerate(results):
            art_url = re.sub(r"\d+x\d+bb", "600x600bb", item.get("artworkUrl100", ""))
            tracks.append({
                "videoId":    "",
                "title":      item.get("name", ""),
                "artists":    [{"name": item.get("artistName", ""), "id": ""}],
                "album":      item.get("collectionName", ""),
                "duration":   "",
                "thumbnails": [{"url": art_url, "width": 600, "height": 600}] if art_url else [],
                "thumbnail":  art_url,
                "isExplicit": item.get("contentAdvisoryRating", "") == "Explicit",
                "year":       item.get("releaseDate", "")[:4],
                "rank":       i + 1,
                "source":     "apple_music",
                "genres":     [g.get("name", "") for g in item.get("genres", []) if isinstance(g, dict)],
                "url":        item.get("url", ""),
            })
        elapsed = (time.monotonic() - t0) * 1000
        _cb_itunes.success()
        log.info("Apple Music: %d tracks for country=%s (%.0f ms)", len(tracks), c, elapsed)
        return tracks
    except Exception as exc:
        _cb_itunes.failure()
        log.warning("Apple Music fetch FAILED country=%s: %s", c, exc)
        log.debug("Apple Music traceback:\n%s", traceback.format_exc())
        return []


async def _fetch_itunes_top_albums(country: str, limit: int = 20) -> list:
    """Apple Music RSS top albums."""
    c   = country.lower() if country and country not in ("ZZ", "zz") else "us"
    url = f"https://rss.applemarketingtools.com/api/v2/{c}/music/most-played/{limit}/albums.json"
    try:
        async with _get_semaphore():
            resp = await _get_apple_client().get(url)
        resp.raise_for_status()
        results = resp.json().get("feed", {}).get("results") or []
        albums  = []
        for i, item in enumerate(results):
            art_url = re.sub(r"\d+x\d+bb", "600x600bb", item.get("artworkUrl100", ""))
            albums.append({
                "browseId":  "",
                "title":     item.get("name", ""),
                "artists":   [{"name": item.get("artistName", ""), "id": ""}],
                "year":      item.get("releaseDate", "")[:4],
                "thumbnail": art_url,
                "thumbnails":[{"url": art_url, "width": 600, "height": 600}] if art_url else [],
                "rank":      i + 1,
                "source":    "apple_music",
                "url":       item.get("url", ""),
            })
        return albums
    except Exception as exc:
        log.warning("Apple Music albums FAILED: %s", exc)
        return []

# ─────────────────────────────────────────────────────────────────────────────
#  External API helpers β€” Deezer
# ─────────────────────────────────────────────────────────────────────────────

async def _fetch_deezer_charts(limit: int = 50) -> dict:
    """Deezer global charts β€” free, no API key needed."""
    if not _cb_deezer.available:
        log.debug("Deezer circuit breaker open β€” skipping fetch")
        return {}
    t0 = time.monotonic()
    try:
        async with _get_semaphore():
            resp = await _get_http_client().get(
                "https://api.deezer.com/chart/0/tracks",
                params={"limit": limit},
            )
        resp.raise_for_status()
        data   = resp.json()
        tracks = []
        for i, item in enumerate(data.get("data") or []):
            art = (item.get("album", {}).get("cover_xl") or
                   item.get("album", {}).get("cover_big") or
                   item.get("album", {}).get("cover_medium", ""))
            tracks.append({
                "videoId":    "",
                "title":      item.get("title", ""),
                "artists":    [{"name": item.get("artist", {}).get("name", ""), "id": ""}],
                "album":      item.get("album", {}).get("title", ""),
                "duration":   str(item.get("duration", "")),
                "thumbnails": [{"url": art, "width": 500, "height": 500}] if art else [],
                "thumbnail":  art,
                "isExplicit": item.get("explicit_lyrics", False),
                "year":       "",
                "rank":       i + 1,
                "source":     "deezer",
                "deezerId":   str(item.get("id", "")),
                "preview":    item.get("preview", ""),
            })
        _cb_deezer.success()
        albums:  list = []
        artists: list = []
        for t_list, endpoint in [(albums, "albums"), (artists, "artists")]:
            try:
                async with _get_semaphore():
                    r2 = await _get_http_client().get(
                        f"https://api.deezer.com/chart/0/{endpoint}",
                        params={"limit": 20},
                    )
                r2.raise_for_status()
                for item in (r2.json().get("data") or []):
                    pic = (item.get("cover_xl") or item.get("cover_big") or
                           item.get("picture_xl") or item.get("picture_big") or
                           item.get("picture_medium", ""))
                    t_list.append({
                        "title":     item.get("title") or item.get("name", ""),
                        "artist":    item.get("artist", {}).get("name", "") if endpoint == "albums" else "",
                        "thumbnail": pic,
                        "source":    "deezer",
                        "deezerId":  str(item.get("id", "")),
                        "url":       item.get("link", ""),
                    })
            except Exception as exc:
                log.debug("Deezer %s fetch skipped: %s", endpoint, exc)
        elapsed = (time.monotonic() - t0) * 1000
        log.info("Deezer: %d chart tracks (%.0f ms)", len(tracks), elapsed)
        return {"tracks": tracks, "albums": albums, "artists": artists}
    except Exception as exc:
        _cb_deezer.failure()
        log.warning("Deezer charts FAILED: %s", exc)
        log.debug("Deezer traceback:\n%s", traceback.format_exc())
        return {}


async def _fetch_deezer_genres() -> list:
    """Deezer genre list."""
    if not _cb_deezer.available:
        return []
    try:
        async with _get_semaphore():
            resp = await _get_http_client().get("https://api.deezer.com/genre")
        resp.raise_for_status()
        genres = []
        for g in (resp.json().get("data") or []):
            pic = g.get("picture_xl") or g.get("picture_big") or g.get("picture_medium", "")
            genres.append({
                "id":        g.get("id"),
                "title":     g.get("name", ""),
                "thumbnail": pic,
                "thumbnails": [{"url": pic, "width": 500, "height": 500}] if pic else [],
                "source":    "deezer",
            })
        _cb_deezer.success()
        return genres
    except Exception as exc:
        _cb_deezer.failure()
        log.warning("Deezer genres FAILED: %s", exc)
        return []


async def _fetch_deezer_editorial_playlists(limit: int = 20) -> list:
    """Deezer editorial playlists (global)."""
    if not _cb_deezer.available:
        return []
    try:
        async with _get_semaphore():
            resp = await _get_http_client().get(
                "https://api.deezer.com/editorial/0/charts",
                params={"limit": limit},
            )
        resp.raise_for_status()
        data      = resp.json()
        playlists = []
        for item in (data.get("playlists", {}).get("data") or []):
            pic = item.get("picture_xl") or item.get("picture_big") or item.get("picture_medium", "")
            playlists.append({
                "browseId":   str(item.get("id", "")),
                "title":      item.get("title", ""),
                "subtitle":   item.get("description", ""),
                "thumbnail":  pic,
                "thumbnails": [{"url": pic, "width": 500, "height": 500}] if pic else [],
                "source":     "deezer",
            })
        _cb_deezer.success()
        return playlists
    except Exception as exc:
        _cb_deezer.failure()
        log.warning("Deezer editorial FAILED: %s", exc)
        return []

# ─────────────────────────────────────────────────────────────────────────────
#  External API helpers β€” Spotify  (Client Credentials, 100% free)
# ─────────────────────────────────────────────────────────────────────────────

# ── Spotify Android-client token state ───────────────────────────────────────
# We simulate the Spotify Android app.  Two separate tokens are maintained:
#   _spotify_client_token  β€” short-lived token from clienttoken.spotify.com
#                            (proves we are a known Spotify client; no secret)
#   _spotify_access_token  β€” Bearer token from accounts.spotify.com
#                            (used in Authorization header; needs client_secret)
# Both are refreshed automatically; all state protected by a threading.Lock.
# ─────────────────────────────────────────────────────────────────────────────

import secrets as _secrets

_SPOTIFY_DEVICE_ID = _secrets.token_hex(16)   # stable per-process, random across restarts

# Android Spotify app version strings (update periodically if Spotify changes them)
_SPOTIFY_ANDROID_VERSION    = "8.6.96.470"
_SPOTIFY_ANDROID_OS_VERSION = "30"            # Android 11

_spotify_access_token:        str   = ""
_spotify_access_expires:      float = 0.0
_spotify_client_token:        str   = ""
_spotify_client_token_expires: float = 0.0
_spotify_token_lock                  = threading.Lock()


async def _refresh_spotify_client_token() -> str:
    """
    Fetch a Spotify client-token via clienttoken.spotify.com.
    This endpoint accepts just the client_id (no secret) and returns a short-lived
    client-token that proves the caller is a known Spotify client application.
    Used identically by the real Spotify Android / iOS apps.
    """
    global _spotify_client_token, _spotify_client_token_expires
    if not _SPOTIFY_CLIENT_ID:
        return ""
    payload = {
        "client_data": {
            "client_version": _SPOTIFY_ANDROID_VERSION,
            "client_id":      _SPOTIFY_CLIENT_ID,
            "js_sdk_data": {
                "device_brand":   "Google",
                "device_model":   "sdk_gphone64_x86_64",
                "os":             "android",
                "os_version":     _SPOTIFY_ANDROID_OS_VERSION,
                "device_id":      _SPOTIFY_DEVICE_ID,
                "device_type":    "smartphone",
            },
        }
    }
    try:
        async with _get_semaphore():
            resp = await _get_http_client().post(
                "https://clienttoken.spotify.com/v1/clienttoken",
                json=payload,
                headers={"Accept": "application/json"},
            )
        resp.raise_for_status()
        data = resp.json()
        token = (
            data.get("granted_token", {}).get("token") or
            data.get("client_token") or ""
        )
        ttl = int(
            data.get("granted_token", {}).get("expires_after_seconds") or
            data.get("refresh_after_seconds") or
            1_800
        )
        with _spotify_token_lock:
            _spotify_client_token         = token
            _spotify_client_token_expires = time.monotonic() + ttl - 30
        log.info("Spotify: client-token refreshed (ttl=%ds)", ttl)
        return token
    except Exception as exc:
        log.warning("Spotify client-token refresh FAILED: %s", exc)
        log.debug("Spotify client-token traceback:\n%s", traceback.format_exc())
        return ""


async def _get_spotify_client_token() -> str:
    with _spotify_token_lock:
        if _spotify_client_token and time.monotonic() < _spotify_client_token_expires:
            return _spotify_client_token
    return await _refresh_spotify_client_token()


async def _refresh_spotify_access_token() -> str:
    """
    Fetch a Spotify Bearer access token via client_credentials grant.
    Uses the provided SPOTIFY_CLIENT_ID + SPOTIFY_CLIENT_SECRET (Android/iOS app creds).
    Does NOT require Spotify Premium β€” gives access to all public catalog endpoints.
    """
    global _spotify_access_token, _spotify_access_expires
    if not _SPOTIFY_CLIENT_ID or not _SPOTIFY_CLIENT_SECRET:
        return ""
    creds = base64.b64encode(
        f"{_SPOTIFY_CLIENT_ID}:{_SPOTIFY_CLIENT_SECRET}".encode()
    ).decode()
    try:
        async with _get_semaphore():
            resp = await _get_http_client().post(
                "https://accounts.spotify.com/api/token",
                headers={
                    "Authorization": f"Basic {creds}",
                    "Content-Type":  "application/x-www-form-urlencoded",
                },
                content=b"grant_type=client_credentials",
            )
        resp.raise_for_status()
        data = resp.json()
        with _spotify_token_lock:
            _spotify_access_token   = data["access_token"]
            _spotify_access_expires = time.monotonic() + data.get("expires_in", 3_600) - 30
        log.info("Spotify: access token refreshed (expires in %ds)", data.get("expires_in", 3_600))
        return _spotify_access_token
    except Exception as exc:
        log.warning("Spotify access token refresh FAILED: %s", exc)
        log.debug("Spotify token traceback:\n%s", traceback.format_exc())
        return ""


async def _get_spotify_tokens() -> tuple[str, str]:
    """Return (access_token, client_token). Either may be empty on failure."""
    with _spotify_token_lock:
        access_ok  = _spotify_access_token  and time.monotonic() < _spotify_access_expires
        client_ok  = _spotify_client_token  and time.monotonic() < _spotify_client_token_expires

    access_task  = (asyncio.sleep(0) if access_ok  else _refresh_spotify_access_token())
    client_task  = (asyncio.sleep(0) if client_ok  else _refresh_spotify_client_token())
    await asyncio.gather(access_task, client_task, return_exceptions=True)

    with _spotify_token_lock:
        return _spotify_access_token, _spotify_client_token


def _spotify_headers(access_token: str, client_token: str) -> dict:
    """Build the full set of headers the Spotify Android app sends."""
    h = {
        "Authorization":    f"Bearer {access_token}",
        "Accept":           "application/json",
        "Accept-Language":  "en",
        "app-platform":     "Android",
        "spotify-app-version": _SPOTIFY_ANDROID_VERSION,
        "User-Agent": (
            f"Spotify/{_SPOTIFY_ANDROID_VERSION} Android/{_SPOTIFY_ANDROID_OS_VERSION} "
            "(Google sdk_gphone64_x86_64)"
        ),
    }
    if client_token:
        h["client-token"] = client_token
    return h


async def _fetch_spotify_trending(country: str, limit: int = 50) -> list:
    """
    Fetch country trending tracks via the Spotify Android client approach.
    Disabled per user request.
    """
    return []

    c = country.upper() if country and country not in ("ZZ", "zz") else "US"
    access_token, client_token = await _get_spotify_tokens()
    if not access_token:
        log.warning("Spotify: no access token available, skipping trending for %s", c)
        return []

    headers = _spotify_headers(access_token, client_token)
    t0      = time.monotonic()

    try:
        # ── 1. Featured playlists (country-localised) ──────────────────────
        async with _get_semaphore():
            fp_resp = await _get_http_client().get(
                "https://api.spotify.com/v1/browse/featured-playlists",
                headers=headers,
                params={"country": c, "limit": 5},
            )
        fp_resp.raise_for_status()
        playlists = fp_resp.json().get("playlists", {}).get("items") or []
        log.debug("Spotify: %d featured playlists for %s", len(playlists), c)

        tracks: list = []
        per_playlist  = max((limit // max(len(playlists), 1)) + 5, 15)

        for playlist in playlists[:4]:
            pid = playlist.get("id", "")
            if not pid:
                continue
            try:
                async with _get_semaphore():
                    tr_resp = await _get_http_client().get(
                        f"https://api.spotify.com/v1/playlists/{pid}/tracks",
                        headers=headers,
                        params={
                            "limit":  per_playlist,
                            "market": c,
                            "fields": (
                                "items(track("
                                "id,name,artists(name,id),album(name,images),"
                                "duration_ms,explicit,popularity))"
                            ),
                        },
                    )
                tr_resp.raise_for_status()
                for item in (tr_resp.json().get("items") or []):
                    t = item.get("track")
                    if not t or not isinstance(t, dict) or not t.get("id"):
                        continue
                    album  = t.get("album") or {}
                    images = album.get("images") or []
                    # pick largest image (Spotify orders by descending width)
                    art = images[0]["url"] if images else ""
                    tracks.append({
                        "videoId":    "",
                        "title":      t.get("name", ""),
                        "artists":    [
                            {"name": a.get("name", ""), "id": a.get("id", "")}
                            for a in (t.get("artists") or [])
                        ],
                        "album":      album.get("name", ""),
                        "duration":   str(int(t.get("duration_ms", 0)) // 1_000),
                        "thumbnails": [{"url": art, "width": 640, "height": 640}] if art else [],
                        "thumbnail":  art,
                        "isExplicit": t.get("explicit", False),
                        "year":       "",
                        "rank":       len(tracks) + 1,
                        "source":     "spotify",
                        "spotifyId":  t.get("id", ""),
                        "popularity": t.get("popularity", 0),
                    })
            except Exception as exc:
                log.debug("Spotify playlist %s track fetch skipped: %s", pid, exc)

        # ── 2. New releases as supplemental source ─────────────────────────
        if len(tracks) < limit // 2:
            try:
                async with _get_semaphore():
                    nr_resp = await _get_http_client().get(
                        "https://api.spotify.com/v1/browse/new-releases",
                        headers=headers,
                        params={"country": c, "limit": 10},
                    )
                nr_resp.raise_for_status()
                for album in (nr_resp.json().get("albums", {}).get("items") or []):
                    images = album.get("images") or []
                    art    = images[0]["url"] if images else ""
                    tracks.append({
                        "videoId":    "",
                        "title":      album.get("name", ""),
                        "artists":    [
                            {"name": a.get("name", ""), "id": a.get("id", "")}
                            for a in (album.get("artists") or [])
                        ],
                        "album":      album.get("name", ""),
                        "duration":   "",
                        "thumbnails": [{"url": art, "width": 640, "height": 640}] if art else [],
                        "thumbnail":  art,
                        "isExplicit": False,
                        "year":       (album.get("release_date") or "")[:4],
                        "rank":       len(tracks) + 1,
                        "source":     "spotify",
                        "spotifyId":  album.get("id", ""),
                        "popularity": 0,
                    })
            except Exception as exc:
                log.debug("Spotify new-releases skipped: %s", exc)

        elapsed = (time.monotonic() - t0) * 1000
        _cb_spotify.success()
        log.info("Spotify: %d tracks for country=%s (%.0f ms)", len(tracks), c, elapsed)
        return tracks[:limit]

    except Exception as exc:
        _cb_spotify.failure()
        log.warning("Spotify trending FAILED country=%s: %s", c, exc)
        log.debug("Spotify traceback:\n%s", traceback.format_exc())
        return []

# ─────────────────────────────────────────────────────────────────────────────
#  Cache-Control header helper
# ─────────────────────────────────────────────────────────────────────────────

def _cc(seconds: int) -> dict:
    return {"Cache-Control": f"public, max-age={seconds}, stale-while-revalidate=60"}

# ─────────────────────────────────────────────────────────────────────────────
#  Track deduplication
# ─────────────────────────────────────────────────────────────────────────────

def _deduplicate_tracks(tracks: list) -> list:
    seen, out = set(), []
    for t in tracks:
        title  = (t.get("title", "") or "").lower().strip()
        artist = ""
        arts   = t.get("artists", [])
        if arts and isinstance(arts[0], dict):
            artist = (arts[0].get("name", "") or "").lower().strip()
        key = f"{title}|{artist}"
        if key and key not in seen:
            seen.add(key)
            out.append(t)
    return out

# ─────────────────────────────────────────────────────────────────────────────
#  Chart merging
# ─────────────────────────────────────────────────────────────────────────────

def _merge_charts(
    country:  str,
    ytm:      dict,
    apple:    Any,
    deezer:   Any,
    spotify:  Any,
) -> dict:
    """Merge chart data from all sources. Apple Music is primary when YTM is thin."""
    apple_tracks   = apple   if isinstance(apple,   list) else []
    deezer_data    = deezer  if isinstance(deezer,  dict) else {}
    spotify_tracks = spotify if isinstance(spotify, list) else []
    deezer_tracks  = deezer_data.get("tracks", [])

    ytm_songs    = ytm.get("songs",    [])
    ytm_videos   = ytm.get("videos",   [])
    ytm_artists  = ytm.get("artists",  [])
    ytm_trending = ytm.get("trending", [])

    primary_songs = apple_tracks if len(apple_tracks) >= 5 else (ytm_songs or apple_tracks)

    return {
        "country":         country,
        "songs":           primary_songs,
        "ytm_songs":       ytm_songs,
        "videos":          ytm_videos,
        "artists":         ytm_artists,
        "trending":        ytm_trending,
        "apple_music_top": apple_tracks,
        "deezer_top":      deezer_tracks,
        "deezer_albums":   deezer_data.get("albums", []),
        "deezer_artists":  deezer_data.get("artists", []),
        "spotify_top":     spotify_tracks,
        "cached_at":       int(time.time()),
        "sources_used": {
            "ytm":     len(ytm_songs)      > 0,
            "apple":   len(apple_tracks)   > 0,
            "deezer":  len(deezer_tracks)  > 0,
            "spotify": len(spotify_tracks) > 0,
        },
    }

# ─────────────────────────────────────────────────────────────────────────────
#  Background warm-up & auto-refresh
# ─────────────────────────────────────────────────────────────────────────────

async def _do_fetch_charts(country: str, language: str) -> dict:
    """Core fetch function: YTM + Apple + Deezer + Spotify in parallel."""
    log.info("Charts fetch: country=%s lang=%s", country, language)
    ytm_task    = (run(get_ytm(country, language).get_charts, country)
                   if _cb_ytm.available else asyncio.sleep(0))
    apple_task  = _fetch_itunes_trending(country, 50)
    deezer_task = _fetch_deezer_charts(50)
    spotify_task = _fetch_spotify_trending(country, 50)

    ytm_raw, apple_tracks, deezer_data, spotify_tracks = await asyncio.gather(
        ytm_task, apple_task, deezer_task, spotify_task,
        return_exceptions=True,
    )

    ytm_result: dict = {}
    if isinstance(ytm_raw, Exception):
        _cb_ytm.failure()
        log.warning("YTMusic charts FAILED country=%s: %s", country, ytm_raw)
    elif isinstance(ytm_raw, dict) and ytm_raw:
        ytm_result = _normalise_charts(ytm_raw, country)
        _cb_ytm.success()

    result = _merge_charts(country, ytm_result, apple_tracks, deezer_data, spotify_tracks)
    key    = f"charts10h:{country}:{language}"
    _cache_charts.set(key, result)
    log.info("Charts cached: country=%s (songs=%d, apple=%d, spotify=%d)",
             country,
             len(result.get("ytm_songs", [])),
             len(result.get("apple_music_top", [])),
             len(result.get("spotify_top", [])))
    return result


async def _warm_home(country: str, language: str) -> None:
    try:
        raw     = await run(get_ytm(country, language).get_home, 6)
        shelves = _normalise_home(raw or [])
        if shelves:
            _cache_medium.set(f"home:{country}:{language}:6", shelves)
    except Exception as exc:
        log.debug("_warm_home country=%s: %s", country, exc)


async def _warm_moods(country: str, language: str) -> None:
    try:
        raw        = await run(get_ytm(country, language).get_mood_categories)
        categories = _flatten_mood_categories(raw)
        if categories:
            _cache_medium.set(f"mood_categories:{country}:{language}", categories)
    except Exception as exc:
        log.debug("_warm_moods country=%s: %s", country, exc)


async def _background_warmup():
    """Pre-populate caches for common locales shortly after startup."""
    await asyncio.sleep(5)
    log.info("Background warm-up starting …")
    warm_targets = [("ZZ", "en"), ("IN", "en"), ("US", "en"), ("GB", "en")]
    for country, lang in warm_targets:
        try:
            await _do_fetch_charts(country, lang)
        except Exception as exc:
            log.warning("Warm-up charts %s failed: %s", country, exc)
        try:
            await _warm_home(country, lang)
        except Exception:
            pass
        await asyncio.sleep(1)   # small stagger to avoid burst
    try:
        await _warm_moods("ZZ", "en")
    except Exception:
        pass
    log.info("Background warm-up complete.")


async def _auto_refresh_charts():
    """Re-fetch all known countries' charts once every 10 hours."""
    await asyncio.sleep(120)    # let warm-up finish first
    while True:
        await asyncio.sleep(36_000)    # 10 hours
        log.info("Auto-refresh: refreshing all cached chart countries …")
        # Refresh every country already known in the charts cache
        # (we track them via disk cache keys)
        refreshed = 0
        try:
            for k in list(_disk_cache.iterkeys()):
                sk = str(k)
                if not sk.startswith("charts10h:"):
                    continue
                parts = sk.split(":")
                if len(parts) == 3:
                    _, c, lang = parts
                    try:
                        await _do_fetch_charts(c, lang)
                        refreshed += 1
                    except Exception as exc:
                        log.warning("Auto-refresh failed for %s/%s: %s", c, lang, exc)
                    await asyncio.sleep(2)
        except Exception as exc:
            log.warning("Auto-refresh loop error: %s", exc)
        log.info("Auto-refresh complete: %d countries refreshed.", refreshed)

# ─────────────────────────────────────────────────────────────────────────────
#  Routes β€” meta
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/", include_in_schema=False)
async def root():
    return {"name": "Musicanaz API", "version": "9.0.0", "status": "ok", "docs": "/docs"}


@app.get("/health", tags=["meta"])
async def health():
    hits, misses = _disk_cache.stats()
    return {
        "status":           "ok",
        "version":          "9.0.0",
        "uptime_seconds":   round(time.monotonic() - _START_TIME),
        "ytm_instances":    len(_ytm_pool),
        "proxy_enabled":    _PROXIES is not None,
        "spotify_enabled":  bool(_SPOTIFY_CLIENT_ID),
        "circuit_breakers": {
            "ytm":     "open" if not _cb_ytm.available     else "closed",
            "itunes":  "open" if not _cb_itunes.available  else "closed",
            "deezer":  "open" if not _cb_deezer.available  else "closed",
            "spotify": "open" if not _cb_spotify.available else "closed",
        },
        "chart_countries_cached": sum(
            1 for k in (_disk_cache.iterkeys() if True else [])
            if str(k).startswith("charts10h:")
        ),
        "disk_cache": {
            "hits":    hits,
            "misses":  misses,
            "size_mb": round(_disk_cache.volume() / 1_048_576, 1),
        },
    }


@app.get("/cache_stats", tags=["meta"])
async def cache_stats():
    hits, misses = _disk_cache.stats()
    return {
        "memory": {
            "short":  len(_cache_short),
            "medium": len(_cache_medium),
            "long":   len(_cache_long),
            "charts": len(_cache_charts),
        },
        "disk": {
            "entries":  len(_disk_cache),
            "size_mb":  round(_disk_cache.volume() / 1_048_576, 1),
            "hits":     hits,
            "misses":   misses,
            "hit_rate": f"{hits/(hits+misses)*100:.1f}%" if (hits + misses) > 0 else "n/a",
        },
        "upnext":   len(_upnext_store),
        "ytm_pool": len(_ytm_pool),
    }


@app.delete("/cache", tags=["meta"])
async def clear_cache(key_prefix: str = ""):
    cleared = 0
    if key_prefix:
        for k in list(_disk_cache.iterkeys()):
            if str(k).startswith(key_prefix):
                _disk_cache.delete(k)
                cleared += 1
    else:
        _disk_cache.clear()
        cleared = -1
    log.info("Cache cleared: prefix=%r entries=%s", key_prefix or "(all)", cleared)
    return {"cleared": cleared if cleared >= 0 else "all"}

# ─────────────────────────────────────────────────────────────────────────────
#  Search
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/search", tags=["search"])
@limiter.limit("40/minute")
async def search(
    request:  Request,
    response: Response,
    query:    str,
    filter:   Optional[str] = Query(None),
    scope:    Optional[str] = Query(None),
    limit:    int  = Query(20, ge=1, le=50),
    offset:   int  = Query(0, ge=0),
    ignore_spelling: bool = False,
    country:  str = Query("ZZ"),
    language: str = Query("en"),
):
    fetch_limit = min(offset + limit, 50)
    cache_key   = f"search:{query}:{filter}:{fetch_limit}:{country}:{language}"
    cached      = _cache_short.get(cache_key)

    if cached is None:
        if not _cb_ytm.available:
            raise HTTPException(503, detail="YTMusic source temporarily unavailable")
        try:
            raw    = await run(
                get_ytm(country, language).search,
                query, filter, scope, fetch_limit, ignore_spelling,
            )
            cached = norm_search_results(raw or [], filter)
            _cache_short.set(cache_key, cached)
            _cb_ytm.success()
        except Exception as e:
            _cb_ytm.failure()
            log.error("Search failed q=%r: %s", query, e)
            raise HTTPException(500, detail=str(e))

    response.headers.update(_cc(120))
    return cached[offset:offset + limit]


@app.get("/search_suggestions", tags=["search"])
@limiter.limit("40/minute")
async def search_suggestions(
    request:  Request,
    response: Response,
    query:    str,
    detailed: bool = False,
    country:  str = Query("ZZ"),
    language: str = Query("en"),
):
    cache_key = f"suggestions:{query}:{detailed}:{country}:{language}"
    cached    = _cache_short.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(60))
        return cached
    try:
        data = await run(get_ytm(country, language).get_search_suggestions, query, detailed)
        _cache_short.set(cache_key, data or [])
        response.headers.update(_cc(60))
        return data or []
    except Exception as e:
        log.warning("Search suggestions failed q=%r: %s", query, e)
        raise HTTPException(500, detail=str(e))

# ─────────────────────────────────────────────────────────────────────────────
#  Home feed
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/home", tags=["discovery"])
@limiter.limit("30/minute")
async def get_home(
    request:  Request,
    response: Response,
    limit:    int = Query(6, ge=1, le=15),
    country:  str = Query("ZZ"),
    language: str = Query("en"),
):
    cache_key = f"home:{country}:{language}:{limit}"
    cached    = _cache_medium.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(300))
        return cached

    try:
        raw     = await run(get_ytm(country, language).get_home, limit)
        shelves = _normalise_home(raw or [])
    except Exception as exc:
        log.warning("Home YTM failed country=%s: %s", country, exc)
        shelves = []

    # Fallback: synthesise home from Apple Music + Spotify when YTM is empty
    if not shelves:
        apple_task   = _fetch_itunes_trending(country, 20)
        spotify_task = _fetch_spotify_trending(country, 20)
        apple_tracks, spotify_tracks = await asyncio.gather(
            apple_task, spotify_task, return_exceptions=True
        )
        if isinstance(apple_tracks, list) and apple_tracks:
            shelves.append({"title": "Top Songs", "contents": apple_tracks[:20]})
        if isinstance(spotify_tracks, list) and spotify_tracks:
            shelves.append({"title": "Trending Worldwide", "contents": spotify_tracks[:20]})

    _cache_medium.set(cache_key, shelves)
    response.headers.update(_cc(300))
    return shelves

# ─────────────────────────────────────────────────────────────────────────────
#  Charts  β€” 10-hour per-country cache with stampede protection
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/charts", tags=["discovery"])
@limiter.limit("30/minute")
async def get_charts(
    request:  Request,
    response: Response,
    country:  str = Query("ZZ"),
    language: str = Query("en"),
    sources:  str = Query("all", description="all | ytm | apple | deezer | spotify"),
):
    """
    Country-aware charts from all sources.
    Cached per-country for 10 hours. A new country triggers one fetch;
    all concurrent callers wait on a per-country lock for the result.
    """
    cache_key = f"charts10h:{country}:{language}"
    cached    = _cache_charts.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(36_000))
        return cached

    # Per-country lock: only one fetch in-flight at a time
    async with _chart_lock(country):
        # Double-check after acquiring lock
        cached = _cache_charts.get(cache_key)
        if cached is not None:
            response.headers.update(_cc(36_000))
            return cached

        try:
            result = await _do_fetch_charts(country, language)
        except Exception as exc:
            log.error("Charts fetch error country=%s: %s", country, exc)
            log.debug("Charts traceback:\n%s", traceback.format_exc())
            raise HTTPException(500, detail=f"Charts fetch failed: {exc}")

    response.headers.update(_cc(36_000))
    return result

# ─────────────────────────────────────────────────────────────────────────────
#  Trending  β€” 10-hour per-country cache with stampede protection
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/trending", tags=["discovery"])
@limiter.limit("30/minute")
async def get_trending(
    request:  Request,
    response: Response,
    country:  str = Query("ZZ"),
    language: str = Query("en"),
    limit:    int = Query(25, ge=1, le=100),
    sources:  str = Query("all", description="all | ytm | apple | deezer | spotify"),
):
    """
    Trending songs merged from Apple Music + Deezer + Spotify (+YTM when warm).
    Cached per-country for 10 hours. First request per country triggers one fetch.
    """
    cache_key = f"trending10h:{country}:{language}"
    cached    = _cache_charts.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(36_000))
        # Return slice of limit from cached merged list
        out = dict(cached)
        out["merged"] = out.get("merged", [])[:limit]
        return out

    async with _trending_lock(country):
        cached = _cache_charts.get(cache_key)
        if cached is not None:
            response.headers.update(_cc(36_000))
            out = dict(cached)
            out["merged"] = out.get("merged", [])[:limit]
            return out

        log.info("Trending fetch: country=%s lang=%s", country, language)

        use_apple   = sources in ("all", "apple")
        use_deezer  = sources in ("all", "deezer")
        use_spotify = sources in ("all", "spotify")
        use_ytm     = sources in ("all", "ytm")

        apple_task   = _fetch_itunes_trending(country, 50)  if use_apple   else asyncio.sleep(0)
        deezer_task  = _fetch_deezer_charts(50)             if use_deezer  else asyncio.sleep(0)
        spotify_task = _fetch_spotify_trending(country, 50) if use_spotify else asyncio.sleep(0)

        # Use YTM from charts cache if already warm
        ytm_trending: list = []
        if use_ytm and _cb_ytm.available:
            chart_cached = _cache_charts.get(f"charts10h:{country}:{language}")
            if chart_cached:
                ytm_trending = (chart_cached.get("trending") or
                                chart_cached.get("ytm_songs") or [])

        apple_tracks, deezer_data, spotify_tracks = await asyncio.gather(
            apple_task, deezer_task, spotify_task,
            return_exceptions=True,
        )
        apple_tracks   = apple_tracks   if isinstance(apple_tracks,   list) else []
        deezer_tracks  = (deezer_data.get("tracks", [])
                          if isinstance(deezer_data, dict) else [])
        spotify_tracks = spotify_tracks if isinstance(spotify_tracks, list) else []

        merged = _deduplicate_tracks(
            apple_tracks[:50] + spotify_tracks[:50] + ytm_trending[:50]
        )

        result = {
            "country":      country,
            "trending":     ytm_trending[:50],
            "apple_top":    apple_tracks[:50],
            "deezer_top":   deezer_tracks[:50],
            "spotify_top":  spotify_tracks[:50],
            "merged":       merged,
            "cached_at":    int(time.time()),
            "sources_used": {
                "ytm":     len(ytm_trending)   > 0,
                "apple":   len(apple_tracks)   > 0,
                "deezer":  len(deezer_tracks)  > 0,
                "spotify": len(spotify_tracks) > 0,
            },
        }
        _cache_charts.set(cache_key, result)
        log.info("Trending cached: country=%s merged=%d", country, len(merged))

    out = dict(result)
    out["merged"] = out["merged"][:limit]
    response.headers.update(_cc(36_000))
    return out

# ─────────────────────────────────────────────────────────────────────────────
#  Apple Music direct endpoints
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/apple_music/top_songs", tags=["apple_music"])
@limiter.limit("30/minute")
async def apple_music_top_songs(
    request:  Request,
    response: Response,
    country:  str = Query("us"),
    limit:    int = Query(50, ge=1, le=100),
):
    cache_key = f"am_songs:{country}:{limit}"
    cached    = _cache_charts.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(36_000))
        return cached
    tracks = await _fetch_itunes_trending(country, limit)
    if not tracks:
        raise HTTPException(503, detail="Apple Music RSS unavailable")
    result = {"country": country, "tracks": tracks, "count": len(tracks)}
    _cache_charts.set(cache_key, result)
    response.headers.update(_cc(36_000))
    return result


@app.get("/apple_music/top_albums", tags=["apple_music"])
@limiter.limit("30/minute")
async def apple_music_top_albums(
    request:  Request,
    response: Response,
    country:  str = Query("us"),
    limit:    int = Query(20, ge=1, le=50),
):
    cache_key = f"am_albums:{country}:{limit}"
    cached    = _cache_medium.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(1_800))
        return cached
    albums = await _fetch_itunes_top_albums(country, limit)
    if not albums:
        raise HTTPException(503, detail="Apple Music RSS unavailable")
    result = {"country": country, "albums": albums, "count": len(albums)}
    _cache_medium.set(cache_key, result)
    response.headers.update(_cc(1_800))
    return result

# ─────────────────────────────────────────────────────────────────────────────
#  Deezer direct endpoints
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/deezer/charts", tags=["deezer"])
@limiter.limit("30/minute")
async def deezer_charts_endpoint(
    request:  Request,
    response: Response,
    limit:    int = Query(50, ge=1, le=100),
):
    cache_key = f"deezer_charts:{limit}"
    cached    = _cache_charts.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(36_000))
        return cached
    data = await _fetch_deezer_charts(limit)
    if not data:
        raise HTTPException(503, detail="Deezer unavailable")
    _cache_charts.set(cache_key, data)
    response.headers.update(_cc(36_000))
    return data

# ─────────────────────────────────────────────────────────────────────────────
#  Spotify direct endpoint
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/spotify/trending", tags=["spotify"])
@limiter.limit("30/minute")
async def spotify_trending(
    request:  Request,
    response: Response,
    country:  str = Query("US"),
    limit:    int = Query(50, ge=1, le=100),
):
    """Spotify featured playlists trending tracks by country (free, no login needed)."""
    if not _SPOTIFY_CLIENT_ID:
        raise HTTPException(503, detail="Spotify not configured (set SPOTIFY_CLIENT_ID + SPOTIFY_CLIENT_SECRET)")
    cache_key = f"spotify_trending:{country}:{limit}"
    cached    = _cache_charts.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(36_000))
        return cached
    tracks = await _fetch_spotify_trending(country, limit)
    # Never raise exception for empty tracks (Spotify is disabled)
    result = {"country": country, "tracks": tracks, "count": len(tracks)}
    _cache_charts.set(cache_key, result)
    response.headers.update(_cc(36_000))
    return result

# ─────────────────────────────────────────────────────────────────────────────
#  Song metadata
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/song/{video_id}", tags=["song"])
@limiter.limit("60/minute")
async def get_song(
    request:  Request,
    response: Response,
    video_id: str,
    country:  str = Query("ZZ"),
    language: str = Query("en"),
):
    cache_key = f"song:{video_id}"
    cached    = _cache_long.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(3_600))
        return cached
    try:
        data = await run(get_ytm(country, language).get_song, video_id)
        raw  = (
            data.get("thumbnail", {}).get("thumbnails") or
            data.get("thumbnails") or []
        )
        thumbs = best_thumbnails_list(raw)
        data["thumbnails"] = thumbs
        data["thumbnail"]  = thumbs[0]["url"] if thumbs else ""
        _cache_long.set(cache_key, data)
        response.headers.update(_cc(3_600))
        return data
    except Exception as e:
        log.error("get_song %s: %s", video_id, e)
        raise HTTPException(500, detail=str(e))


@app.get("/stream/{video_id}", tags=["song"])
@limiter.limit("60/minute")
async def get_stream(
    request:  Request,
    response: Response,
    video_id: str,
    country:  str = Query("ZZ"),
    language: str = Query("en"),
):
    cache_key = f"stream:{video_id}"
    cached    = _cache_long.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(3_600))
        return cached
    try:
        song_data = await run(get_ytm(country, language).get_song, video_id)
        vd = song_data.get("videoDetails", {})
        if not vd:
            raise HTTPException(404, "Video not found")
        raw    = (vd.get("thumbnail", {}).get("thumbnails") or
                  song_data.get("thumbnail", {}).get("thumbnails") or [])
        thumbs = best_thumbnails_list(raw)
        result = {
            "video_id":          video_id,
            "videoId":           video_id,
            "url":               f"https://www.youtube.com/watch?v={video_id}",
            "audio_url":         f"https://www.youtube.com/watch?v={video_id}",
            "stream_url":        f"https://www.youtube.com/watch?v={video_id}",
            "title":             vd.get("title", ""),
            "artist":            vd.get("author", ""),
            "channel_id":        vd.get("channelId", ""),
            "duration_seconds":  int(vd.get("lengthSeconds") or 0),
            "views":             int(vd.get("viewCount") or 0),
            "keywords":          vd.get("keywords", [])[:10],
            "is_live":           vd.get("isLiveContent", False),
            "thumbnails":        thumbs,
            "thumbnail":         thumbs[0]["url"] if thumbs else "",
        }
        _cache_long.set(cache_key, result)
        response.headers.update(_cc(3_600))
        return result
    except HTTPException:
        raise
    except Exception as e:
        log.error("get_stream %s: %s", video_id, e)
        raise HTTPException(500, detail=str(e))


@app.get("/now_playing/{video_id}", tags=["song"])
@limiter.limit("60/minute")
async def now_playing(
    request:       Request,
    response:      Response,
    video_id:      str,
    related_limit: int = Query(10, ge=1, le=30),
    country:       str = Query("ZZ"),
    language:      str = Query("en"),
):
    cache_key = f"now_playing:{video_id}:{related_limit}:{country}:{language}"
    cached    = _cache_long.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(1_800))
        return cached

    ytm = get_ytm(country, language)
    song_data, watch_data = await asyncio.gather(
        run(ytm.get_song, video_id),
        run(ytm.get_watch_playlist, video_id, None, related_limit + 1),
        return_exceptions=True,
    )

    stream: dict = {}
    if isinstance(song_data, dict):
        vd     = song_data.get("videoDetails", {})
        raw    = (vd.get("thumbnail", {}).get("thumbnails") or
                  song_data.get("thumbnail", {}).get("thumbnails") or [])
        thumbs = best_thumbnails_list(raw)
        stream = {
            "videoId":          video_id,
            "url":              f"https://www.youtube.com/watch?v={video_id}",
            "audio_url":        f"https://www.youtube.com/watch?v={video_id}",
            "title":            vd.get("title", ""),
            "artist":           vd.get("author", ""),
            "duration_seconds": int(vd.get("lengthSeconds") or 0),
            "thumbnails":       thumbs,
            "thumbnail":        thumbs[0]["url"] if thumbs else "",
        }

    related: list = []
    if isinstance(watch_data, dict):
        tracks_raw = watch_data.get("tracks") or []
        if tracks_raw and tracks_raw[0].get("videoId") == video_id:
            tracks_raw = tracks_raw[1:]
        related = [norm_track(t) for t in tracks_raw[:related_limit] if t.get("videoId")]

    result = {"videoId": video_id, "stream": stream, "related": related}
    _cache_long.set(cache_key, result, ttl=1_800)
    response.headers.update(_cc(1_800))
    return result


@app.get("/related_songs/{video_id}", tags=["song"])
@limiter.limit("30/minute")
async def get_related_songs(
    request:   Request,
    response:  Response,
    video_id:  str,
    limit:     int = Query(15, ge=1, le=50),
    country:   str = Query("ZZ"),
    language:  str = Query("en"),
):
    cache_key = f"related:{video_id}:{limit}:{country}:{language}"
    cached    = _cache_long.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(1_800))
        return cached
    try:
        raw        = await run(get_ytm(country, language).get_watch_playlist, video_id, None, limit + 1)
        tracks_raw = raw.get("tracks") or []
        if tracks_raw and tracks_raw[0].get("videoId") == video_id:
            tracks_raw = tracks_raw[1:]
        tracks = [norm_track(t) for t in tracks_raw[:limit] if t.get("videoId")]
        result = {"videoId": video_id, "tracks": tracks, "count": len(tracks)}
        _cache_long.set(cache_key, result, ttl=1_800)
        response.headers.update(_cc(1_800))
        return result
    except Exception as e:
        log.error("related_songs %s: %s", video_id, e)
        raise HTTPException(500, detail=str(e))

# ─────────────────────────────────────────────────────────────────────────────
#  Up-Next
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/upnext/{video_id}", tags=["song"])
@limiter.limit("30/minute")
async def get_upnext(
    request:       Request,
    response:      Response,
    video_id:      str,
    limit:         int  = Query(20, ge=5, le=50),
    force_refresh: bool = Query(False),
    country:       str = Query("ZZ"),
    language:      str = Query("en"),
):
    store_key = f"{video_id}:{country}:{language}"
    now       = time.time()
    with _upnext_lock:
        existing = _upnext_store.get(store_key)
    if existing and not force_refresh:
        if now - existing.get("created_at", 0) < _UPNEXT_TTL:
            response.headers.update(_cc(300))
            return existing
    try:
        raw        = await run(get_ytm(country, language).get_watch_playlist, video_id, None, limit)
        tracks_raw = raw.get("tracks") or []
        if tracks_raw and tracks_raw[0].get("videoId") == video_id:
            tracks_raw = tracks_raw[1:]
        tracks = [norm_track(t) for t in tracks_raw if t.get("videoId")]
        queue  = {
            "origin_video_id": video_id,
            "tracks":          tracks,
            "count":           len(tracks),
            "created_at":      now,
            "country":         country,
        }
        with _upnext_lock:
            _upnext_store[store_key] = queue
            _upnext_store.move_to_end(store_key)
            while len(_upnext_store) > _UPNEXT_MAX:
                _upnext_store.popitem(last=False)
        response.headers.update(_cc(300))
        return queue
    except Exception as e:
        log.error("upnext %s: %s", video_id, e)
        raise HTTPException(500, detail=str(e))


@app.delete("/upnext/{video_id}", tags=["song"])
async def reset_upnext(video_id: str, country: str = Query("ZZ"), language: str = Query("en")):
    store_key = f"{video_id}:{country}:{language}"
    with _upnext_lock:
        _upnext_store.pop(store_key, None)
    return {"cleared": store_key}

# ─────────────────────────────────────────────────────────────────────────────
#  Artist
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/artist/{artist_id}", tags=["artist"])
@limiter.limit("30/minute")
async def get_artist(
    request:   Request,
    response:  Response,
    artist_id: str,
    country:   str = Query("ZZ"),
    language:  str = Query("en"),
):
    cache_key = f"artist:{artist_id}:{country}:{language}"
    cached    = _cache_long.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(3_600))
        return cached
    try:
        data = await run(get_ytm(country, language).get_artist, artist_id)
        if not data:
            raise HTTPException(404, "Artist not found")
        data["thumbnails"] = best_thumbnails_list(data.get("thumbnails") or [])
        data["thumbnail"]  = data["thumbnails"][0]["url"] if data["thumbnails"] else ""
        _cache_long.set(cache_key, data)
        response.headers.update(_cc(3_600))
        return data
    except HTTPException:
        raise
    except Exception as e:
        log.error("get_artist %s: %s", artist_id, e)
        raise HTTPException(500, detail=str(e))


@app.get("/artist/{artist_id}/songs", tags=["artist"])
@limiter.limit("20/minute")
async def get_artist_songs(
    request:   Request,
    response:  Response,
    artist_id: str,
    limit:     int = Query(20, ge=1, le=100),
    country:   str = Query("ZZ"),
    language:  str = Query("en"),
):
    cache_key = f"artist_songs:{artist_id}:{limit}:{country}:{language}"
    cached    = _cache_long.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(600))
        return cached
    try:
        ytm         = get_ytm(country, language)
        artist_data = await run(ytm.get_artist, artist_id)
        if not artist_data:
            raise HTTPException(404, "Artist not found")
        artist_name   = artist_data.get("name", "")
        songs_section = artist_data.get("songs", {})
        all_tracks: list  = []
        albums_info: list = []

        if isinstance(songs_section, dict) and songs_section.get("browseId"):
            try:
                songs_raw = await run(ytm.get_artist_songs, artist_id, songs_section.get("params"))
                all_tracks.extend(songs_raw or [])
            except Exception:
                all_tracks.extend(songs_section.get("results") or [])
        else:
            all_tracks.extend(songs_section.get("results") or [])

        for section_key in ("albums", "singles"):
            section = artist_data.get(section_key, {})
            if not isinstance(section, dict):
                continue
            entries = section.get("results") or section.get("items") or []
            for entry in entries[:3]:
                thumbs = best_thumbnails_list(entry.get("thumbnails") or [])
                albums_info.append({
                    "browseId":   entry.get("browseId", ""),
                    "title":      entry.get("title", ""),
                    "year":       entry.get("year", ""),
                    "type":       entry.get("type", "Album"),
                    "thumbnails": thumbs,
                    "thumbnail":  thumbs[0]["url"] if thumbs else "",
                    "trackCount": len(entry.get("tracks") or []),
                })
                for t in entry.get("tracks") or []:
                    if isinstance(t, dict) and t.get("videoId"):
                        if not t.get("album"):
                            t = dict(t)
                            t["album"] = {"name": entry.get("title", "")}
                        all_tracks.append(t)

        seen, deduped = set(), []
        for t in all_tracks:
            vid = t.get("videoId", "")
            if vid and vid not in seen:
                seen.add(vid)
                deduped.append(norm_track(t))

        result = {
            "artistId": artist_id,
            "name":     artist_name,
            "songs":    deduped[:limit],
            "total":    len(deduped),
            "albums":   albums_info,
        }
        _cache_long.set(cache_key, result)
        response.headers.update(_cc(600))
        return result
    except HTTPException:
        raise
    except Exception as e:
        log.error("artist_songs %s: %s", artist_id, e)
        raise HTTPException(500, detail=str(e))


@app.get("/artist/{artist_id}/albums", tags=["artist"])
@limiter.limit("20/minute")
async def get_artist_albums(
    request:   Request,
    response:  Response,
    artist_id: str,
    country:   str = Query("ZZ"),
    language:  str = Query("en"),
):
    cache_key = f"artist_albums:{artist_id}:{country}:{language}"
    cached    = _cache_long.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(600))
        return cached
    try:
        ytm         = get_ytm(country, language)
        artist_data = await run(ytm.get_artist, artist_id)
        if not artist_data:
            raise HTTPException(404, "Artist not found")
        artist_name = artist_data.get("name", "")
        channel_id  = artist_data.get("channelId", artist_id)
        album_entries: list = []
        for section_key in ("albums", "singles"):
            section = artist_data.get(section_key, {})
            if not isinstance(section, dict):
                continue
            params = section.get("params")
            if params and channel_id:
                try:
                    more = await run(ytm.get_artist_albums, channel_id, params)
                    album_entries.extend(
                        more if isinstance(more, list) else
                        (more.get("results") or more.get("items") or [])
                    )
                except Exception:
                    album_entries.extend(section.get("results") or section.get("items") or [])
            else:
                album_entries.extend(section.get("results") or section.get("items") or [])

        async def _album_detail(entry: dict) -> dict:
            bid    = entry.get("browseId")
            thumbs = best_thumbnails_list(entry.get("thumbnails") or [])
            base   = {
                "browseId": bid or "", "title": entry.get("title", ""),
                "year":     entry.get("year", ""), "type": entry.get("type", "Album"),
                "thumbnails": thumbs, "thumbnail": thumbs[0]["url"] if thumbs else "",
                "tracks": [],
            }
            if not bid:
                return base
            try:
                d = await run(ytm.get_album, bid)
                base["tracks"] = [norm_track(t) for t in (d.get("tracks") or []) if t.get("videoId")]
            except Exception:
                pass
            return base

        albums_out: list = []
        for i in range(0, len(album_entries), 5):
            batch   = album_entries[i:i+5]
            results = await asyncio.gather(*[_album_detail(e) for e in batch])
            albums_out.extend(results)

        result = {
            "artistId":    artist_id,
            "name":        artist_name,
            "albums":      albums_out,
            "totalAlbums": len(albums_out),
            "totalTracks": sum(len(a["tracks"]) for a in albums_out),
        }
        _cache_long.set(cache_key, result)
        response.headers.update(_cc(600))
        return result
    except HTTPException:
        raise
    except Exception as e:
        log.error("artist_albums %s: %s", artist_id, e)
        raise HTTPException(500, detail=str(e))

# ─────────────────────────────────────────────────────────────────────────────
#  Album
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/album/{album_id}", tags=["album"])
@limiter.limit("30/minute")
async def get_album(
    request:  Request,
    response: Response,
    album_id: str,
    country:  str = Query("ZZ"),
    language: str = Query("en"),
):
    cache_key = f"album:{album_id}:{country}:{language}"
    cached    = _cache_long.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(3_600))
        return cached
    try:
        data = await run(get_ytm(country, language).get_album, album_id)
        if not data:
            raise HTTPException(404, "Album not found")
        data["thumbnails"] = best_thumbnails_list(data.get("thumbnails") or [])
        data["thumbnail"]  = data["thumbnails"][0]["url"] if data["thumbnails"] else ""
        data["tracks"]     = [norm_track(t) for t in (data.get("tracks") or [])]
        _cache_long.set(cache_key, data)
        response.headers.update(_cc(3_600))
        return data
    except HTTPException:
        raise
    except Exception as e:
        log.error("get_album %s: %s", album_id, e)
        raise HTTPException(500, detail=str(e))

# ─────────────────────────────────────────────────────────────────────────────
#  Playlist
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/playlist/{playlist_id}", tags=["playlist"])
@limiter.limit("30/minute")
async def get_playlist(
    request:      Request,
    response:     Response,
    playlist_id:  str,
    limit:        int  = Query(100, ge=1, le=500),
    related:      bool = False,
    suggestions_limit: int = 0,
    country:      str = Query("ZZ"),
    language:     str = Query("en"),
):
    clean_id  = playlist_id[2:] if playlist_id.startswith("VL") else playlist_id
    cache_key = f"playlist:{clean_id}:{limit}:{country}:{language}"
    cached    = _cache_medium.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(300))
        return cached
    try:
        data = await run(
            get_ytm(country, language).get_playlist,
            clean_id, limit, related, suggestions_limit,
        )
        if not data:
            raise HTTPException(404, "Playlist not found")
        data["tracks"]     = [norm_track(t) for t in (data.get("tracks") or []) if isinstance(t, dict)]
        data["thumbnails"] = best_thumbnails_list(data.get("thumbnails") or [])
        data["thumbnail"]  = data["thumbnails"][0]["url"] if data["thumbnails"] else ""
        _cache_medium.set(cache_key, data)
        response.headers.update(_cc(300))
        return data
    except HTTPException:
        raise
    except Exception as e:
        log.error("get_playlist %s: %s", playlist_id, e)
        raise HTTPException(500, detail=str(e))

# ─────────────────────────────────────────────────────────────────────────────
#  Podcast
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/podcast/{podcast_id}", tags=["podcast"])
@limiter.limit("20/minute")
async def get_podcast(
    request:    Request,
    response:   Response,
    podcast_id: str,
    limit:      int = Query(50, ge=1, le=200),
    country:    str = Query("ZZ"),
    language:   str = Query("en"),
):
    clean_id = (podcast_id[2:]
                if podcast_id.startswith("VL") and not podcast_id.startswith("VLM")
                else podcast_id)
    cache_key = f"podcast:{clean_id}:{limit}:{country}:{language}"
    cached    = _cache_long.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(1_800))
        return cached

    ytm          = get_ytm(country, language)
    episodes_raw: list = []
    meta: dict         = {}

    for fn, *fn_args in [
        (ytm.get_podcast,  clean_id),
        (ytm.get_playlist, clean_id, limit),
        (ytm.get_podcast,  podcast_id),
        (ytm.get_playlist, podcast_id, limit),
    ]:
        if episodes_raw:
            break
        try:
            data = await run(fn, *fn_args)
            if isinstance(data, dict) and data:
                if not meta:
                    meta = data
                episodes_raw = data.get("episodes") or data.get("tracks") or []
        except Exception:
            pass

    if not meta and not episodes_raw:
        raise HTTPException(404, "Podcast not found")

    def _norm_ep(ep: dict) -> dict:
        raw_t = ep.get("thumbnails") or ep.get("thumbnail") or []
        if isinstance(raw_t, str):
            raw_t = [{"url": raw_t, "width": 0}]
        thumbs = best_thumbnails_list(raw_t)
        dur    = ep.get("duration") or ep.get("durationSeconds") or ""
        if isinstance(dur, int) and dur > 0:
            m, s = divmod(dur, 60)
            h, m = divmod(m, 60)
            dur  = f"{h}:{m:02d}:{s:02d}" if h else f"{m}:{s:02d}"
        artists = ep.get("artists") or ep.get("author") or ""
        if isinstance(artists, list):
            artists = ", ".join(
                a.get("name", "") if isinstance(a, dict) else str(a) for a in artists
            )
        return {
            "videoId":    ep.get("videoId", "") or ep.get("id", ""),
            "title":      ep.get("title", ""),
            "author":     artists,
            "duration":   dur,
            "date":       ep.get("date", "") or ep.get("publishedAt", ""),
            "thumbnails": thumbs,
            "thumbnail":  thumbs[0]["url"] if thumbs else "",
            "description":ep.get("description", ""),
        }

    thumbs_p = best_thumbnails_list(meta.get("thumbnails") or [])
    result   = {
        "podcastId":  clean_id,
        "title":      meta.get("title", ""),
        "author":     meta.get("author", ""),
        "description":meta.get("description", ""),
        "thumbnails": thumbs_p,
        "thumbnail":  thumbs_p[0]["url"] if thumbs_p else "",
        "episodes":   [_norm_ep(ep) for ep in episodes_raw[:limit] if isinstance(ep, dict)],
        "count":      min(len(episodes_raw), limit),
    }
    _cache_long.set(cache_key, result, ttl=1_800)
    response.headers.update(_cc(1_800))
    return result

# ─────────────────────────────────────────────────────────────────────────────
#  Watch playlist / lyrics
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/watch/{video_id}", tags=["song"])
@limiter.limit("30/minute")
async def get_watch_playlist(
    request:   Request,
    response:  Response,
    video_id:  str,
    limit:     int = Query(25, ge=1, le=50),
    country:   str = Query("ZZ"),
    language:  str = Query("en"),
):
    cache_key = f"watch:{video_id}:{limit}:{country}:{language}"
    cached    = _cache_long.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(1_800))
        return cached
    try:
        raw        = await run(get_ytm(country, language).get_watch_playlist, video_id, None, limit)
        tracks_raw = raw.get("tracks") or []
        tracks     = [norm_track(t) for t in tracks_raw if isinstance(t, dict) and t.get("videoId")]
        result     = {
            "videoId":  video_id,
            "tracks":   tracks,
            "count":    len(tracks),
            "lyrics":   raw.get("lyrics") or raw.get("lyricsId") or "",
            "related":  raw.get("related") or "",
        }
        _cache_long.set(cache_key, result, ttl=1_800)
        response.headers.update(_cc(1_800))
        return result
    except Exception as e:
        log.error("watch %s: %s", video_id, e)
        raise HTTPException(500, detail=str(e))


@app.get("/lyrics/{browse_id}", tags=["song"])
@limiter.limit("30/minute")
async def get_lyrics(
    request:   Request,
    response:  Response,
    browse_id: str,
    country:   str = Query("ZZ"),
    language:  str = Query("en"),
):
    cache_key = f"lyrics:{browse_id}"
    cached    = _cache_long.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(86_400))
        return cached
    try:
        data = await run(get_ytm(country, language).get_lyrics, browse_id)
        _cache_long.set(cache_key, data or {})
        response.headers.update(_cc(86_400))
        return data or {}
    except Exception as e:
        log.warning("get_lyrics %s: %s", browse_id, e)
        raise HTTPException(500, detail=str(e))

# ─────────────────────────────────────────────────────────────────────────────
#  Genres / featured playlists
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/genres", tags=["discovery"])
@limiter.limit("30/minute")
async def get_genres(
    request:  Request,
    response: Response,
    country:  str = Query("ZZ"),
    language: str = Query("en"),
    limit:    int = Query(50, ge=1, le=200),
):
    cache_key = f"genres:{country}:{language}:{limit}"
    cached    = _cache_medium.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(600))
        return cached

    ytm_task    = run(get_ytm(country, language).get_charts, country)
    deezer_task = _fetch_deezer_editorial_playlists(20)

    ytm_charts_raw, deezer_playlists = await asyncio.gather(
        ytm_task, deezer_task, return_exceptions=True
    )

    playlists: list = []
    if not isinstance(ytm_charts_raw, Exception) and isinstance(ytm_charts_raw, dict):
        for sk in ("playlists", "genres", "moods", "trending"):
            section = ytm_charts_raw.get(sk, {})
            items   = section if isinstance(section, list) else (
                section.get("items") or section.get("results") or []
            )
            for item in items:
                if not isinstance(item, dict):
                    continue
                bid = item.get("browseId") or item.get("playlistId")
                if bid and item.get("title"):
                    thumbs = best_thumbnails_list(item.get("thumbnails") or [])
                    playlists.append({
                        "browseId":   bid,
                        "title":      item.get("title", ""),
                        "subtitle":   item.get("subtitle", "") or item.get("author", ""),
                        "thumbnails": thumbs,
                        "thumbnail":  thumbs[0]["url"] if thumbs else "",
                        "source":     "ytm",
                    })

    try:
        cats         = await run(get_ytm(country, language).get_mood_categories)
        first_params = None
        if isinstance(cats, dict):
            for items in cats.values():
                if isinstance(items, list) and items:
                    p = items[0].get("params")
                    if p:
                        first_params = p
                        break
        elif isinstance(cats, list) and cats:
            first_params = cats[0].get("params")
        if first_params:
            mood_raw = await run(get_ytm(country, language).get_mood_playlists, first_params)
            for section in (mood_raw or []):
                if not isinstance(section, dict):
                    continue
                for item in (section.get("contents") or section.get("playlists") or []):
                    if not isinstance(item, dict):
                        continue
                    bid = item.get("playlistId") or item.get("browseId")
                    if bid:
                        thumbs = best_thumbnails_list(item.get("thumbnails") or [])
                        playlists.append({
                            "browseId":   bid,
                            "title":      item.get("title", ""),
                            "subtitle":   item.get("subtitle", ""),
                            "thumbnails": thumbs,
                            "thumbnail":  thumbs[0]["url"] if thumbs else "",
                            "source":     "ytm",
                        })
    except Exception:
        pass

    if not isinstance(deezer_playlists, Exception):
        playlists.extend(deezer_playlists)

    seen, deduped = set(), []
    for p in playlists:
        bid = p.get("browseId", "")
        if bid and bid not in seen:
            seen.add(bid)
            deduped.append(p)

    result = deduped[:limit]
    _cache_medium.set(cache_key, result)
    response.headers.update(_cc(600))
    return result

# ─────────────────────────────────────────────────────────────────────────────
#  Mood categories & playlists
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/mood_categories", tags=["discovery"])
@limiter.limit("30/minute")
async def get_mood_categories(
    request:  Request,
    response: Response,
    country:  str = Query("ZZ"),
    language: str = Query("en"),
):
    cache_key = f"mood_categories:{country}:{language}"
    cached    = _cache_medium.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(600))
        return cached
    try:
        ytm_task    = run(get_ytm(country, language).get_mood_categories)
        deezer_task = _fetch_deezer_genres()
        ytm_raw, deezer_genres = await asyncio.gather(ytm_task, deezer_task, return_exceptions=True)

        categories: list = []
        if not isinstance(ytm_raw, Exception):
            categories = _flatten_mood_categories(ytm_raw)

        existing_titles = {c["title"].lower() for c in categories}
        if not isinstance(deezer_genres, Exception):
            for g in deezer_genres:
                if g.get("title", "").lower() not in existing_titles:
                    g["section"] = "Genres"
                    categories.append(g)
                    existing_titles.add(g["title"].lower())

        _cache_medium.set(cache_key, categories)
        response.headers.update(_cc(600))
        return categories
    except Exception as e:
        log.error("mood_categories country=%s: %s", country, e)
        raise HTTPException(500, detail=str(e))


@app.get("/mood_playlists/{params}", tags=["discovery"])
@limiter.limit("30/minute")
async def get_mood_playlists(
    request:  Request,
    response: Response,
    params:   str,
    country:  str = Query("ZZ"),
    language: str = Query("en"),
):
    cache_key = f"mood_playlists:{params}:{country}:{language}"
    cached    = _cache_medium.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(600))
        return cached
    try:
        raw       = await run(get_ytm(country, language).get_mood_playlists, params)
        playlists: list = []
        for section in (raw if isinstance(raw, list) else []):
            if not isinstance(section, dict):
                continue
            contents = section.get("contents") or section.get("playlists") or []
            if isinstance(contents, list):
                for item in contents:
                    if not isinstance(item, dict):
                        continue
                    thumbs = best_thumbnails_list(item.get("thumbnails") or [])
                    playlists.append({
                        "browseId":   item.get("playlistId") or item.get("browseId", ""),
                        "title":      item.get("title", ""),
                        "subtitle":   item.get("subtitle", ""),
                        "thumbnails": thumbs,
                        "thumbnail":  thumbs[0]["url"] if thumbs else "",
                    })
            else:
                thumbs = best_thumbnails_list(section.get("thumbnails") or [])
                playlists.append({
                    "browseId":   section.get("playlistId") or section.get("browseId", ""),
                    "title":      section.get("title", ""),
                    "subtitle":   section.get("subtitle", ""),
                    "thumbnails": thumbs,
                    "thumbnail":  thumbs[0]["url"] if thumbs else "",
                })
        _cache_medium.set(cache_key, playlists)
        response.headers.update(_cc(600))
        return playlists
    except Exception as e:
        log.error("mood_playlists params=%s: %s", params, e)
        raise HTTPException(500, detail=str(e))

# ─────────────────────────────────────────────────────────────────────────────
#  Explore
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/explore", tags=["discovery"])
@limiter.limit("30/minute")
async def get_explore(
    request:  Request,
    response: Response,
    country:  str = Query("ZZ"),
    language: str = Query("en"),
):
    cache_key = f"explore:{country}:{language}"
    cached    = _cache_medium.get(cache_key)
    if cached is not None:
        response.headers.update(_cc(600))
        return cached
    try:
        data = await run(get_ytm(country, language).get_explore)
        _cache_medium.set(cache_key, data)
        response.headers.update(_cc(600))
        return data
    except Exception as e:
        log.error("get_explore country=%s: %s", country, e)
        raise HTTPException(500, detail=str(e))

# ─────────────────────────────────────────────────────────────────────────────
#  User
# ─────────────────────────────────────────────────────────────────────────────

@app.get("/user/{channel_id}", tags=["user"])
async def get_user(
    response:   Response,
    channel_id: str,
    country:    str = Query("ZZ"),
    language:   str = Query("en"),
):
    cache_key = f"user:{channel_id}:{country}:{language}"
    cached    = _cache_long.get(cache_key)
    if cached is not None:
        return cached
    try:
        data = await run(get_ytm(country, language).get_user, channel_id)
        _cache_long.set(cache_key, data)
        return data
    except Exception as e:
        log.error("get_user %s: %s", channel_id, e)
        raise HTTPException(500, detail=str(e))


@app.get("/user_playlists/{channel_id}", tags=["user"])
async def get_user_playlists(
    response:   Response,
    channel_id: str,
    params:     Optional[str] = None,
    country:    str = Query("ZZ"),
    language:   str = Query("en"),
):
    try:
        data = await run(get_ytm(country, language).get_user_playlists, channel_id, params)
        return data
    except Exception as e:
        log.error("user_playlists %s: %s", channel_id, e)
        raise HTTPException(500, detail=str(e))