File size: 116,042 Bytes
f697c3b
36dde81
f697c3b
36dde81
 
 
 
07f63a8
d3a7f5b
36dde81
 
 
 
 
 
 
 
 
 
 
 
bed5e23
 
36dde81
 
 
bed5e23
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
36dde81
 
 
 
 
d3a7f5b
 
36dde81
 
d3a7f5b
 
 
36dde81
d3a7f5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404692
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1404692
 
 
 
36dde81
 
1404692
 
36dde81
 
 
1404692
36dde81
 
 
 
1404692
36dde81
 
1404692
36dde81
 
1404692
36dde81
 
 
1404692
 
 
 
36dde81
1404692
 
 
36dde81
1404692
 
 
 
36dde81
 
1404692
 
 
 
 
 
 
 
36dde81
1404692
 
 
36dde81
1404692
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
1404692
 
 
 
 
 
 
 
 
 
36dde81
1404692
 
 
36dde81
1404692
 
 
 
 
 
 
 
 
36dde81
 
1404692
14ad4e9
1404692
 
 
 
 
 
 
 
36dde81
1404692
36dde81
1404692
14ad4e9
1404692
14ad4e9
1404692
 
 
 
 
 
36dde81
1404692
36dde81
1404692
 
 
 
 
 
 
 
 
36dde81
 
1404692
 
 
 
 
 
 
 
d3a7f5b
 
36dde81
 
 
 
 
 
 
 
 
d3a7f5b
 
 
 
 
36dde81
d3a7f5b
 
36dde81
 
 
 
d3a7f5b
 
36dde81
 
d3a7f5b
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d3a7f5b
 
 
 
 
36dde81
d3a7f5b
36dde81
 
d3a7f5b
36dde81
d3a7f5b
 
f697c3b
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
f697c3b
36dde81
f697c3b
 
36dde81
f697c3b
 
 
36dde81
f697c3b
36dde81
 
f697c3b
 
 
 
 
36dde81
f697c3b
 
 
 
 
 
 
 
36dde81
f697c3b
 
36dde81
f697c3b
 
 
 
36dde81
f697c3b
 
36dde81
 
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
f697c3b
 
 
 
 
 
 
 
 
36dde81
f697c3b
 
36dde81
f697c3b
 
 
 
 
36dde81
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
f697c3b
 
 
36dde81
f697c3b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
f697c3b
 
 
 
36dde81
f697c3b
 
36dde81
f697c3b
 
 
 
 
36dde81
f697c3b
 
 
 
 
36dde81
f697c3b
 
36dde81
 
f697c3b
 
 
 
 
36dde81
f697c3b
 
 
 
 
 
36dde81
 
f697c3b
 
 
 
 
36dde81
f697c3b
 
36dde81
 
f697c3b
 
 
 
 
 
 
36dde81
 
f697c3b
 
 
 
 
 
e581a8c
 
36dde81
 
51ebe66
 
 
 
 
 
 
 
 
 
 
 
e581a8c
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e581a8c
 
 
 
 
 
 
 
 
 
 
36dde81
e581a8c
 
 
36dde81
e581a8c
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
e581a8c
 
 
36dde81
e581a8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
e581a8c
 
 
 
 
 
 
 
36dde81
 
e581a8c
36dde81
e581a8c
3e18b74
36dde81
 
3e18b74
 
 
 
 
 
 
 
36dde81
3e18b74
 
 
 
 
 
e581a8c
36dde81
3e18b74
e581a8c
 
 
 
 
 
 
 
36dde81
e581a8c
 
 
 
 
 
36dde81
 
07f63a8
e581a8c
 
 
 
 
 
 
36dde81
e581a8c
36dde81
 
e581a8c
36dde81
 
 
 
 
 
 
 
 
 
 
 
e581a8c
36dde81
e581a8c
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e581a8c
36dde81
 
e581a8c
36dde81
 
 
 
 
e581a8c
 
 
 
36dde81
e581a8c
36dde81
 
 
e581a8c
36dde81
e581a8c
 
 
 
36dde81
 
 
 
e581a8c
07f63a8
e581a8c
 
36dde81
 
 
e581a8c
 
 
 
36dde81
e581a8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
e581a8c
 
36dde81
e581a8c
 
36dde81
e581a8c
36dde81
e581a8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
e581a8c
 
36dde81
 
 
 
 
 
 
e581a8c
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e581a8c
 
36dde81
 
 
 
 
 
 
 
 
 
 
e581a8c
36dde81
 
e581a8c
 
 
 
c778c21
 
36dde81
c778c21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
c778c21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
c778c21
 
 
 
 
 
 
 
 
b5f02cc
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5f02cc
36dde81
 
b5f02cc
 
 
 
 
36dde81
b5f02cc
 
 
 
36dde81
 
 
b5f02cc
 
 
 
 
 
 
 
36dde81
 
b5f02cc
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5f02cc
 
 
 
 
36dde81
 
b5f02cc
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
b5f02cc
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b5f02cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
b5f02cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
b5f02cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
b5f02cc
36dde81
b5f02cc
 
 
 
36dde81
b5f02cc
 
 
36dde81
b5f02cc
 
 
 
 
 
 
 
 
36dde81
 
b5f02cc
bed5e23
 
36dde81
bed5e23
36dde81
bed5e23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
36dde81
 
 
 
 
 
 
 
07f63a8
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
36dde81
 
 
 
 
 
 
 
 
07f63a8
36dde81
07f63a8
36dde81
07f63a8
36dde81
07f63a8
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
36dde81
07f63a8
 
36dde81
 
07f63a8
36dde81
 
07f63a8
 
 
 
36dde81
07f63a8
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c12bb0b
 
 
36dde81
 
 
c12bb0b
07f63a8
e2c4766
 
 
36dde81
 
 
e2c4766
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
07f63a8
36dde81
 
 
 
07f63a8
 
 
36dde81
 
 
07f63a8
 
 
 
 
 
 
 
 
 
532c525
 
 
36dde81
532c525
 
36dde81
532c525
 
 
 
 
 
 
 
36dde81
532c525
 
 
36dde81
 
532c525
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532c525
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532c525
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532c525
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36dde81
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
import asyncio
import asyncio
import json
import os
import random
import secrets
import shutil
from datetime import datetime
from time import time

from fastapi import HTTPException, Query, Request
from fastapi.responses import FileResponse, StreamingResponse
from pyrogram.enums import ChatMemberStatus, ChatMembersFilter
from pyrogram.errors import FloodWait
from pyrogram.types import ChatPrivileges

import Backend
from Backend import StartTime, __version__, db
from Backend.fastapi.routes.stream_routes import _streamer_by_client
from Backend.fastapi.routes.stremio_routes import invalidate_membership_cache
from Backend.helper.analytics import get_activity_overview
from Backend.helper.auto_catalog import (
    get_auto_catalog_settings,
    get_auto_catalog_sync_status,
    start_auto_catalog_sync_background,
    start_single_media_catalog_sync,
    update_auto_catalog_settings,
)
from Backend.helper.backup import export_config, import_config
from Backend.helper.custom_dl import ByteStreamer, _speed_test_single_client, run_speed_test
from Backend.helper.encrypt import decode_string, encode_string
from Backend.helper.health import run_health_checks
from Backend.helper.manual_add import resolve_telegram_message, retag_media, stamp_caption_by_ref
from Backend.helper import own_bots
from Backend.helper.pyro import resolve_video_thumb_url
from Backend.helper.requests_manager import (
    delete_request,
    list_requests,
    popular_pending,
    search_titles,
    set_status,
    submit_request,
)
from Backend.helper.metadata import (
    build_id_link,
    extract_default_id,
    fetch_selected_movie_metadata,
    fetch_selected_tv_metadata,
    gradient_cover_path,
    resolve_cover_url,
    search_any_candidates,
    search_movie_candidates,
    search_tv_candidates,
)
from Backend.helper.passwords import hash_password, verify_password
from Backend.helper.pyro import get_readable_file_size, get_readable_time
from Backend.helper.scan_manager import dbcheck_manager, duplicate_manager, scan_manager
from Backend.helper.session_auth import (
    disconnect_session,
    get_session_status,
    reconnect_session,
    remove_session,
    start_login,
    submit_code,
    submit_password,
)
from Backend.helper.settings_manager import SettingsManager
from Backend.helper.split_files import strip_part_suffix
from Backend.helper.subtitles import (
    list_languages,
    list_title_subtitles,
    manual_ingest_subtitle,
    remove_subtitle,
    resolve_subtitle_message,
)
from Backend.logger import LOGGER
import Backend.pyrofork.bot as botmod
from Backend.helper.announcer import delete_announcement_async
from Backend.pyrofork.bot import (
    StreamBot,
    client_avg_mbps,
    client_dc_map,
    client_failures,
    multi_clients,
    work_loads,
)




def _coerce_tmdb_id(value):
    """Accept int or string; treat 'null'/''/None as missing."""
    if value is None:
        return None
    if isinstance(value, int):
        return value
    s = str(value).strip()
    if not s or s.lower() in ("null", "none", "undefined"):
        return None
    try:
        return int(float(s))
    except (TypeError, ValueError):
        return None


def _require_tmdb_id(value) -> int:
    tid = _coerce_tmdb_id(value)
    if tid is None:
        raise HTTPException(status_code=400, detail="tmdb_id is required and must be an integer")
    return tid



#----- System stats
async def get_system_stats_api():
    try:
        db_stats = await db.get_database_stats()
        total_movies, total_tv_shows = db.content_totals(db_stats)
        api_tokens = await db.get_all_api_tokens()
        
        return {
            "server_status": "running",
            "uptime": get_readable_time(time() - StartTime),
            "telegram_bot": f"@{StreamBot.username}" if StreamBot and StreamBot.username else "@StreamBot",
            "connected_bots": len(multi_clients),
            "version": __version__,
            "movies": total_movies,
            "tv_shows": total_tv_shows,
            "databases": db_stats,
            "total_databases": len(db_stats),
            "current_db_index": db.current_db_index,
            "api_tokens": api_tokens
        }
    except Exception as e:
        print(f"System Stats API Error: {e}")
        return {
            "server_status": "error", 
            "error": str(e)
        }


#----- Expand stored gradient cover paths into full URLs for UI responses
def _resolve_covers(items) -> None:
    for item in items or []:
        for key in ("poster", "backdrop"):
            if item.get(key):
                item[key] = resolve_cover_url(item[key])


_LIST_PROJECTION = {k: 0 for k in (
    "description", "cast", "telegram.name", "seasons.episodes.title", "seasons.episodes.overview",
    "seasons.episodes.episode_backdrop", "seasons.episodes.telegram.name",
)}


#----- Media management
async def list_media_api(
    media_type: str = Query("movie", regex="^(movie|tv)$"),
    page: int = Query(1, ge=1),
    page_size: int = Query(24, ge=1, le=100),
    search: str = Query("", max_length=100),
    custom: bool = Query(False)
):
    try:
        key = "movies" if media_type == "movie" else "tv_shows"
        #----- Custom (manually added) titles carry a negative synthetic tmdb_id
        extra_filter = {"tmdb_id": {"$lt": 0}} if custom else None
        if search:
            result = await db.search_documents(search, page, page_size, extra_filter=extra_filter, media_type=media_type)
            total = result["total_count"]
            resp = {
                "total_count": total,
                "current_page": page,
                "total_pages": (total + page_size - 1) // page_size,
                key: result["results"],
            }
        elif media_type == "movie":
            resp = await db.sort_movies([], page, page_size, extra_filter=extra_filter, projection=_LIST_PROJECTION)
        else:
            resp = await db.sort_tv_shows([], page, page_size, extra_filter=extra_filter, projection=_LIST_PROJECTION)
        _resolve_covers(resp.get(key))
        return resp
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

async def delete_media_api(
    tmdb_id: str | int,
    db_index: int,
    media_type: str = Query(regex="^(movie|tv)$")
):
    tmdb_id = _require_tmdb_id(tmdb_id)
    try:
        media_type_formatted = "Movie" if media_type == "movie" else "Series"
        result = await db.delete_document(media_type_formatted, tmdb_id, db_index)
        if result:
            # Remove matching announcement post from the announcement channel
            delete_announcement_async(media_type, tmdb_id)
            return {"message": "Media deleted successfully"}
        else:
            raise HTTPException(status_code=404, detail="Media not found")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

async def update_media_api(
    request: Request,
    tmdb_id: str | int,
    db_index: int,
    media_type: str = Query(regex="^(movie|tv)$")
):
    tmdb_id = _require_tmdb_id(tmdb_id)
    try:
        update_data = await request.json()
        if 'rating' in update_data and update_data['rating']:
            try:
                update_data['rating'] = float(update_data['rating'])
            except (ValueError, TypeError):
                update_data['rating'] = 0.0
        
        if 'release_year' in update_data and update_data['release_year']:
            try:
                update_data['release_year'] = int(update_data['release_year'])
            except (ValueError, TypeError):
                pass
        if 'genres' in update_data:
            if isinstance(update_data['genres'], str):
                update_data['genres'] = [g.strip() for g in update_data['genres'].split(',') if g.strip()]
            elif not isinstance(update_data['genres'], list):
                update_data['genres'] = []
        
        if 'languages' in update_data:
            if isinstance(update_data['languages'], str):
                update_data['languages'] = [l.strip() for l in update_data['languages'].split(',') if l.strip()]
            elif not isinstance(update_data['languages'], list):
                update_data['languages'] = []
        if media_type == "movie":
            if 'runtime' in update_data and update_data['runtime']:
                try:
                    update_data['runtime'] = int(update_data['runtime'])
                except (ValueError, TypeError):
                    pass
        elif media_type == "tv":
            if 'total_seasons' in update_data and update_data['total_seasons']:
                try:
                    update_data['total_seasons'] = int(update_data['total_seasons'])
                except (ValueError, TypeError):
                    pass
            
            if 'total_episodes' in update_data and update_data['total_episodes']:
                try:
                    update_data['total_episodes'] = int(update_data['total_episodes'])
                except (ValueError, TypeError):
                    pass
        update_data = {k: v for k, v in update_data.items() if v != ""}
        if "title" in update_data:
            update_data["title_english"] = update_data["title"]
        result = await db.update_document(media_type, tmdb_id, db_index, update_data)
        if result:
            return {"message": "Media updated successfully"}
        else:
            raise HTTPException(status_code=404, detail="Media not found or no changes made")
            
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

async def get_media_details_api(
    tmdb_id: str | int,
    db_index: int,
    media_type: str = Query(regex="^(movie|tv)$")
):
    tmdb_id = _require_tmdb_id(tmdb_id)
    try:
        result = await db.get_document(media_type, tmdb_id, db_index)
        if result:
            return result
        else:
            raise HTTPException(status_code=404, detail="Media not found")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

async def delete_movie_quality_api(tmdb_id: str | int, db_index: int, id: str):
    tmdb_id = _require_tmdb_id(tmdb_id)
    try:
        result = await db.delete_movie_quality(tmdb_id, db_index, id)
        if result:
            return {"message": "Quality deleted successfully"}
        else:
            raise HTTPException(status_code=404, detail="Quality not found")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

async def delete_tv_quality_api(
    tmdb_id: str | int, db_index: int, season: int, episode: int, id: str
):
    tmdb_id = _require_tmdb_id(tmdb_id)
    try:
        result = await db.delete_tv_quality(tmdb_id, db_index, season, episode, id)
        if result:
            return {"message": "deleted successfully"}
        else:
            raise HTTPException(status_code=404, detail="Quality not found")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

async def delete_tv_episode_api(
    tmdb_id: str | int, db_index: int, season: int, episode: int
):
    tmdb_id = _require_tmdb_id(tmdb_id)
    try:
        result = await db.delete_tv_episode(tmdb_id, db_index, season, episode)
        if result:
            return {"message": "Episode deleted successfully"}
        else:
            raise HTTPException(status_code=404, detail="Episode not found")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

async def delete_tv_season_api(tmdb_id: str | int, db_index: int, season: int):
    tmdb_id = _require_tmdb_id(tmdb_id)
    try:
        result = await db.delete_tv_season(tmdb_id, db_index, season)
        if result:
            return {"message": "Season deleted successfully"}
        else:
            raise HTTPException(status_code=404, detail="Season not found")
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


#----- Token management
#----- Parse a GB-limit value into a positive float, or None
def _parse_limit(val):
    try:
        v = float(val)
        return v if v > 0 else None
    except (ValueError, TypeError, AttributeError):
        return None


async def create_token_api(payload: dict):
    try:
        token_name = payload.get("name")
        if not token_name:
            raise HTTPException(status_code=400, detail="Token name is required")

        new_token = await db.add_api_token(
            token_name,
            _parse_limit(payload.get("daily_limit_gb")),
            _parse_limit(payload.get("monthly_limit_gb")),
            subscription_exempt=bool(payload.get("subscription_exempt")),
        )
        return new_token
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


#----- Toggle a token's lifetime (subscription-exempt) flag
async def set_token_lifetime_api(token: str, payload: dict) -> dict:
    exempt = bool(payload.get("subscription_exempt"))
    if not await db.set_token_lifetime(token, exempt):
        raise HTTPException(status_code=404, detail="Token not found.")
    return {"status": "success", "subscription_exempt": exempt}


#----- Set/extend/reduce a token's own expiry (subscription-off mode).
#----- Optionally attach a Telegram user id at the same time.
async def set_token_expiry_api(token: str, payload: dict) -> dict:
    user_id = payload.get("user_id")
    if user_id not in (None, "", 0, "0"):
        try:
            uid = int(user_id)
        except (TypeError, ValueError):
            raise HTTPException(status_code=400, detail="Invalid Telegram user id.")
        #----- Enforces one-user-one-token + pulls the real Telegram name
        await link_token_user_api(token, uid)

    action = str(payload.get("action") or "set")
    days = int(payload.get("days") or 0)
    result = await db.update_token_expiry(token, action, days)
    if not result:
        raise HTTPException(status_code=404, detail="Token not found.")
    return {"status": "success", "expires_at": result.get("expires_at").isoformat() if result.get("expires_at") else None}


#----- How many tokens would stop working if subscription mode is enabled
async def subscription_preflight_api() -> dict:
    return {"status": "success", "uncovered": await db.count_uncovered_tokens()}


#----- Relabel "User <id>" placeholder subscribers with their real Telegram name
async def backfill_subscriber_names_api() -> dict:
    users = await db.get_all_subscribers()
    updated = 0
    for u in users:
        uid = u.get("_id")
        if uid is None or (u.get("first_name") or "") != f"User {uid}":
            continue
        name = await _fetch_tg_name(uid)
        if name and name != f"User {uid}":
            await db.update_subscriber_name(uid, name)
            updated += 1
    return {"status": "success", "updated": updated, "message": f"{updated} name(s) updated."}


#----- Mark all tokens that aren't linked to a user as lifetime
async def grant_lifetime_api() -> dict:
    count = await db.grant_lifetime_to_unlinked()
    return {"status": "success", "updated": count, "message": f"{count} token(s) marked as lifetime."}

async def update_token_cf_api(token: str, payload: dict):
    try:
        await own_bots.set_worker(token, payload.get("cf_url"), payload.get("cf_secret"))
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    return {"message": "Cloudflare proxy saved"}

async def update_token_limits_api(token: str, payload: dict):
    try:
        daily_limit = payload.get("daily_limit_gb")
        monthly_limit = payload.get("monthly_limit_gb")

        await db.update_api_token_limits(
            token,
            _parse_limit(daily_limit),
            _parse_limit(monthly_limit)
        )
        return {"message": "Limits updated successfully"}

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


#----- Speed test
#----- Decode a quality_id into (chat_id, msg_id); split files use the first part
async def _resolve_speed_test_target(quality_id: str):
    decoded = await decode_string(quality_id)
    target = decoded["parts"][0] if decoded.get("parts") else decoded
    msg_id = target.get("msg_id")
    raw_cid = target.get("chat_id")
    if not msg_id or not raw_cid:
        return None, None, decoded
    return int(f"-100{raw_cid}"), int(msg_id), decoded


#----- Run a parallel download speed test across all connected clients
async def speed_test_api(
    quality_id: str = Query(..., description="Encoded quality ID from DB"),
    tmdb_id: str | int = Query(...),
    db_index: int = Query(...),
    media_type: str = Query(..., regex="^(movie|tv)$"),
):
    tmdb_id = _require_tmdb_id(tmdb_id)
    try:
        chat_id, msg_id, decoded = await _resolve_speed_test_target(quality_id)
        if not chat_id or not msg_id:
            raise HTTPException(
                status_code=422,
                detail=f"Decoded quality data is missing msg_id or chat_id. Decoded: {decoded}"
            )

        results = await run_speed_test(chat_id, msg_id)
        return {"results": results, "total_clients_tested": len(results)}

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


#----- SSE speed test streaming per-client results as they finish
async def speed_test_stream_api(
    quality_id: str,
    tmdb_id: str | int,
    db_index: int,
    media_type: str,
):

    tmdb_id = _require_tmdb_id(tmdb_id)
    async def event_generator():
        try:
            chat_id, msg_id, decoded = await _resolve_speed_test_target(quality_id)
            if not chat_id or not msg_id:
                payload = json.dumps({"type": "error", "message": f"Cannot decode quality_id. Got: {decoded}"})
                yield f"data: {payload}\n\n"
                return
        except Exception as exc:
            payload = json.dumps({"type": "error", "message": str(exc)})
            yield f"data: {payload}\n\n"
            return

        total = len(multi_clients)
        if total == 0:
            payload = json.dumps({"type": "error", "message": "No bot clients connected"})
            yield f"data: {payload}\n\n"
            return

        #----- Resolve the FileId to report the target DC
        target_dc = "?"
        try:
            primary_client = multi_clients.get(0) or next(iter(multi_clients.values()))
            streamer = ByteStreamer(primary_client)
            file_id = await streamer.get_file_properties(chat_id, int(msg_id))
            target_dc = file_id.dc_id
        except Exception:
            pass

        #----- Initial start event so the frontend can build its table
        yield f"data: {json.dumps({'type': 'start', 'total': total, 'target_dc': target_dc})}\n\n"

        #----- Run all clients in parallel, feeding results into a queue
        queue: asyncio.Queue = asyncio.Queue()

        async def run_one(client, idx):
            async def on_progress(prog_data):
                await queue.put({"type": "progress", "data": prog_data})

            result = await _speed_test_single_client(
                client, idx, chat_id, int(msg_id), progress_callback=on_progress
            )
            await queue.put({"type": "result", "data": result})

        tasks = [
            asyncio.create_task(run_one(client, idx))
            for idx, client in multi_clients.items()
        ]

        completed = 0
        while completed < total:
            msg = await queue.get()

            if msg["type"] == "progress":
                payload = json.dumps(msg)
                yield f"data: {payload}\n\n"

            elif msg["type"] == "result":
                completed += 1
                payload = json.dumps({
                    "type": "result",
                    "data": msg["data"],
                    "completed": completed,
                    "total": total,
                })
                yield f"data: {payload}\n\n"

        await asyncio.gather(*tasks, return_exceptions=True)
        yield f"data: {json.dumps({'type': 'done', 'total': total})}\n\n"

    return StreamingResponse(
        event_generator(),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "X-Accel-Buffering": "no",
        },
    )


#----- Admin stats
async def get_admin_stats_api() -> dict:
    cache_size = sum(len(s._file_id_cache) for s in _streamer_by_client.values())

    bot_stats = []
    for client_index in multi_clients:
        load = work_loads.get(client_index, 0)
        failures = client_failures.get(client_index, 0)
        mbps = client_avg_mbps.get(client_index, 0.0)

        status = "healthy"
        if failures > 5:
            status = "degraded"
        if failures > 15:
            status = "failing"

        bot_stats.append({
            "client_index": client_index,
            "display_name": "Userbot" if client_index < 0 else f"Bot {client_index + 1}",
            "dc": client_dc_map.get(client_index),
            "current_load": load,
            "failures": failures,
            "avg_mbps": round(mbps, 2),
            "status": status
        })

    return {
        "cache_size": cache_size,
        "total_bots": len(multi_clients),
        "bot_workloads": bot_stats
    }


#----- Clear the FileId cache across all active streamers
async def clear_cache_api() -> dict:
    total_cleared = sum(len(s._file_id_cache) for s in _streamer_by_client.values())
    for streamer in _streamer_by_client.values():
        streamer._file_id_cache.clear()
    LOGGER.info(f"Admin cleared the FileId cache ({total_cleared} items purged across {len(_streamer_by_client)} clients).")

    return {"status": "success", "message": f"{total_cleared} cached items cleared."}


#----- List dead links recorded in the DB
async def get_dead_links_api() -> dict:
    try:
        dead_links = await db.get_all_dead_links()
        return {"status": "success", "data": dead_links}
    except Exception as e:
        return {"status": "error", "message": str(e)}


#----- Recent stream analytics
async def get_stream_analytics_api() -> dict:
    try:
        data = await db.get_stream_analytics(limit=200)
        return {"status": "success", "data": data}
    except Exception as e:
        LOGGER.error(f"Stream analytics API error: {e}")
        return {"status": "error", "message": str(e)}


#----- Purge all stream analytics records
async def clear_stream_analytics_api() -> dict:
    try:
        result = await db.dbs["tracking"]["stream_analytics"].delete_many({})
        LOGGER.info(f"Admin cleared stream analytics ({result.deleted_count} records deleted).")

        return {
            "status": "success",
            "message": f"{result.deleted_count} analytics records cleared."
        }
    except Exception as e:
        return {"status": "error", "message": str(e)}


#----- Public: search titles to request (by name, IMDb id or TMDB id)
async def request_search_api(q: str) -> dict:
    try:
        return {"status": "success", "data": await search_titles(q)}
    except Exception as e:
        LOGGER.error(f"Request search error: {e}")
        return {"status": "error", "message": str(e), "data": []}


#----- Public: submit a request for a title
async def request_submit_api(payload: dict, client_ip: str) -> dict:
    result = await submit_request(
        media_type=payload.get("media_type"),
        tmdb_id=payload.get("tmdb_id"),
        imdb_id=payload.get("imdb_id"),
        title=payload.get("title"),
        year=payload.get("year"),
        poster=payload.get("poster"),
        client_ip=client_ip,
    )
    return {"status": "success" if result.get("ok") else "error", **result}


#----- Public: most-requested pending titles
async def request_popular_api() -> dict:
    try:
        return {"status": "success", "data": await popular_pending()}
    except Exception as e:
        return {"status": "error", "message": str(e), "data": []}


#----- Admin: list all content requests
async def get_requests_api() -> dict:
    try:
        return {"status": "success", "data": await list_requests()}
    except Exception as e:
        LOGGER.error(f"Requests API error: {e}")
        return {"status": "error", "message": str(e)}


#----- Admin: uploaded / denied / banned / pending
async def update_request_api(request_id: str, payload: dict) -> dict:
    new_status = str(payload.get("status", "")).strip()
    doc = await set_status(request_id, new_status)
    if not doc:
        raise HTTPException(status_code=404, detail="Request not found or invalid status.")
    return {"status": "success", "data": doc}


async def delete_request_api(request_id: str) -> dict:
    if not await delete_request(request_id):
        raise HTTPException(status_code=404, detail="Request not found.")
    return {"status": "success", "message": "Request deleted."}


#----- Admin subscription management
async def get_subscription_plans_api() -> dict:
    try:
        plans = await db.get_subscription_plans()
        return {"status": "success", "data": plans}
    except Exception as e:
        return {"status": "error", "message": str(e)}

async def add_subscription_plan_api(payload: dict) -> dict:
    try:
        days = int(payload.get("days", 0))
        price = float(payload.get("price", 0.0))
        currency = str(payload.get("currency") or "INR").upper().strip()
        if days <= 0 or price < 0:
            raise HTTPException(status_code=400, detail="Invalid plan parameters")
            
        plan_id = await db.add_subscription_plan(days, price, currency)
        if plan_id:
            return {"status": "success", "message": "Plan added successfully", "plan_id": plan_id}
        else:
            raise HTTPException(status_code=500, detail="Failed to add plan")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

async def update_subscription_plan_api(plan_id: str, payload: dict) -> dict:
    try:
        days = int(payload.get("days", 0))
        price = float(payload.get("price", 0.0))
        currency = str(payload.get("currency") or "INR").upper().strip()
        if days <= 0 or price < 0:
             raise HTTPException(status_code=400, detail="Invalid plan parameters")
             
        success = await db.update_subscription_plan(plan_id, days, price, currency)
        if success:
             return {"status": "success", "message": "Plan updated successfully"}
        else:
             raise HTTPException(status_code=404, detail="Plan not found or update failed")
    except HTTPException:
         raise
    except Exception as e:
         raise HTTPException(status_code=500, detail=str(e))

async def delete_subscription_plan_api(plan_id: str) -> dict:
    try:
        success = await db.delete_subscription_plan(plan_id)
        if success:
            return {"status": "success", "message": "Plan deleted successfully"}
        else:
            raise HTTPException(status_code=404, detail="Plan not found")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

async def get_all_subscribers_api() -> dict:
    try:
        users = await db.get_all_subscribers()
        for u in users:
            u["is_admin"] = db._is_owner(u.get("_id"))
        return {"status": "success", "data": users}
    except Exception as e:
        return {"status": "error", "message": str(e)}

async def manage_subscriber_api(user_id: int, payload: dict) -> dict:
    try:
        action = payload.get("action")
        days = int(payload.get("days", 0))

        if action not in ["extend", "reduce", "delete", "remove"]:
            raise HTTPException(status_code=400, detail="Invalid action")

        success = await db.manage_subscriber(user_id, action, days)

        #----- On revoke/remove, kick the user from the group immediately (ban+unban)
        if success and action in ("delete", "remove") and SettingsManager.current().subscription:
            group_id = SettingsManager.current().subscription_group_id
            if group_id:
                try:
                    await StreamBot.ban_chat_member(group_id, user_id)
                    await StreamBot.unban_chat_member(group_id, user_id)
                except Exception as exc:
                    LOGGER.warning(f"Revoke: could not remove user {user_id} from group: {exc}")

        #----- Reflect the change immediately in the stremio membership cache
        if success:
            try:
                invalidate_membership_cache(user_id)
            except Exception:
                pass

        if success:
            verb = {"extend": "extended", "reduce": "reduced", "delete": "revoked", "remove": "removed"}.get(action, "updated")
            return {"status": "success", "message": f"User subscription {verb} successfully"}
        else:
            raise HTTPException(status_code=404, detail="User not found or update failed")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


#----- Access management
async def get_all_tokens_api() -> dict:
    try:
        tokens = await db.get_all_api_tokens()
        now = datetime.utcnow()
        result = []

        #----- Pre-load subscribers keyed by user_id for O(1) lookup
        subscriber_map = {}
        if SettingsManager.current().subscription:
            try:
                for u in await db.get_all_subscribers():
                    uid = str(u.get("_id"))
                    subscriber_map[uid] = u
            except Exception:
                pass

        #----- Display name, preferring a real name/alias over the "User <id>" placeholder
        def display_name(user, user_id, token_name=None):
            placeholder = f"User {user_id}" if user_id is not None else None
            options = [token_name]
            if user:
                options += [user.get("first_name"), user.get("username")]
            for o in options:
                if o and o != placeholder:
                    return o
            for o in options:
                if o:
                    return o
            return placeholder or "Telegram User"

        sub_on = SettingsManager.current().subscription

        #----- Unified access entry from optional user + token records
        def build_entry(user_id, user, token_doc):
            token_doc = token_doc or {}
            user_found = bool(user)
            sub_status = user.get("subscription_status") if user else None
            is_admin = bool(token_doc.get("is_admin")) or db._is_owner(user_id)
            lifetime = bool(token_doc.get("subscription_exempt"))
            token_str = token_doc.get("token")

            token_expiry = token_doc.get("expires_at")
            user_sub_expiry = user.get("subscription_expiry") if user else None

            #----- Sub OFF: token's own expiry (display only). Sub ON: token expiry is an
            #----- admin grant, otherwise fall back to the subscription's expiry.
            if not sub_on:
                expiry = token_expiry
                is_expired = False
            elif is_admin or lifetime:
                expiry = None
                is_expired = False
            elif token_expiry is not None:
                expiry = token_expiry
                is_expired = token_expiry < now
            elif user_found and sub_status == "active" and user_sub_expiry:
                expiry = user_sub_expiry
                is_expired = user_sub_expiry < now
            else:
                expiry = user_sub_expiry
                is_expired = True

            created = token_doc.get("created_at") or (user.get("created_at") if user else None)
            limits = token_doc.get("limits") or {}
            usage = token_doc.get("usage") or {}
            has_active_sub = sub_on and user_found and sub_status == "active" and bool(user_sub_expiry) and user_sub_expiry > now
            never_expires = not expiry and (is_admin or lifetime or not sub_on)

            return {
                "token": token_str,
                "user_id": user_id,
                "user_name": display_name(user, user_id, token_doc.get("name")),
                "user_found": user_found,
                "is_admin": is_admin,
                "lifetime": lifetime,
                "never_expires": never_expires,
                "has_token": bool(token_str),
                "has_active_sub": has_active_sub,
                "created_at": created.isoformat() if created else None,
                "expires_at": expiry.isoformat() if expiry else None,
                "is_expired": is_expired,
                "sub_status": sub_status,
                "daily_limit_gb": limits.get("daily_limit_gb") or 0,
                "monthly_limit_gb": limits.get("monthly_limit_gb") or 0,
                "daily_bytes": (usage.get("daily") or {}).get("bytes", 0),
                "monthly_bytes": (usage.get("monthly") or {}).get("bytes", 0),
                "addon_url": (
                    f"{SettingsManager.current().base_url}/stremio/{token_str}/manifest.json"
                    if token_str else None
                ),
                "own_bots": own_bots.public(token_doc["own_bots"]) if token_doc.get("own_bots") else None,
                "cf_url": (token_doc.get("cf") or {}).get("url", ""),
                "cf_secret": (token_doc.get("cf") or {}).get("secret", ""),
            }

        seen_user_ids = set()

        #----- 1. Process all existing tokens
        for t in tokens:
            token_user_id = t.get("user_id")

            user = None
            if token_user_id:
                uid_str = str(token_user_id)
                user = subscriber_map.get(uid_str)
                if not user:
                    try:
                        user = await db.get_user(int(token_user_id))
                    except Exception:
                        pass
                seen_user_ids.add(uid_str)

            result.append(build_entry(token_user_id, user, t))

        #----- 2. Add subscribers who have no token
        for uid_str, u in subscriber_map.items():
            if uid_str in seen_user_ids:
                continue
            result.append(build_entry(u.get("_id"), u, None))

        #----- Sort: active-with-token first, active-no-token next, expired last
        result.sort(key=lambda x: (x["is_expired"], not x["has_token"]))
        return {"tokens": result, "subscription": sub_on}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


async def revoke_token_api(token: str) -> dict:
    try:
        success = await db.revoke_api_token(token)
        if success:
            return {"status": "success", "message": "Token revoked."}
        raise HTTPException(status_code=404, detail="Token not found.")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


#----- Assign or extend a subscription for any user_id
async def assign_plan_api(user_id: int, days: int) -> dict:
    try:
        #----- Use the real Telegram name so the Plans page shows it (not "User <id>")
        name = await _fetch_tg_name(user_id)
        #----- 0 / empty days means "never expires"
        if days and days > 0:
            result = await db.assign_subscription(user_id, days, name)
        else:
            result = await db.set_user_never_expires(user_id, name)
        return {"status": "success", "data": result}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


#----- Look up a Telegram user's display name via the bot (best-effort)
async def _fetch_tg_name(user_id: int):
    try:
        u = await StreamBot.get_users(user_id)
        if not u:
            return None
        name = (u.first_name or "").strip()
        if getattr(u, "last_name", None):
            name = f"{name} {u.last_name}".strip()
        return name or (u.username or None)
    except Exception:
        return None


#----- Link an orphan token to a Telegram user_id (one user_id = one token)
async def link_token_user_api(token: str, user_id: int) -> dict:
    try:
        existing = await db.get_api_token_by_user(user_id)
        if existing and existing.get("token") == token:
            return {"status": "success", "message": f"Already linked to user {user_id}."}
        if existing:
            raise HTTPException(
                status_code=409,
                detail=f"User {user_id} is already linked to token '{existing.get('name')}'. Unlink or delete that token first.",
            )
        #----- Overwrite the token name with the user's real Telegram name when available
        name = await _fetch_tg_name(user_id)
        success = await db.link_token_user(token, user_id, name)
        if success:
            return {"status": "success", "message": f"Token linked to {name or user_id}."}
        raise HTTPException(status_code=404, detail="Token not found.")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


#----- Rescan: search TMDB candidates for a title
async def search_media_rescan_api(media_type: str, query: str, year: int | None = None):
    query = (query or "").strip()
    if not query:
        raise HTTPException(status_code=400, detail="query is required.")

    if media_type == "movie":
        results = await search_movie_candidates(query=query, year=year)
    elif media_type == "tv":
        results = await search_tv_candidates(query=query)
    else:
        raise HTTPException(status_code=400, detail="Invalid media_type.")

    return {"results": results}


async def tag_media_api(tmdb_id: str | int, db_index: int, media_type: str):
    doc = await db.get_document(media_type, _require_tmdb_id(tmdb_id), db_index)
    if not doc:
        raise HTTPException(status_code=404, detail="Media not found.")
    if not build_id_link(doc.get("imdb_id"), doc.get("tmdb_id"), media_type):
        raise HTTPException(status_code=400, detail="This title has no IMDb or TMDB id to tag with.")
    asyncio.create_task(retag_media(_scan_client(), media_type, doc))
    return {"status": "success", "message": "Tagging files in the background."}


async def apply_media_rescan_api(request: Request, tmdb_id: str | int, db_index: int, media_type: str):
    tmdb_id = _require_tmdb_id(tmdb_id)
    body = await request.json()
    selected_id = str(body.get("selected_id") or "").strip()

    if not selected_id:
        raise HTTPException(status_code=400, detail="selected_id is required.")

    current_doc = await db.get_document(media_type, tmdb_id, db_index)
    if not current_doc:
        raise HTTPException(status_code=404, detail="Media not found.")

    if media_type == "movie":
        metadata = await fetch_selected_movie_metadata(selected_id)
    elif media_type == "tv":
        metadata = await fetch_selected_tv_metadata(selected_id)
    else:
        raise HTTPException(status_code=400, detail="Invalid media_type.")

    if not metadata:
        raise HTTPException(status_code=404, detail="Unable to fetch metadata for selected item.")

    updated_doc = await db.replace_media_metadata(
        media_type=media_type,
        tmdb_id=tmdb_id,
        db_index=db_index,
        metadata=metadata,
    )

    if not updated_doc:
        raise HTTPException(status_code=500, detail="Failed to replace media metadata.")
    asyncio.create_task(retag_media(_scan_client(), media_type, updated_doc))

    return {
        "success": True,
        "message": "Metadata rescanned successfully.",
        "redirect_tmdb_id": updated_doc.get("tmdb_id"),
        "db_index": updated_doc.get("db_index", db_index),
        "media_type": media_type,
        "data": updated_doc,
}


#----- Manual add: fetch full metadata for a selected TMDB/IMDB title to autofill the form
async def resolve_manual_metadata_api(media_type: str, selected_id: str) -> dict:
    selected_id = str(selected_id or "").strip()
    if not selected_id:
        raise HTTPException(status_code=400, detail="selected_id is required.")
    mt = _normalize_media_type(media_type)
    data = await (
        fetch_selected_movie_metadata(selected_id) if mt == "movie"
        else fetch_selected_tv_metadata(selected_id)
    )
    if not data:
        raise HTTPException(status_code=404, detail="Could not fetch metadata for the selected title.")
    if data.get("poster"):
        data["poster"] = resolve_cover_url(data["poster"])
    if data.get("backdrop"):
        data["backdrop"] = resolve_cover_url(data["backdrop"])
    return {"metadata": data}


#----- Manual add: resolve a Telegram post link into a streamable file
async def resolve_telegram_api(payload: dict) -> dict:
    client = _scan_client()
    if client is None:
        raise HTTPException(status_code=503, detail="No Telegram client is connected yet.")
    try:
        data = await resolve_telegram_message(
            client,
            url=payload.get("url"),
            chat_id=payload.get("chat_id"),
            msg_id=payload.get("msg_id"),
        )
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc))
    except Exception as exc:
        raise HTTPException(status_code=500, detail=f"Could not read that message: {exc}")
    return {"status": "success", "data": data}


async def resolve_subtitle_api(payload: dict) -> dict:
    client = _scan_client()
    if client is None:
        raise HTTPException(status_code=503, detail="No Telegram client is connected yet.")
    try:
        data = await resolve_subtitle_message(
            client, url=payload.get("url"),
            chat_id=payload.get("chat_id"), msg_id=payload.get("msg_id"),
        )
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc))
    except Exception as exc:
        raise HTTPException(status_code=500, detail=f"Could not read that message: {exc}")
    return {"status": "success", "data": data}


async def _resolve_imdb_id(media_type: str, tmdb_id, db_index) -> str:
    tmdb_id = _coerce_tmdb_id(tmdb_id)
    if not (tmdb_id and db_index):
        raise HTTPException(status_code=400, detail="tmdb_id and db_index are required.")
    doc = await db.get_document(media_type, int(tmdb_id), int(db_index))
    if not doc or not doc.get("imdb_id"):
        raise HTTPException(status_code=404, detail="Title not found.")
    return doc["imdb_id"]


def list_subtitle_languages_api() -> dict:
    return {"status": "success", "languages": list_languages()}


async def list_subtitles_api(media_type: str, tmdb_id, db_index) -> dict:
    tmdb_id = _require_tmdb_id(tmdb_id)
    mt = "tv" if media_type in ("tv", "series") else "movie"
    imdb_id = await _resolve_imdb_id(mt, tmdb_id, db_index)
    return {"status": "success", "subtitles": await list_title_subtitles(imdb_id)}


async def add_subtitles_api(payload: dict) -> dict:
    media_type = "tv" if payload.get("media_type") in ("tv", "series") else "movie"
    imdb_id = await _resolve_imdb_id(media_type, payload.get("tmdb_id"), payload.get("db_index"))
    items = payload.get("items") or []
    if not isinstance(items, list) or not items:
        raise HTTPException(status_code=400, detail="Provide at least one subtitle to add.")

    client = _scan_client()
    if client is None:
        raise HTTPException(status_code=503, detail="No Telegram client is connected yet.")

    added, errors = [], []
    for item in items:
        try:
            season = item.get("season") if media_type == "tv" else None
            episode = item.get("episode") if media_type == "tv" else None
            if media_type == "tv" and (not season or not episode):
                raise ValueError("Season and episode are required for series subtitles.")
            resolved = await resolve_subtitle_message(
                client, url=item.get("url"),
                chat_id=item.get("chat_id"), msg_id=item.get("msg_id"),
            )
            doc = await manual_ingest_subtitle(
                imdb_id, media_type, season, episode,
                item.get("lang_code") or resolved["lang_code"],
                resolved["chat_id"], resolved["msg_id"], resolved["name"],
            )
            added.append({
                "name": doc["name"], "lang_label": doc["lang_label"],
                "season": doc["season"], "episode": doc["episode"],
            })
        except ValueError as exc:
            errors.append(str(exc))
        except Exception as exc:
            errors.append(f"Could not add subtitle: {exc}")

    if not added and errors:
        raise HTTPException(status_code=400, detail=" ".join(errors))
    message = f"Added {len(added)} subtitle(s)."
    if errors:
        message += f" {len(errors)} failed: {' '.join(errors)}"
    return {"status": "success", "message": message, "added": added, "errors": errors}


async def remove_subtitle_api(payload: dict) -> dict:
    chat_id = payload.get("chat_id")
    msg_id = payload.get("msg_id")
    if chat_id in (None, "") or msg_id in (None, ""):
        raise HTTPException(status_code=400, detail="chat_id and msg_id are required.")
    if not await remove_subtitle(chat_id, msg_id):
        raise HTTPException(status_code=404, detail="Subtitle not found.")
    return {"status": "success", "message": "Subtitle removed."}


#----- Build a metadata base (title-level fields) from various sources
def _metadata_base(source: dict, from_doc: bool = False) -> dict:
    genres = source.get("genres")
    if isinstance(genres, str):
        genres = [g.strip() for g in genres.split(",") if g.strip()]
    year = source.get("release_year") if from_doc else source.get("year")
    rate = source.get("rating") if from_doc else source.get("rate")
    return {
        "tmdb_id": source.get("tmdb_id"),
        "imdb_id": source.get("imdb_id") or None,
        "title": (source.get("title") or "").strip(),
        "year": int(year) if str(year or "").strip().lstrip("-").isdigit() else 0,
        "rate": float(rate) if str(rate or "").replace(".", "", 1).isdigit() else 0,
        "description": source.get("description") or "",
        "poster": source.get("poster") or "",
        "backdrop": source.get("backdrop") or "",
        "logo": source.get("logo") or "",
        "genres": genres or [],
        "cast": source.get("cast") or [],
        "runtime": str(source.get("runtime") or ""),
        "original_language": source.get("original_language"),
        "origin_country": source.get("origin_country") or [],
    }


_PLACEHOLDER_GENRES = ["Action", "Adventure", "Comedy", "Drama", "Fantasy",
                       "Thriller", "Mystery", "Sci-Fi", "Romance", "Family"]
_PLACEHOLDER_DESCRIPTIONS = [
    "A gripping story full of unexpected twists and turns.",
    "An unforgettable journey that keeps you on the edge of your seat.",
    "A captivating tale of drama, courage and emotion.",
    "An entertaining experience packed with memorable moments.",
    "A thrilling adventure blending heart, action and wonder.",
]


#----- Fill empty optional metadata with random values and a gradient cover path
def _fill_placeholder_metadata(meta: dict) -> None:
    title = meta.get("title") or "Media"
    if not meta.get("poster"):
        meta["poster"] = gradient_cover_path(title, portrait=True)
    if not meta.get("backdrop"):
        meta["backdrop"] = gradient_cover_path(title)
    if not meta.get("genres"):
        meta["genres"] = random.sample(_PLACEHOLDER_GENRES, random.randint(1, 3))
    if not meta.get("rate"):
        meta["rate"] = round(random.uniform(6.0, 8.9), 1)
    if not meta.get("description"):
        meta["description"] = random.choice(_PLACEHOLDER_DESCRIPTIONS)


#----- Manual add: create/append a movie, tv show, season, episode or stream by hand
async def manual_add_media_api(payload: dict) -> dict:
    media_type = payload.get("media_type")
    if media_type not in ("movie", "tv"):
        raise HTTPException(status_code=400, detail="media_type must be 'movie' or 'tv'.")

    stream = payload.get("stream") or {}
    quality = str(stream.get("quality") or "").strip()
    if not quality:
        raise HTTPException(status_code=400, detail="A quality label (e.g. 1080p) is required.")

    #----- One source = single file, multiple sources = split file parts (in order)
    part_sources = stream.get("parts")
    if not isinstance(part_sources, list) or not part_sources:
        part_sources = [{"url": stream.get("url"), "chat_id": stream.get("chat_id"), "msg_id": stream.get("msg_id")}]
    part_sources = [p for p in part_sources if p and (p.get("url") or (p.get("chat_id") and p.get("msg_id")))]
    if not part_sources:
        raise HTTPException(status_code=400, detail="Provide at least one Telegram message link.")

    client = _scan_client()
    if client is None:
        raise HTTPException(status_code=503, detail="No Telegram client is connected yet.")

    resolved_parts = []
    for src in part_sources:
        try:
            resolved_parts.append(await resolve_telegram_message(
                client, url=src.get("url"), chat_id=src.get("chat_id"), msg_id=src.get("msg_id"),
            ))
        except ValueError as exc:
            raise HTTPException(status_code=400, detail=str(exc))
        except Exception as exc:
            raise HTTPException(status_code=500, detail=f"Could not read that message: {exc}")

    primary = resolved_parts[0]
    is_split = len(resolved_parts) > 1
    raw_name = (stream.get("name") or primary["name"]).strip()
    name = strip_part_suffix(raw_name) if is_split else raw_name

    #----- Resolve the title-level metadata: existing doc, TMDB/IMDb pick, or manual entry
    tmdb_id = payload.get("tmdb_id")
    db_index = payload.get("db_index")
    selected_id = str(payload.get("selected_id") or "").strip()

    base = None
    if tmdb_id and db_index:
        doc = await db.get_document(media_type, int(tmdb_id), int(db_index))
        if doc:
            base = _metadata_base(doc, from_doc=True)
    if base is None and selected_id:
        selection = await (
            fetch_selected_movie_metadata(selected_id) if media_type == "movie"
            else fetch_selected_tv_metadata(selected_id)
        )
        if not selection:
            raise HTTPException(status_code=404, detail="Could not fetch metadata for the selected title.")
        base = _metadata_base(selection, from_doc=True)
    if base is None:
        base = _metadata_base(payload.get("manual_metadata") or {})
        if not base["title"]:
            raise HTTPException(status_code=400, detail="A title is required for manual entry.")
        if not base["year"]:
            base["year"] = int(primary.get("upload_year") or 0)

    #----- Brand-new hand-made titles get a negative synthetic id (never collides with TMDB)
    if not base.get("tmdb_id"):
        base["tmdb_id"] = -(secrets.randbelow(2_000_000_000) + 1)
    #----- A synthetic "tg" imdb id is required so Stremio can request meta/streams
    if not base.get("imdb_id"):
        base["imdb_id"] = f"tg{abs(int(base['tmdb_id']))}"
    _fill_placeholder_metadata(base)

    thumb_url = ""
    if primary.get("has_thumb"):
        thumb_enc = await encode_string({"chat_id": int(primary["chat_id"]), "msg_id": int(primary["msg_id"])})
        try:
            chat_ref = int(f"-100{str(primary['chat_id']).replace('-100', '')}")
            msg = await client.get_messages(chat_ref, int(primary["msg_id"]))
            thumb_url = await resolve_video_thumb_url(client, msg, thumb_enc)
        except Exception:
            thumb_url = f"/thumb/{thumb_enc}"

    #----- Split parts share one quality entry via a common group key
    group_key = f"manual:{primary['chat_id']}:{quality}:{secrets.token_hex(6)}" if is_split else None

    tv_extra = {}
    if media_type == "tv":
        try:
            season_number = int(payload.get("season_number"))
            episode_number = int(payload.get("episode_number"))
        except (TypeError, ValueError):
            raise HTTPException(status_code=400, detail="Season and episode numbers are required for TV.")
        tv_extra = {
            "season_number": season_number,
            "episode_number": episode_number,
            "episode_title": (payload.get("episode_title") or "").strip() or f"S{season_number:02d}E{episode_number:02d}",
            "episode_backdrop": payload.get("episode_backdrop") or thumb_url or base.get("backdrop") or "",
            "episode_overview": payload.get("episode_overview") or "",
            "episode_released": payload.get("episode_released") or "",
        }
    elif thumb_url and not base.get("backdrop"):
        base["backdrop"] = thumb_url

    for index, part in enumerate(resolved_parts, start=1):
        p_channel = int(part["chat_id"])
        p_msg = int(part["msg_id"])
        encoded = await encode_string({"chat_id": p_channel, "msg_id": p_msg})
        metadata_info = dict(base)
        metadata_info.update({
            "media_type": media_type,
            "quality": quality,
            "encoded_string": encoded,
            "group_key": group_key,
            "part_number": index if is_split else None,
            "is_anime": False,
        })
        metadata_info.update(tv_extra)
        updated_id = await db.insert_media(
            metadata_info, channel=p_channel, msg_id=p_msg,
            size=part["size"], name=name, raw_size=int(part.get("raw_size") or 0),
        )
        if not updated_id:
            raise HTTPException(status_code=500, detail="Failed to add media (validation error).")
        await stamp_caption_by_ref(client, p_channel, p_msg, metadata_info)

    result_tmdb_id = base["tmdb_id"]
    location = await db.find_media_doc(media_type, result_tmdb_id)
    result_db_index = location[1] if location else db.current_db_index

    #----- Assign to selected custom catalogs before triggering auto sync, so any
    #----- exclusivity is stamped on the doc first and auto sync correctly skips it.
    #----- Guarded on `location` so we never add a reference to a non-existent doc.
    catalog_ids = payload.get("catalog_ids") or []
    catalogs_added = []
    if location:
        for cat_id in catalog_ids:
            try:
                cat_id = str(cat_id).strip()
                if not cat_id:
                    continue
                added = await db.add_item_to_custom_catalog(cat_id, int(result_tmdb_id), int(result_db_index), media_type)
                if added:
                    catalog = await db.get_custom_catalog(cat_id)
                    if catalog:
                        catalogs_added.append(catalog.get("name", cat_id))
                        cat_vis = catalog.get("visibility")
                        if cat_vis in ("owner", "tokens"):
                            await db.set_media_visibility(
                                int(result_tmdb_id), int(result_db_index), media_type,
                                cat_vis, catalog.get("allowed_tokens") or []
                            )
                        if catalog.get("exclusive"):
                            await db.mark_item_exclusive(
                                cat_id, int(result_tmdb_id), int(result_db_index),
                                media_type, catalog.get("searchable", False)
                            )
            except Exception:
                pass

    if result_tmdb_id and result_tmdb_id > 0:
        try:
            start_single_media_catalog_sync(db, tmdb_id=result_tmdb_id, media_type=media_type)
        except Exception:
            pass

    message = f"Split stream added ({len(resolved_parts)} parts)." if is_split else "Stream added successfully."
    if catalogs_added:
        message += f" Added to: {', '.join(catalogs_added)}."
    return {
        "status": "success",
        "message": message,
        "tmdb_id": result_tmdb_id,
        "db_index": result_db_index,
        "media_type": media_type,
    }


#----- Custom catalog APIs
def _normalize_media_type(media_type: str) -> str:
    return "tv" if media_type in ["tv", "series"] else "movie"


async def list_custom_catalogs_api(
    tmdb_id: str | int | None = None,
    db_index: int | None = None,
    media_type: str | None = None,
):
    try:
        check_current = tmdb_id is not None and db_index is not None and bool(media_type)
        catalogs = await db.get_custom_catalogs(item_fields=("tmdb_id", "db_index", "media_type") if check_current else ())
        if check_current:
            normalized_type = _normalize_media_type(media_type)
            for catalog in catalogs:
                catalog["contains_current"] = any(
                    int(item.get("tmdb_id", -1)) == int(tmdb_id)
                    and int(item.get("db_index", -1)) == int(db_index)
                    and item.get("media_type") == normalized_type
                    for item in catalog.get("items", []) or []
                )
        for catalog in catalogs:
            catalog.pop("items", None)
        return {"catalogs": catalogs}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


async def list_manual_add_catalogs_api():
    try:
        catalogs = await db.get_custom_catalogs(slim=True)
        filtered = [c for c in catalogs if not c.get("auto")]
        filtered.sort(key=lambda c: (0 if c.get("exclusive") else 1, (c.get("name") or "").lower()))
        return {"catalogs": [
            {"_id": c["_id"], "name": c["name"], "exclusive": bool(c.get("exclusive")),
             "visibility": c.get("visibility", "public")}
            for c in filtered
        ]}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


_VISIBILITY_MODES = ("public", "tokens", "owner")


#----- Parse a (visibility, allowed_tokens) pair from a request payload
def _clean_visibility(payload: dict):
    visibility = payload.get("visibility")
    if visibility not in _VISIBILITY_MODES:
        visibility = None
    tokens = payload.get("allowed_tokens")
    tokens = [str(t).strip() for t in tokens if str(t).strip()] if isinstance(tokens, list) else []
    return visibility, tokens


async def create_custom_catalog_api(payload: dict):
    name = (payload.get("name") or "").strip()
    if not name:
        raise HTTPException(status_code=400, detail="Catalog name is required.")

    visibility, tokens = _clean_visibility(payload)
    catalog_id = await db.create_custom_catalog(name=name, visibility=visibility or "public", allowed_tokens=tokens)
    if not catalog_id:
        raise HTTPException(status_code=500, detail="Failed to create catalog.")

    catalog = await db.get_custom_catalog(catalog_id)
    return {"message": "Catalog created successfully.", "catalog": catalog}


async def update_custom_catalog_api(catalog_id: str, payload: dict):
    name = payload.get("name")
    visibility, tokens = _clean_visibility(payload)
    exclusive = payload.get("exclusive")
    exclusive = bool(exclusive) if exclusive is not None else None
    searchable = bool(payload.get("searchable"))
    result = await db.update_custom_catalog(
        catalog_id, name=name, visibility=visibility, allowed_tokens=tokens,
        exclusive=exclusive, searchable=searchable,
    )
    if not result:
        catalog = await db.get_custom_catalog(catalog_id)
        if not catalog:
            raise HTTPException(status_code=404, detail="Catalog not found.")
    return {"message": "Catalog updated successfully.", "catalog": await db.get_custom_catalog(catalog_id)}


#----- Set a title's visibility across every catalog it belongs to (used by media edit)
async def set_media_visibility_api(payload: dict):
    tmdb_id = payload.get("tmdb_id")
    db_index = payload.get("db_index")
    media_type = payload.get("media_type")
    if not tmdb_id or not db_index or media_type not in ("movie", "tv", "series"):
        raise HTTPException(status_code=400, detail="tmdb_id, db_index and media_type are required.")

    visibility, tokens = _clean_visibility(payload)
    if not visibility:
        raise HTTPException(status_code=400, detail="A valid visibility is required.")

    count = await db.set_media_visibility(
        int(tmdb_id), int(db_index), _normalize_media_type(media_type), visibility, tokens
    )
    return {
        "status": "success",
        "updated_catalogs": count,
        "message": "Visibility updated — applies to default catalogs and every catalog this title is in.",
    }


#----- Current effective visibility of a title (from the catalogs it belongs to)
async def get_media_visibility_api(tmdb_id: str | int, db_index: int, media_type: str):
    tmdb_id = _require_tmdb_id(tmdb_id)
    data = await db.get_media_visibility(int(tmdb_id), int(db_index), _normalize_media_type(media_type))
    return {"visibility": data or {}}


async def delete_custom_catalog_api(catalog_id: str):
    result = await db.delete_custom_catalog(catalog_id)
    if not result:
        raise HTTPException(status_code=404, detail="Catalog not found.")
    return {"message": "Catalog deleted successfully."}


async def get_custom_catalog_items_api(
    catalog_id: str,
    media_type: str | None = None,
    page: int = 1,
    page_size: int = 24,
):
    try:
        data = await db.get_custom_catalog_items(catalog_id, media_type, page, page_size)
        if not data.get("catalog"):
            raise HTTPException(status_code=404, detail="Catalog not found.")
        _resolve_covers(data.get("items"))
        return data
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


async def search_catalog_media_api(
    query: str,
    media_type: str = "movie",
    page: int = 1,
    page_size: int = 12,
):
    query = (query or "").strip()
    if not query:
        return {"results": [], "total_count": 0}

    try:
        normalized_type = _normalize_media_type(media_type)
        result = await db.search_documents(query, page, page_size, media_type=normalized_type)
        filtered = [item for item in result.get("results", []) if item.get("media_type") == normalized_type]
        return {"results": filtered, "total_count": len(filtered)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


async def add_custom_catalog_item_api(catalog_id: str, payload: dict):
    tmdb_id = payload.get("tmdb_id")
    db_index = payload.get("db_index")
    media_type = _normalize_media_type(payload.get("media_type", "movie"))

    if not tmdb_id or not db_index:
        raise HTTPException(status_code=400, detail="tmdb_id and db_index are required.")

    media = await db.get_document(media_type, int(tmdb_id), int(db_index))
    if not media:
        raise HTTPException(status_code=404, detail="Media not found.")

    catalog = await db.get_custom_catalog(catalog_id)
    if not catalog:
        raise HTTPException(status_code=404, detail="Catalog not found.")

    added = await db.add_item_to_custom_catalog(catalog_id, int(tmdb_id), int(db_index), media_type)
    visibility_synced = None
    if added:
        #----- Adding to a hidden/restricted catalog adopts that visibility onto the title
        cat_vis = catalog.get("visibility")
        if cat_vis in ("owner", "tokens"):
            await db.set_media_visibility(
                int(tmdb_id), int(db_index), media_type, cat_vis, catalog.get("allowed_tokens") or []
            )
            visibility_synced = cat_vis
        if catalog.get("exclusive"):
            await db.mark_item_exclusive(catalog_id, int(tmdb_id), int(db_index), media_type, catalog.get("searchable", False))
    message = "Added to catalog." if added else "Already exists in this catalog."
    return {"message": message, "added": added, "visibility_synced": visibility_synced}


async def remove_custom_catalog_item_api(
    catalog_id: str,
    tmdb_id: str | int,
    db_index: int,
    media_type: str,
):
    tmdb_id = _require_tmdb_id(tmdb_id)
    catalog = await db.get_custom_catalog(catalog_id)
    if not catalog:
        raise HTTPException(status_code=404, detail="Catalog not found.")

    removed = await db.remove_item_from_custom_catalog(
        catalog_id, int(tmdb_id), int(db_index), _normalize_media_type(media_type)
    )
    if not removed:
        return {"message": "Item was not in this catalog.", "removed": False}
    if catalog.get("exclusive"):
        await db.clear_item_exclusive(int(tmdb_id), int(db_index), _normalize_media_type(media_type))
    return {"message": "Removed from catalog.", "removed": True}


async def auto_sync_custom_catalogs_api(force_refresh: bool = False):
    try:
        result = await start_auto_catalog_sync_background(db, force=True, force_refresh=force_refresh)
        return {"message": result.get("message", "Auto sync started."), "result": result}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


async def auto_catalog_sync_status_api():
    try:
        return {"status": await get_auto_catalog_sync_status(db)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


async def get_auto_catalog_settings_api():
    try:
        return {"settings": await get_auto_catalog_settings(db)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


async def update_auto_catalog_settings_api(payload: dict):
    try:
        enabled_keys = payload.get("enabled_keys", [])
        if not isinstance(enabled_keys, list):
            raise HTTPException(status_code=400, detail="enabled_keys must be a list.")
        settings = await update_auto_catalog_settings(db, enabled_keys)
        return {"message": "Auto catalog settings saved.", "settings": settings}
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


_DEFAULT_CATALOG_ENTRIES = [
    {"id": "latest_movies", "name": "Recently Added Movies", "group": "Default Movies", "type": "movie"},
    {"id": "top_movies", "name": "Popular Movies", "group": "Default Movies", "type": "movie"},
    {"id": "latest_series", "name": "Recently Added Series", "group": "Default TV", "type": "series"},
    {"id": "top_series", "name": "Popular Series", "group": "Default TV", "type": "series"},
    {"id": "trending_movies", "name": "Trending Movies", "group": "Default Movies", "type": "movie"},
    {"id": "trending_series", "name": "Trending Series", "group": "Default TV", "type": "series"},
]


async def get_catalog_order_api():
    try:
        catalogs = await db.get_custom_catalogs(slim=True)
        entries = [dict(e) for e in _DEFAULT_CATALOG_ENTRIES]
        for c in catalogs:
            items = c.get("items") or []
            cid = f"custom_{c['_id']}"
            name = c.get("name") or "Catalog"
            group = "Auto" if c.get("auto") else "Custom"
            has_movie = any(i.get("media_type") == "movie" for i in items)
            has_series = any(i.get("media_type") == "tv" for i in items)
            if has_movie or not items:
                entries.append({"id": cid, "name": name, "group": group, "type": "movie"})
            if has_series:
                entries.append({"id": cid, "name": name, "group": group, "type": "series"})
        for e in entries:
            e["key"] = f"{e['id']}::{e['type']}"
        order = await db.get_catalog_order()
        rank = {k: i for i, k in enumerate(order)}
        entries.sort(key=lambda e: rank.get(e["key"], rank.get(e["id"], len(order) + 1)))
        hidden = set(await db.get_hidden_catalogs())
        for e in entries:
            e["hidden"] = e["key"] in hidden
        return {"entries": entries, "order": order}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


async def update_catalog_order_api(payload: dict):
    order = payload.get("order")
    if not isinstance(order, list):
        raise HTTPException(status_code=400, detail="order must be a list.")
    await db.save_catalog_order(order)
    if isinstance(payload.get("hidden"), list):
        await db.save_hidden_catalogs(payload["hidden"])
    return {"ok": True, "message": "Catalog order saved."}


async def get_user_activity_api(page: int = 1, per_page: int = 5):
    try:
        return await get_activity_overview(page, per_page)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


async def session_send_code_api(payload: dict):
    try:
        return await start_login(payload.get("phone"))
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


async def session_verify_code_api(payload: dict):
    try:
        return await submit_code(payload.get("login_id"), payload.get("code"))
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


async def session_verify_password_api(payload: dict):
    try:
        return await submit_password(payload.get("login_id"), payload.get("password"))
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


async def session_status_api():
    return await get_session_status()


async def session_disconnect_api():
    return await disconnect_session()


async def session_reconnect_api():
    try:
        return await reconnect_session()
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))


async def session_remove_api():
    return await remove_session()




# ─────────────────────────────────────────────────────────────────────────────
# Settings API
# ─────────────────────────────────────────────────────────────────────────────

async def get_settings_api() -> dict:

    data = SettingsManager.current().to_dict()
    data["admin_password_set"] = bool(data.get("admin_password"))
    data["admin_password"] = ""
    data["session_secret_set"] = bool(data.get("session_secret"))
    data["session_secret"] = ""

    try:
        data["database_list"] = db.get_database_list()
    except Exception as e:
        LOGGER.error(f"get_settings_api: could not load database list: {e}")
        data["database_list"] = []

    active = SettingsManager._all_channel_ids(data)
    titles = data.get("channel_titles") or {}
    if not isinstance(titles, dict):
        titles = {}
    titles = {str(k): str(v) for k, v in titles.items() if str(k) in active and v}
    missing = [cid for cid in active if cid not in titles]
    if missing:
        full = SettingsManager.current().to_dict()
        await SettingsManager._sync_channel_titles(full)
        try:
            await db.save_settings(full)
            SettingsManager._current = SettingsManager.current().__class__(full)
        except Exception as e:
            LOGGER.warning(f"get_settings_api: could not persist channel titles: {e}")
        titles = full.get("channel_titles") or {}
    data["channel_titles"] = {str(k): str(v) for k, v in (titles or {}).items() if k and v}

    return {"settings": data}


async def update_settings_api(payload: dict) -> dict:

    #----- Empty password string means leave it unchanged
    if "admin_password" in payload and not str(payload["admin_password"]).strip():
        del payload["admin_password"]
    if "session_secret" in payload and not str(payload["session_secret"]).strip():
        del payload["session_secret"]

    #----- Type coercion and validation
    bool_keys = {"replace_mode", "duplicate_protection", "hide_catalog", "subscription", "show_proxy_and_non_proxy_both", "mediaflow_proxy", "announce_new_content", "delete_on_metadata_fail", "better_poster_enabled", "rpdb_enabled", "spatial_poster_enabled", "fanart_enabled", "fanart_shuffle", "fanart_low_res_poster"}
    for key in bool_keys:
        if key in payload:
            payload[key] = bool(payload[key])

    list_str_keys = {"auth_channels", "multi_tokens", "helper_tokens", "extra_databases", "global_search_channels", "anime_channels", "manual_channels"}
    for key in list_str_keys:
        if key in payload:
            if not isinstance(payload[key], list):
                raise HTTPException(status_code=400, detail=f"'{key}' must be a list.")
            payload[key] = [str(v).strip() for v in payload[key] if str(v).strip()]

    if "better_poster" in payload:
        payload["better_poster"] = str(payload["better_poster"] or "").strip()
        if payload["better_poster"] and "{imdb_id}" not in payload["better_poster"]:
            raise HTTPException(status_code=400, detail="wrong betterposter url")

    if "spatial_poster" in payload:
        payload["spatial_poster"] = str(payload["spatial_poster"] or "").strip()
        if payload["spatial_poster"] and "{imdb_id}" not in payload["spatial_poster"]:
            raise HTTPException(status_code=400, detail="SpatialPosters URL must contain {imdb_id}")

    if payload.get("spatial_poster_enabled") and not payload.get("spatial_poster"):
        raise HTTPException(status_code=400, detail="SpatialPosters URL is required")

    if "stream_formatter" in payload:
        from Backend.helper.stream_formatter import PRESETS
        if payload["stream_formatter"] not in ("default", "custom", *PRESETS):
            raise HTTPException(status_code=400, detail="Unknown stream formatter")
    for key in ("formatter_name", "formatter_description"):
        if key in payload:
            payload[key] = str(payload[key] or "")[:20000]

    if "default_streaming" in payload and payload["default_streaming"] not in ("bots", "userbot"):
        raise HTTPException(status_code=400, detail="default_streaming must be 'bots' or 'userbot'")

    if "rpdb_api_key" in payload:
        payload["rpdb_api_key"] = str(payload["rpdb_api_key"] or "").strip()

    if "fanart_api_key" in payload:
        payload["fanart_api_key"] = str(payload["fanart_api_key"] or "").strip()

    if "fanart_shuffle_interval" in payload:
        try:
            payload["fanart_shuffle_interval"] = max(0, int(payload["fanart_shuffle_interval"]))
        except (ValueError, TypeError):
            payload["fanart_shuffle_interval"] = 5

    if len([k for k in ("better_poster_enabled", "rpdb_enabled", "spatial_poster_enabled", "fanart_enabled") if payload.get(k)]) > 1:
        raise HTTPException(status_code=400, detail="Enable only one poster provider at a time")

    if payload.get("fanart_enabled") and not str(payload.get("fanart_api_key") or "").strip():
        raise HTTPException(status_code=400, detail="Fanart.tv API key is required")

    if "extra_databases" in payload:
        for uri in payload["extra_databases"]:
            if not uri.startswith(("mongodb://", "mongodb+srv://")):
                raise HTTPException(
                    status_code=400,
                    detail=f"Invalid database URI (must start with mongodb:// or mongodb+srv://): {uri[:30]}…"
                )

    if "approver_ids" in payload:
        if not isinstance(payload["approver_ids"], list):
            raise HTTPException(status_code=400, detail="'approver_ids' must be a list.")
        try:
            payload["approver_ids"] = [int(v) for v in payload["approver_ids"] if str(v).strip()]
        except (ValueError, TypeError):
            raise HTTPException(status_code=400, detail="All approver_ids must be integers.")

    if "subscription_group_id" in payload:
        try:
            payload["subscription_group_id"] = int(payload["subscription_group_id"])
        except (ValueError, TypeError):
            raise HTTPException(status_code=400, detail="'subscription_group_id' must be an integer.")
    def _validate_channel_id(channel: str, field: str) -> str:
        channel = str(channel).strip()
        if not channel:
            return ""
        if not channel.startswith("-100") or not channel[4:].isdigit() or len(channel) < 8:
            raise HTTPException(
                status_code=400,
                detail=f"Invalid {field}: '{channel}'. Only channel IDs in -100xxxxxxxxxx format are accepted (channels only, no groups/users/bots)."
            )
        return channel

    if "auth_channels" in payload:
        cleaned = []
        for channel in payload["auth_channels"]:
            c = _validate_channel_id(channel, "auth channel")
            if c:
                cleaned.append(c)
        payload["auth_channels"] = cleaned

    if "global_search_channels" in payload:
        cleaned = []
        for channel in payload["global_search_channels"]:
            c = _validate_channel_id(channel, "global search channel")
            if c:
                cleaned.append(c)
        payload["global_search_channels"] = cleaned

    if "anime_channels" in payload:
        cleaned = []
        for channel in payload["anime_channels"]:
            c = _validate_channel_id(channel, "anime channel")
            if c:
                cleaned.append(c)
        payload["anime_channels"] = cleaned

    if "manual_channels" in payload:
        cleaned = []
        for channel in payload["manual_channels"]:
            c = _validate_channel_id(channel, "manual channel")
            if c:
                cleaned.append(c)
        payload["manual_channels"] = cleaned

    if "announcement_channel" in payload and payload["announcement_channel"]:
        payload["announcement_channel"] = _validate_channel_id(
            payload["announcement_channel"], "announcement channel"
        )

    if "skip_channel" in payload and payload["skip_channel"]:
        payload["skip_channel"] = _validate_channel_id(
            payload["skip_channel"], "skip channel"
        )

    #----- The same channel id may not appear in more than one channel field.
    #----- Only AUTH ∩ ANIME is allowed, because an anime channel is an auth channel
    #----- that's flagged as anime (the receiver only indexes files from auth channels).
    _channel_fields = ("auth_channels", "manual_channels", "global_search_channels",
                       "anime_channels", "announcement_channel", "skip_channel")
    if any(field in payload for field in _channel_fields):
        current = SettingsManager.current()

        def _norm_ids(values) -> set:
            if isinstance(values, str):
                values = [values]
            return {str(c).strip().replace("-100", "") for c in (values or []) if str(c).strip()}

        groups = {
            "AUTH": _norm_ids(payload.get("auth_channels", list(current.auth_channels))),
            "MANUAL": _norm_ids(payload.get("manual_channels", list(current.manual_channels))),
            "GLOBAL SEARCH": _norm_ids(payload.get("global_search_channels", list(current.global_search_channels))),
            "ANIME": _norm_ids(payload.get("anime_channels", list(current.anime_channels))),
            "ANNOUNCEMENT": _norm_ids(payload.get("announcement_channel", current.announcement_channel)),
            "SKIP": _norm_ids(payload.get("skip_channel", current.skip_channel)),
        }

        allowed_overlap = frozenset({"AUTH", "ANIME"})
        names = list(groups)
        for i in range(len(names)):
            for j in range(i + 1, len(names)):
                a, b = names[i], names[j]
                if frozenset({a, b}) == allowed_overlap:
                    continue
                clash = groups[a] & groups[b]
                if clash:
                    raise HTTPException(
                        status_code=400,
                        detail=f"Channel {', '.join(sorted(clash))} can't be in both {a} and {b} channels — each channel may only belong to one field."
                    )

    #----- Strip whitespace from string fields
    for key in ("tmdb_api", "base_url", "upstream_repo", "upstream_branch",
                "admin_username", "admin_password", "session_secret", "http_proxy_url",
                "cf_stream_url", "cf_stream_secret", "cf_stream_mode",
                "mediaflow_password", "payment_instructions", "payment_qr_url",
                "announcement_channel", "skip_channel"):
        if key in payload and isinstance(payload[key], str):
            payload[key] = payload[key].strip()

    if payload.get("admin_password"):
        payload["admin_password"] = hash_password(payload["admin_password"])

    try:
        reinit_results = await SettingsManager.update(db, payload)
        return {
            "message": "Settings saved successfully.",
            "reinit": reinit_results,
        }
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc))
    except Exception as exc:
        raise HTTPException(status_code=500, detail=str(exc))


# ─────────────────────────────────────────────────────────────────────────────
#  Tools — WebUI replacement for /scan, /rescan, /scanstatus, /cancelscan, /dbcheck
# ─────────────────────────────────────────────────────────────────────────────

#----- Pick a Telegram client capable of fetching channel messages
def _scan_client():
    if StreamBot is not None:
        return StreamBot
    if multi_clients:
        return multi_clients.get(0) or next(iter(multi_clients.values()))
    return None


#----- Configured AUTH channels with friendly names for the picker
async def get_tools_channels_api() -> dict:
    channels = list(SettingsManager.current().auth_channels)
    client = _scan_client()

    async def _resolve(ch):
        name = str(ch)
        try:
            if client is not None:
                chat = await client.get_chat(int(ch) if str(ch).lstrip("-").isdigit() else ch)
                name = getattr(chat, "title", None) or getattr(chat, "first_name", None) or str(ch)
        except Exception as e:
            LOGGER.warning(f"[Tools] Could not resolve channel {ch}: {e}")
        return {"id": str(ch), "name": name}

    return {"status": "success", "data": await asyncio.gather(*(_resolve(ch) for ch in channels))}


#----- ── Manual upload session (web replacement for the /set bot command) ──

#----- Personal (hand-made) titles get a negative synthetic tmdb_id; real ones are positive
def _is_personal_media(tmdb_id) -> bool:
    try:
        return int(tmdb_id) < 0
    except (TypeError, ValueError):
        return False


#----- Normalize a media document into a compact session-picker result
def _session_result(doc: dict) -> dict:
    mt = doc.get("media_type") or doc.get("type") or "movie"
    mt = "tv" if str(mt).lower() in ("tv", "series") else "movie"
    imdb_id = doc.get("imdb_id") or ""
    tmdb_id = doc.get("tmdb_id")
    selected_id = imdb_id if str(imdb_id).startswith("tt") else (str(tmdb_id) if tmdb_id is not None else "")
    return {
        "tmdb_id": tmdb_id,
        "db_index": doc.get("db_index"),
        "media_type": mt,
        "title": doc.get("title") or "",
        "year": doc.get("release_year") or "",
        "poster": resolve_cover_url(doc.get("poster") or ""),
        "imdb_id": imdb_id,
        "selected_id": selected_id,
        "is_personal": _is_personal_media(tmdb_id),
        "in_library": True,
    }


#----- Search the library, then IMDb/Cinemeta + TMDB, by title or an id/link
async def search_manual_session_api(query: str) -> dict:
    query = (query or "").strip()
    if not query:
        return {"results": []}

    results: list[dict] = []
    seen: set = set()

    def _add(doc: dict) -> None:
        entry = _session_result(doc)
        key = (entry["tmdb_id"], entry["db_index"], entry["media_type"])
        if entry["tmdb_id"] is None or key in seen:
            return
        seen.add(key)
        results.append(entry)

    default_id = extract_default_id(query)
    if default_id:
        try:
            if str(default_id).startswith("tt"):
                doc = await db.get_media_details(default_id)
                if doc:
                    _add(doc)
            else:
                for mt in ("movie", "tv"):
                    location = await db.find_media_doc(mt, int(default_id))
                    if location:
                        found, db_index = location
                        found["media_type"] = mt
                        found["db_index"] = db_index
                        _add(found)
        except Exception as e:
            LOGGER.warning(f"[Manual Session] id lookup failed for '{query}': {e}")

    if not default_id:
        try:
            data = await db.search_documents(query, 1, 20)
            for doc in data.get("results", []):
                _add(doc)
        except Exception as e:
            LOGGER.warning(f"[Manual Session] library search failed for '{query}': {e}")

    library_ids = {(e.get("imdb_id") or "", str(e.get("tmdb_id") or "")) for e in results}
    try:
        online = await search_any_candidates(query)
    except Exception as e:
        LOGGER.warning(f"[Manual Session] online search failed for '{query}': {e}")
        online = []

    for cand in online:
        if not cand.get("selected_id") or not cand.get("title"):
            continue
        imdb_id = cand.get("imdb_id") or ""
        tmdb_id = cand.get("tmdb_id")
        if (imdb_id, str(tmdb_id or "")) in library_ids:
            continue
        results.append({
            "tmdb_id": tmdb_id,
            "db_index": None,
            "media_type": "tv" if cand.get("media_type") == "tv" else "movie",
            "title": cand.get("title") or "",
            "year": cand.get("year") or "",
            "poster": resolve_cover_url(cand.get("poster") or ""),
            "imdb_id": imdb_id,
            "selected_id": str(cand.get("selected_id")),
            "source": cand.get("source"),
            "is_personal": False,
            "in_library": False,
        })

    return {"results": results}


#----- Current active manual upload session (or None)
async def get_manual_session_api() -> dict:
    return {"session": getattr(Backend, "MANUAL_SESSION", None)}


async def _set_online_manual_session(payload: dict, media_type: str, selected_id: str) -> dict:
    if not selected_id:
        raise HTTPException(status_code=400, detail="A library title or a selected id is required.")

    meta = await (
        fetch_selected_movie_metadata(selected_id) if media_type == "movie"
        else fetch_selected_tv_metadata(selected_id)
    )
    if not meta:
        raise HTTPException(status_code=404, detail="Could not fetch metadata for the selected title.")

    imdb_id = meta.get("imdb_id") or ""
    default_id = imdb_id if str(imdb_id).startswith("tt") else selected_id

    season = payload.get("season")
    if media_type == "tv" and season is not None and str(season).strip() != "":
        try:
            season = int(season)
        except (TypeError, ValueError):
            raise HTTPException(status_code=400, detail="Season must be a number.")
    else:
        season = None

    try:
        display_tmdb = int(meta.get("tmdb_id")) if meta.get("tmdb_id") is not None else 0
    except (TypeError, ValueError):
        display_tmdb = 0

    session = {
        "tmdb_id": display_tmdb,
        "db_index": None,
        "media_type": media_type,
        "title": meta.get("title") or "",
        "year": meta.get("release_year") or "",
        "is_personal": False,
        "kind": "real",
        "default_id": default_id,
        "season": season,
        "episode": None,
        "quality": None,
    }
    Backend.MANUAL_SESSION = session
    return {"status": "success", "session": session}


#----- Activate a manual upload session targeting an existing library title.
#----- Real (TMDB/IMDb) titles parse season/episode/quality from each file; personal
#----- (hand-made) titles need a season for TV since their files carry no metadata.
async def set_manual_session_api(payload: dict) -> dict:
    tmdb_id = payload.get("tmdb_id")
    db_index = payload.get("db_index")
    media_type = _normalize_media_type(payload.get("media_type", "movie"))
    selected_id = str(payload.get("selected_id") or "").strip()
    in_library = payload.get("in_library", True) and tmdb_id is not None and db_index is not None

    if not in_library:
        return await _set_online_manual_session(payload, media_type, selected_id)

    doc = await db.get_document(media_type, int(tmdb_id), int(db_index))
    if not doc:
        raise HTTPException(status_code=404, detail="That title was not found in your library.")

    is_personal = _is_personal_media(tmdb_id)
    session = {
        "tmdb_id": int(tmdb_id),
        "db_index": int(db_index),
        "media_type": media_type,
        "title": doc.get("title") or "",
        "year": doc.get("release_year") or "",
        "is_personal": is_personal,
    }

    if is_personal:
        #----- Personal: files have no usable metadata, so season/episode come from here
        season = payload.get("season")
        episode = payload.get("episode")
        quality = str(payload.get("quality") or "").strip()

        if media_type == "tv":
            if season is None or str(season).strip() == "":
                raise HTTPException(status_code=400, detail="A season number is required for personal TV shows.")
            try:
                season = int(season)
            except (TypeError, ValueError):
                raise HTTPException(status_code=400, detail="Season must be a number.")
            if episode is not None and str(episode).strip() != "":
                try:
                    episode = int(episode)
                except (TypeError, ValueError):
                    raise HTTPException(status_code=400, detail="Episode must be a number.")
            else:
                episode = None
        else:
            season = None
            episode = None

        session.update({
            "kind": "personal",
            "default_id": None,
            "season": season,
            "episode": episode,
            "quality": quality or None,
        })
    else:
        #----- Real: force the title's own id and let metadata() parse from each file.
        #----- An optional season is only used as a fallback for files that carry an
        #----- episode but no season (e.g. absolute-numbered anime).
        imdb_id = doc.get("imdb_id") or ""
        default_id = imdb_id if str(imdb_id).startswith("tt") else str(int(tmdb_id))

        season = payload.get("season")
        if media_type == "tv" and season is not None and str(season).strip() != "":
            try:
                season = int(season)
            except (TypeError, ValueError):
                raise HTTPException(status_code=400, detail="Season must be a number.")
        else:
            season = None

        session.update({
            "kind": "real",
            "default_id": default_id,
            "season": season,
            "episode": None,
            "quality": None,
        })

    Backend.MANUAL_SESSION = session
    return {"status": "success", "session": session}


#----- Clear the active manual upload session
async def clear_manual_session_api() -> dict:
    Backend.MANUAL_SESSION = None
    return {"status": "success"}


#----- Start a scan or rescan job over the given channels
async def start_scan_api(payload: dict) -> dict:
    client = _scan_client()
    if client is None:
        raise HTTPException(status_code=503, detail="No Telegram client is connected yet.")

    mode = str(payload.get("mode", "scan")).lower()
    if mode not in ("scan", "rescan"):
        raise HTTPException(status_code=400, detail="mode must be 'scan' or 'rescan'.")
    channels = payload.get("channels") or []
    if not isinstance(channels, list):
        raise HTTPException(status_code=400, detail="'channels' must be a list.")

    result = await scan_manager.start(client, channels, mode=mode)
    if not result.get("ok"):
        raise HTTPException(status_code=409, detail=result.get("message", "Could not start scan."))
    return {"status": "success", **result}


async def cancel_scan_api() -> dict:
    result = await scan_manager.cancel()
    return {"status": "success" if result.get("ok") else "error", **result}


async def scan_status_api() -> dict:
    return {"status": "success", "data": scan_manager.get_status()}


async def start_dbcheck_api() -> dict:
    client = _scan_client()
    if client is None:
        raise HTTPException(status_code=503, detail="No Telegram client is connected yet.")
    result = await dbcheck_manager.start(client)
    if not result.get("ok"):
        raise HTTPException(status_code=409, detail=result.get("message", "Could not start DB check."))
    return {"status": "success", **result}


async def cancel_dbcheck_api() -> dict:
    result = await dbcheck_manager.cancel()
    return {"status": "success" if result.get("ok") else "error", **result}


async def dbcheck_status_api() -> dict:
    return {"status": "success", "data": dbcheck_manager.get_status()}


#----- ── Duplicate check & cleanup ──
async def start_duplicate_check_api() -> dict:
    result = await duplicate_manager.start()
    if not result.get("ok"):
        raise HTTPException(status_code=409, detail=result.get("message", "Could not start duplicate scan."))
    return {"status": "success", **result}


async def cancel_duplicate_check_api() -> dict:
    result = await duplicate_manager.cancel()
    return {"status": "success" if result.get("ok") else "error", **result}


async def duplicate_check_status_api() -> dict:
    return {"status": "success", "data": duplicate_manager.get_status()}


#----- Remove selected duplicate streams, or (delete_all) keep the newest per group
async def purge_duplicates_api(payload: dict | None = None) -> dict:
    payload = payload or {}
    delete_all = bool(payload.get("delete_all"))
    stream_ids = payload.get("stream_ids")
    if not delete_all and (not isinstance(stream_ids, list) or not stream_ids):
        raise HTTPException(status_code=400, detail="Provide 'stream_ids' or set 'delete_all'.")
    result = await duplicate_manager.purge(stream_ids, delete_all=delete_all)
    return {"status": "success" if result.get("ok") else "error", **result}


#----- Purge dead links (from last dbcheck, flagged in DB, or a specific set)
async def purge_dead_links_api(payload: dict | None = None) -> dict:
    payload = payload or {}
    source = str(payload.get("source", "dbcheck")).lower()
    stream_ids = payload.get("stream_ids")

    if stream_ids is not None:
        result = await dbcheck_manager.purge(stream_ids)
    elif source == "flagged":
        try:
            flagged = await db.get_all_dead_links()
            ids = list({d.get("quality_id") for d in flagged if d.get("quality_id")})
        except Exception as e:
            raise HTTPException(status_code=500, detail=f"Could not load flagged dead links: {e}")
        result = await dbcheck_manager.purge(ids)
    else:
        result = await dbcheck_manager.purge()

    return {"status": "success" if result.get("ok") else "error", **result}



#----- ── System & Maintenance (web replacements for /stats, /log, /restart) ──

LOG_FILE = "log.txt"


#----- Aggregate content + system metrics across all storage DBs (was /stats)
async def get_db_stats_api() -> dict:
    try:
        total_movies = total_tv = total_episodes = total_streams = total_db_size = 0

        for i in range(1, db.current_db_index + 1):
            storage = db.dbs.get(f"storage_{i}")
            if storage is None:
                continue

            total_movies += await storage["movie"].count_documents({})
            async for movie in storage["movie"].find({}, {"telegram": 1}):
                total_streams += len(movie.get("telegram", []))

            total_tv += await storage["tv"].count_documents({})
            async for show in storage["tv"].find({}, {"seasons": 1}):
                for season in show.get("seasons", []):
                    for episode in season.get("episodes", []):
                        total_episodes += 1
                        total_streams += len(episode.get("telegram", []))

            try:
                total_db_size += (await storage.command("dbStats")).get("dataSize", 0)
            except Exception:
                pass

        return {
            "status": "success",
            "data": {
                "version": __version__,
                "movies": total_movies,
                "tv_shows": total_tv,
                "episodes": total_episodes,
                "streams": total_streams,
                "uptime": get_readable_time(int(time() - StartTime)),
                "db_size": get_readable_file_size(total_db_size),
                "storage_dbs": db.current_db_index,
                "auth_channels": len(SettingsManager.current().auth_channels),
            },
        }
    except Exception as e:
        LOGGER.error(f"[Stats] Error: {e}")
        return {"status": "error", "message": str(e)}


#----- First-run setup checklist: what's configured vs still missing
async def setup_status_api() -> dict:
    s = SettingsManager.current()
    checks = [
        {"key": "tmdb", "label": "TMDB API key", "done": bool(s.tmdb_api),
         "hint": "Powers automatic poster & metadata matching."},
        {"key": "tvdb", "label": "TVDB API key", "done": bool(s.tvdb_api),
         "hint": "Improves TV show matching; used after TMDB / with anime pipelines."},
        {"key": "channels", "label": "AUTH channel added", "done": len(s.auth_channels) > 0,
         "hint": "The channel(s) the bot indexes and streams from."},
        {"key": "base_url", "label": "Base URL set", "done": bool(s.base_url),
         "hint": "Stremio uses this public address to reach your streams."},
        {"key": "password", "label": "Admin password changed", "done": not verify_password("admin", s.admin_password),
         "hint": "Change the default admin / admin login for security."},
    ]
    done = sum(1 for c in checks if c["done"])
    return {"status": "success", "data": {
        "checks": checks, "done": done, "total": len(checks), "complete": done == len(checks),
    }}


#----- Config backup export (settings minus secrets + catalogs, plans, tokens)
async def export_config_api() -> dict:
    return await export_config()


#----- Config backup restore
async def import_config_api(payload: dict) -> dict:
    try:
        result = await import_config(payload)
        return {"status": "success", "result": result, "message": "Backup restored successfully."}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        LOGGER.error(f"Config import error: {e}")
        return {"status": "error", "message": str(e)}


#----- Lightweight liveness probe; start_time changes on every boot (restart detection)
async def health_api() -> dict:
    return {"status": "ok", "start_time": StartTime, "version": __version__}


async def version_status_api(force: bool = False) -> dict:
    from Backend.helper.version_check import check_upstream_version, get_version_status
    if force:
        await check_upstream_version(force=True)
    return {"status": "success", "data": get_version_status()}


#----- Full diagnostics report (DBs, bot clients, TMDB, base URL)
async def health_report_api(force: bool = False) -> dict:
    try:
        return {"status": "success", "data": await run_health_checks(force=force)}
    except Exception as e:
        LOGGER.error(f"Health report error: {e}")
        return {"status": "error", "message": str(e)}


#----- Tail of the log file for the web viewer (was /log)
async def get_logs_api(lines: int = 300) -> dict:
    path = os.path.abspath(LOG_FILE)
    if not os.path.exists(path):
        return {"status": "error", "message": "Log file not found.", "log": ""}
    try:
        with open(path, "r", encoding="utf-8", errors="replace") as f:
            tail = f.readlines()[-max(1, min(lines, 2000)):]
        return {"status": "success", "log": "".join(tail)}
    except Exception as e:
        return {"status": "error", "message": str(e), "log": ""}


#----- Download the raw log file (was /log document)
async def download_logs_api():
    path = os.path.abspath(LOG_FILE)
    if not os.path.exists(path):
        raise HTTPException(status_code=404, detail="Log file not found.")
    return FileResponse(path, filename="log.txt", media_type="text/plain")


#----- Run the updater then re-exec the app; runs after the HTTP response is flushed
async def _perform_restart(delay: float = 1.0) -> None:
    await asyncio.sleep(delay)
    try:
        LOGGER.info("Web-triggered restart: running updater...")
        proc = await asyncio.create_subprocess_exec("uv", "run", "update.py")
        await proc.wait()
    except Exception as e:
        LOGGER.error(f"Restart updater failed: {e}")

    uv_path = shutil.which("uv")
    if not uv_path:
        LOGGER.error("Restart aborted: uv not found in PATH.")
        return
    LOGGER.info("Web-triggered restart: re-executing app...")
    os.execl(uv_path, uv_path, "run", "-m", "Backend")


#----- Trigger a restart from the web (was /restart)
async def restart_app_api() -> dict:
    asyncio.create_task(_perform_restart())
    return {"status": "success", "message": "Restart initiated — the server will be back shortly."}



_bot_admin_apply_state: dict = {
    "running": False,
    "status": "idle",
    "total": 0,
    "done": 0,
    "results": [],
    "error": "",
    "task": None,
}


def _norm_chat_id(ch):
    s = str(ch).strip()
    if not s:
        return None
    return int(s) if s.lstrip("-").isdigit() else s


async def _managed_bots() -> list[dict]:
    bots: list[dict] = []
    for cid in sorted(multi_clients.keys()):
        client = multi_clients.get(cid)
        if client is None:
            continue
        me = getattr(client, "me", None)
        if me is None:
            try:
                me = await client.get_me()
            except Exception as e:
                LOGGER.warning(f"[BotAdmin] Could not resolve bot client {cid}: {e}")
                me = None
        if not me:
            continue
        bots.append({
            "client_id": cid,
            "user_id": me.id,
            "username": me.username,
            "name": me.first_name or me.username or f"Bot {cid + 1}",
            "is_main": cid == 0,
        })
    return bots


def _bot_served_channels() -> list[dict]:
    s = SettingsManager.current()
    order: list[str] = []
    mapping: dict[str, dict] = {}

    def add(ch, role):
        nid = _norm_chat_id(ch)
        if nid is None:
            return
        key = str(nid)
        if key not in mapping:
            mapping[key] = {"id": nid, "roles": []}
            order.append(key)
        if role not in mapping[key]["roles"]:
            mapping[key]["roles"].append(role)

    for ch in s.auth_channels:
        add(ch, "auth")
    for ch in s.manual_channels:
        add(ch, "manual")
    for ch in s.anime_channels:
        add(ch, "anime")
    if s.announcement_channel:
        add(s.announcement_channel, "announce")
    if s.skip_channel:
        add(s.skip_channel, "skip")
    return [mapping[k] for k in order]


def _bot_admin_privileges() -> ChatPrivileges:
    return ChatPrivileges(
        can_manage_chat=True,
        can_post_messages=True,
        can_edit_messages=True,
        can_delete_messages=True,
        can_invite_users=True,
        can_pin_messages=False,
        can_promote_members=False,
        can_change_info=False,
        can_restrict_members=False,
        can_manage_video_chats=False,
        is_anonymous=False,
    )


def _no_privileges() -> ChatPrivileges:
    return ChatPrivileges(
        can_manage_chat=False,
        can_post_messages=False,
        can_edit_messages=False,
        can_delete_messages=False,
        can_invite_users=False,
        can_pin_messages=False,
        can_promote_members=False,
        can_change_info=False,
        can_restrict_members=False,
        can_manage_video_chats=False,
        is_anonymous=False,
    )


async def _bot_member_status(chat_id, bot_user_id) -> str:
    try:
        m = await botmod.Userbot.get_chat_member(chat_id, bot_user_id)
        st = m.status
        if st in (ChatMemberStatus.OWNER, ChatMemberStatus.ADMINISTRATOR):
            return "admin"
        if st == ChatMemberStatus.BANNED:
            return "banned"
        if st == ChatMemberStatus.RESTRICTED:
            return "restricted"
        if st == ChatMemberStatus.MEMBER:
            return "member"
        return "missing"
    except Exception:
        return "missing"


def _friendly_promote_error(exc) -> str:
    msg = str(exc)
    up = msg.upper()
    if "CHAT_ADMIN_REQUIRED" in up:
        return "Your session account isn't an admin with rights to do this here."
    if "USER_CREATOR" in up or "ADMIN_RANK" in up:
        return "Can't modify the channel creator."
    if "ADD_ADMINS" in up or ("PROMOTE" in up and "RIGHT" in up):
        return "Your session account can't grant these rights (it doesn't hold them itself)."
    if "PARTICIPANT" in up or "USER_NOT_MUTUAL_CONTACT" in up:
        return "The bot isn't in the channel and couldn't be added automatically."
    if "BOTS_TOO_MUCH" in up:
        return "This channel already has the maximum number of bots."
    return msg


async def _session_rights(chat_id) -> dict:
    try:
        me = await botmod.Userbot.get_chat_member(chat_id, "me")
    except Exception as e:
        return {"manageable": False, "status": "unknown", "reason": f"Couldn't check your rights: {e}"}
    st = me.status
    if st == ChatMemberStatus.OWNER:
        return {"manageable": True, "status": "owner", "reason": ""}
    if st == ChatMemberStatus.ADMINISTRATOR:
        can_promote = bool(getattr(me, "privileges", None) and me.privileges.can_promote_members)
        return {
            "manageable": can_promote,
            "status": "admin_can_promote" if can_promote else "admin_no_promote",
            "reason": "" if can_promote else "You're an admin here but without the 'Add New Admins' permission.",
        }
    return {"manageable": False, "status": "not_admin", "reason": "Your session account is not an admin here."}


async def bot_admin_scan_api() -> dict:
    if botmod.Userbot is None:
        return {"status": "error", "reason": "no_session",
                "message": "Connect your Telegram session from the Settings page to manage channel admins."}

    bots = await _managed_bots()
    if len(bots) <= 1:
        return {"status": "error", "reason": "single_token", "bots": bots,
                "message": "Add at least one extra bot token (multi-token) to use this tool."}

    channels = _bot_served_channels()
    managed_ids = {b["user_id"] for b in bots}
    out: list[dict] = []

    for ch in channels:
        cid = ch["id"]
        entry = {
            "id": str(cid), "roles": ch["roles"], "name": str(cid),
            "accessible": False, "manageable": False, "session_status": "",
            "reason": "", "bots": {}, "orphans": [],
        }

        try:
            chat = await botmod.Userbot.get_chat(cid)
            entry["name"] = getattr(chat, "title", None) or getattr(chat, "first_name", None) or str(cid)
            entry["accessible"] = True
        except Exception as e:
            entry["reason"] = f"Session account can't access this channel: {e}"
            out.append(entry)
            continue

        rights = await _session_rights(cid)
        entry["manageable"] = rights["manageable"]
        entry["session_status"] = rights["status"]
        entry["reason"] = rights["reason"]

        for b in bots:
            entry["bots"][str(b["user_id"])] = await _bot_member_status(cid, b["user_id"])

        try:
            async for m in botmod.Userbot.get_chat_members(cid, filter=ChatMembersFilter.ADMINISTRATORS):
                u = getattr(m, "user", None)
                if u and getattr(u, "is_bot", False) and u.id not in managed_ids:
                    entry["orphans"].append({
                        "user_id": u.id, "username": u.username,
                        "name": u.first_name or u.username or str(u.id),
                    })
        except Exception as e:
            LOGGER.warning(f"[BotAdmin] Could not list admins for {cid}: {e}")

        out.append(entry)

    return {"status": "success", "data": {"bots": bots, "channels": out}}


async def _promote_one(chat_id, bot: dict, privileges: ChatPrivileges, _retry: bool = True) -> dict:
    label = bot.get("name") or (f"@{bot['username']}" if bot.get("username") else str(bot["user_id"]))
    bid = bot["user_id"]

    if await _bot_member_status(chat_id, bid) == "admin":
        return {"bot": label, "user_id": bid, "status": "already", "message": "Already an admin."}

    try:
        await botmod.Userbot.promote_chat_member(chat_id, bid, privileges=privileges)
        return {"bot": label, "user_id": bid, "status": "added", "message": "Promoted to admin."}
    except FloodWait as fw:
        wait = int(getattr(fw, "value", getattr(fw, "x", 5)) or 5)
        if _retry:
            await asyncio.sleep(wait + 1)
            return await _promote_one(chat_id, bot, privileges, _retry=False)
        return {"bot": label, "user_id": bid, "status": "error",
                "message": f"Rate-limited by Telegram (wait {wait}s) — try again."}
    except Exception as e:
        up = str(e).upper()
        if _retry and ("PARTICIPANT" in up or "USER_NOT_MUTUAL_CONTACT" in up):
            try:
                await botmod.Userbot.add_chat_members(chat_id, bid)
                await asyncio.sleep(0.5)
                await botmod.Userbot.promote_chat_member(chat_id, bid, privileges=privileges)
                return {"bot": label, "user_id": bid, "status": "added", "message": "Added and promoted to admin."}
            except Exception as e2:
                return {"bot": label, "user_id": bid, "status": "error", "message": _friendly_promote_error(e2)}
        return {"bot": label, "user_id": bid, "status": "error", "message": _friendly_promote_error(e)}


async def _demote_one(chat_id, user) -> dict:
    label = getattr(user, "first_name", None) or (f"@{user.username}" if getattr(user, "username", None) else str(user.id))
    try:
        await botmod.Userbot.promote_chat_member(chat_id, user.id, privileges=_no_privileges())
        return {"bot": label, "user_id": user.id, "status": "demoted", "message": "Admin rights removed (orphan)."}
    except Exception as e:
        return {"bot": label, "user_id": user.id, "status": "error", "message": _friendly_promote_error(e)}


async def _run_bot_admin_apply(channel_ids, selected, demote_orphans, managed_ids) -> None:
    state = _bot_admin_apply_state
    privileges = _bot_admin_privileges()
    try:
        for raw in channel_ids:
            cid = _norm_chat_id(raw)
            ch_result = {"id": str(cid), "name": str(cid), "items": []}

            try:
                chat = await botmod.Userbot.get_chat(cid)
                ch_result["name"] = getattr(chat, "title", None) or getattr(chat, "first_name", None) or str(cid)
            except Exception as e:
                ch_result["items"].append({"bot": "—", "status": "error", "message": f"Channel not accessible: {e}"})
                state["results"].append(ch_result)
                state["done"] += 1
                continue

            rights = await _session_rights(cid)
            if not rights["manageable"]:
                ch_result["items"].append({
                    "bot": "—", "status": "skipped",
                    "message": rights["reason"] or "Your session account can't add admins here.",
                })
                state["results"].append(ch_result)
                state["done"] += 1
                continue

            for b in selected:
                ch_result["items"].append(await _promote_one(cid, b, privileges))
                await asyncio.sleep(0.3)

            if demote_orphans:
                try:
                    async for m in botmod.Userbot.get_chat_members(cid, filter=ChatMembersFilter.ADMINISTRATORS):
                        u = getattr(m, "user", None)
                        if u and getattr(u, "is_bot", False) and u.id not in managed_ids:
                            ch_result["items"].append(await _demote_one(cid, u))
                            await asyncio.sleep(0.3)
                except Exception as e:
                    ch_result["items"].append({"bot": "orphans", "status": "error", "message": f"Couldn't scan orphans: {e}"})

            state["results"].append(ch_result)
            state["done"] += 1

        state["status"] = "completed"
    except Exception as e:
        LOGGER.error(f"[BotAdmin] Apply run failed: {e}")
        state["status"] = "error"
        state["error"] = str(e)
    finally:
        state["running"] = False


async def bot_admin_apply_api(payload: dict | None = None) -> dict:
    if botmod.Userbot is None:
        raise HTTPException(status_code=503, detail="No Telegram session connected. Connect one from Settings.")

    if _bot_admin_apply_state["running"]:
        raise HTTPException(status_code=409, detail="An apply run is already in progress.")

    payload = payload or {}
    channel_ids = payload.get("channel_ids") or []
    if not isinstance(channel_ids, list) or not channel_ids:
        raise HTTPException(status_code=400, detail="Select at least one channel.")

    bots = await _managed_bots()
    if len(bots) <= 1:
        raise HTTPException(status_code=400, detail="Need a session string and more than one bot token.")

    bot_by_id = {str(b["user_id"]): b for b in bots}
    sel_ids = payload.get("bot_ids")
    if isinstance(sel_ids, list) and sel_ids:
        selected = [bot_by_id[str(x)] for x in sel_ids if str(x) in bot_by_id]
    else:
        selected = bots
    if not selected:
        raise HTTPException(status_code=400, detail="No matching bots selected.")

    demote_orphans = bool(payload.get("demote_orphans"))
    managed_ids = {b["user_id"] for b in bots}

    _bot_admin_apply_state.update({
        "running": True,
        "status": "running",
        "total": len(channel_ids),
        "done": 0,
        "results": [],
        "error": "",
    })
    _bot_admin_apply_state["task"] = asyncio.create_task(
        _run_bot_admin_apply(channel_ids, selected, demote_orphans, managed_ids)
    )
    return {"status": "started", "total": len(channel_ids)}


async def bot_admin_apply_status_api() -> dict:
    st = _bot_admin_apply_state
    return {
        "status": "success",
        "data": {
            "running": st["running"],
            "state": st["status"],
            "total": st["total"],
            "done": st["done"],
            "results": st["results"],
            "error": st["error"],
        },
    }