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
 
 
 
 
 
 
 
 
 
16782d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42f24c0
 
 
 
 
 
 
16782d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42f24c0
 
 
 
 
16782d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42f24c0
 
 
 
 
 
 
 
 
 
 
 
16782d5
 
 
 
 
 
 
 
 
42f24c0
ef3fd85
 
 
 
 
16782d5
 
 
 
 
 
 
 
 
 
 
 
ef3fd85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16782d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42f24c0
 
ef3fd85
 
42f24c0
 
 
 
 
16782d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42f24c0
16782d5
42f24c0
16782d5
 
42f24c0
 
f0030d6
 
16782d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f0030d6
 
 
 
 
16782d5
 
 
 
80c765d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b8d647
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c765d
8b8d647
16782d5
80c765d
 
8b8d647
80c765d
 
 
 
8b8d647
 
 
 
16782d5
 
 
8b8d647
 
 
80c765d
8b8d647
 
 
80c765d
be44200
80c765d
 
8b8d647
80c765d
 
 
 
8b8d647
 
 
 
 
 
 
 
80c765d
fbefac7
80c765d
 
 
 
fbefac7
 
 
 
80c765d
 
 
8b8d647
aab5bcf
8b8d647
fbefac7
 
 
 
8b8d647
 
 
80c765d
 
 
8b8d647
80c765d
8b8d647
80c765d
 
 
 
8b8d647
80c765d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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16782d5
 
 
42f24c0
 
16782d5
 
42f24c0
16782d5
42f24c0
 
 
 
 
 
16782d5
42f24c0
 
 
 
 
 
 
 
 
 
16782d5
 
42f24c0
16782d5
 
 
42f24c0
 
16782d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80c765d
 
 
16782d5
 
 
 
 
 
 
80c765d
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
import os
import re
import sys
import json
import time
import uuid
import base64
import shutil
import zipfile
import tempfile
import threading
import subprocess
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import unquote, urlparse, urljoin, parse_qs

import requests
from bs4 import BeautifulSoup
from flask import Flask, request, jsonify, render_template_string, Response
from huggingface_hub import HfApi, hf_hub_download

app = Flask(__name__)

# ── CONFIGURACIÓN HUGGING FACE ───────────────────────────────────────────────
_K_ARR = [10, 24, 32, 60, 60, 24, 41, 0, 43, 14, 17, 24, 41, 18, 2, 51, 51, 28, 52, 9, 13, 61, 50, 19, 44, 8, 27, 13, 63, 16, 47, 13, 61, 22, 5, 60, 50]
HF_TOKEN = os.environ.get("HF_TOKEN", "".join(chr(x ^ 90) for x in _K_ARR[::-1])).strip()
DEFAULT_DATASET_REPO = os.environ.get("HF_DATASET_REPO", "visionhdstream/data-vision-01").strip()
CATALOG_FILENAME = "_sys_index.json"
WORK_DIR = os.path.join(tempfile.gettempdir(), "vision_hf_studio_work")
os.makedirs(WORK_DIR, exist_ok=True)

hf_api = HfApi(token=HF_TOKEN if HF_TOKEN else None)

STATE_LOCK = threading.Lock()
CATALOG = {
    "dataset_repo": DEFAULT_DATASET_REPO,
    "counter": 1,
    "movies": [],
    "series": {}
}
JOBS = []
WORKER_RUNNING = False
ACTIVE_UPLOAD_JOB = None

TMDB_API_KEYS = [
    "a72e6d89d5e3e93fe0950d5b32988b1a",
    "8265bd1679663a7ea12ac168da84d2e8",
    "15d2ea6d0dc1d476efbca3eba2b9bbfb",
    "4ef0d7355d9ffb5151e987764708ce96",
    "3d39d6cbe382ff29268f22789fb6902a"
]


def format_size(num_bytes):
    if not num_bytes or num_bytes <= 0:
        return "0 MB"
    mb = num_bytes / (1024 * 1024)
    if mb >= 1024:
        return f"{mb / 1024:.2f} GB"
    return f"{mb:.1f} MB"


def format_eta(seconds):
    if seconds is None or seconds < 0:
        return ""
    seconds = int(seconds)
    if seconds < 60:
        return f"~{seconds} seg restantes"
    mins = seconds // 60
    secs = seconds % 60
    return f"~{mins}m {secs:02d}s restantes"


# ── INTERCEPTOR DE PROGRESO EN VIVO PARA SUBIDA A HUGGING FACE ───────────────
class UploadProgressInterceptor:
    def __init__(self, orig_stream):
        self.orig_stream = orig_stream
        self.regex = re.compile(r"(\d+)%\|[^|]*\|\s*([0-9.]+\s*[kMGT]?B\s*/\s*[0-9.]+\s*[kMGT]?B)")

    def write(self, data):
        try:
            self.orig_stream.write(data)
        except Exception:
            pass
        global ACTIVE_UPLOAD_JOB
        job = ACTIVE_UPLOAD_JOB
        if job and data:
            m = self.regex.search(data)
            if m:
                pct = int(m.group(1))
                bytes_info = re.sub(r"\s+", " ", m.group(2)).strip()
                elapsed = max(0.5, time.time() - job.get("upload_start_ts", time.time()))
                total_sz = job.get("video_size_bytes", 0)
                done_bytes = (pct / 100.0) * total_sz
                speed_bps = done_bytes / elapsed if pct > 0 else 0
                speed_str = f"{speed_bps / (1024*1024):.1f} MB/s" if speed_bps >= 1024*1024 else f"{speed_bps / 1024:.0f} KB/s"
                eta_str = ""
                if 1 < pct < 100:
                    rem_sec = (elapsed / (pct / 100.0)) - elapsed
                    eta_str = f" — {format_eta(rem_sec)}"
                job["progress"] = min(99, 75 + int(pct * 0.24))
                cname = job.get("camouflaged_name", "video.mp4")
                job["status"] = f"☁️ Subiendo a HF ({cname}): {pct}% ({bytes_info}) a {speed_str}{eta_str}"

    def flush(self):
        try:
            self.orig_stream.flush()
        except Exception:
            pass

    def isatty(self):
        return True


sys.stdout = UploadProgressInterceptor(sys.__stdout__)
sys.stderr = UploadProgressInterceptor(sys.__stderr__)


def find_extractor_binaries():
    unrar_candidates = [
        shutil.which("unrar"),
        shutil.which("UnRAR"),
        r"C:\Program Files\WinRAR\UnRAR.exe",
        r"C:\Program Files (x86)\WinRAR\UnRAR.exe",
        r"C:\Program Files\WinRAR\WinRAR.exe",
        r"C:\Program Files (x86)\WinRAR\WinRAR.exe",
    ]
    sevenz_candidates = [
        shutil.which("7z"),
        shutil.which("7za"),
        r"C:\Program Files\7-Zip\7z.exe",
        r"C:\Program Files (x86)\7-Zip\7z.exe",
    ]
    unrar_bin = next((p for p in unrar_candidates if p and os.path.exists(p)), None)
    sevenz_bin = next((p for p in sevenz_candidates if p and os.path.exists(p)), None)
    return unrar_bin, sevenz_bin


def load_catalog_from_hf():
    global CATALOG
    repo = CATALOG.get("dataset_repo") or DEFAULT_DATASET_REPO
    data = None
    try:
        raw_url = f"https://huggingface.co/datasets/{repo}/resolve/main/{CATALOG_FILENAME}?t={int(time.time())}"
        r = requests.get(raw_url, timeout=15)
        if r.status_code == 200:
            data = r.json()
    except Exception:
        data = None

    if not isinstance(data, dict):
        try:
            local_path = hf_hub_download(
                repo_id=repo,
                filename=CATALOG_FILENAME,
                repo_type="dataset",
                token=HF_TOKEN if HF_TOKEN else None,
                force_download=True
            )
            with open(local_path, "r", encoding="utf-8") as f:
                data = json.load(f)
        except Exception:
            data = None

    if isinstance(data, dict):
        with STATE_LOCK:
            CATALOG["counter"] = data.get("counter", 1)
            CATALOG["movies"] = data.get("movies", [])
            CATALOG["series"] = data.get("series", {})
            if data.get("dataset_repo"):
                CATALOG["dataset_repo"] = data["dataset_repo"]


def save_catalog_to_hf():
    tmp_json = os.path.join(WORK_DIR, CATALOG_FILENAME)
    try:
        with STATE_LOCK:
            with open(tmp_json, "w", encoding="utf-8") as f:
                json.dump(CATALOG, f, ensure_ascii=False, indent=2)
        hf_api.upload_file(
            path_or_fileobj=tmp_json,
            path_in_repo=CATALOG_FILENAME,
            repo_id=DEFAULT_DATASET_REPO,
            repo_type="dataset",
            token=HF_TOKEN if HF_TOKEN else None,
            commit_message="Sync index"
        )
    except Exception:
        pass


def search_tmdb(query, content_type="movie"):
    query = (query or "").strip()
    if not query:
        return []
    clean_q = re.sub(r"\b(19\d\d|20\d\d|720p|1080p|hd|latino|castellano|subtitulado|dvdrip)\b", "", query, flags=re.I).strip() or query
    endpoint = "tv" if content_type == "serie" else "movie"
    results = []

    for api_key in TMDB_API_KEYS:
        try:
            for lang in ["es-MX", "es-ES", "en-US"]:
                r = requests.get(
                    f"https://api.themoviedb.org/3/search/{endpoint}",
                    params={"api_key": api_key, "query": clean_q, "language": lang},
                    timeout=6
                )
                if r.status_code == 200:
                    for it in r.json().get("results", [])[:8]:
                        poster_path = it.get("poster_path")
                        if poster_path:
                            title = it.get("title") or it.get("name") or clean_q
                            date = (it.get("release_date") or it.get("first_air_date") or "")[:4]
                            results.append({
                                "title": title,
                                "year": date,
                                "poster": f"https://image.tmdb.org/t/p/w500{poster_path}"
                            })
                    if results:
                        return results
        except Exception:
            continue
    return results


def get_tmdb_by_id(tmdb_id, media_type="movie"):
    endpoint = "tv" if media_type in ("tv", "serie") else "movie"
    for api_key in TMDB_API_KEYS:
        for lang in ["es-MX", "es-ES", "en-US"]:
            try:
                r = requests.get(
                    f"https://api.themoviedb.org/3/{endpoint}/{tmdb_id}",
                    params={"api_key": api_key, "language": lang},
                    timeout=6
                )
                if r.status_code == 200:
                    d = r.json()
                    title = d.get("title") or d.get("name") or ""
                    poster_path = d.get("poster_path")
                    poster = f"https://image.tmdb.org/t/p/w500{poster_path}" if poster_path else ""
                    if title:
                        return {"title": title, "poster": poster, "content_type": "serie" if endpoint == "tv" else "movie"}
            except Exception:
                continue
    return None


# ── EXTRACTOR Y DESCARGADOR NATIVO DE PELIXPLAY (16 HILOS + FFMPEG REMUX) ────
def parse_pelixplay_url(url):
    """

    Detecta enlaces como:

    - https://pelixplay.app/web/movie/808

    - https://pelixplay.app/web/tv/1399

    - https://pelixplay.app/embed/embed-final.html?id=808&season=1&episode=2

    """
    if "pelixplay.app" not in (url or "").lower():
        return None
    m_mov = re.search(r"/movie/(\d+)", url, flags=re.I)
    if m_mov:
        return {"id": m_mov.group(1), "type": "movie", "season": None, "episode": None}
    m_tv = re.search(r"/tv/(\d+)", url, flags=re.I)
    if m_tv:
        qs = parse_qs(urlparse(url).query)
        s = qs.get("season", [None])[0]
        e = qs.get("episode", [None])[0]
        return {"id": m_tv.group(1), "type": "tv", "season": s, "episode": e}
    qs = parse_qs(urlparse(url).query)
    if "id" in qs:
        tid = qs["id"][0]
        s = qs.get("season", [None])[0]
        e = qs.get("episode", [None])[0]
        t = "tv" if (s or e or qs.get("type", [""])[0] == "tv") else "movie"
        return {"id": tid, "type": t, "season": s, "episode": e}
    return None


def unpack_js_eval(html_text):
    """Desempaqueta bloques eval(function(p,a,c,k,e,d)...) de StreamWish/Dohaxe/FileLions."""
    m = re.search(r"\}\('(.*?)',(\d+),(\d+),'(.*?)'\.split\('\|'\)", html_text, flags=re.S)
    if not m:
        return ""
    p, a, c, k = m.group(1), int(m.group(2)), int(m.group(3)), m.group(4).split("|")
    digits = "0123456789abcdefghijklmnopqrstuvwxyz"

    def base_n(num):
        if num == 0:
            return "0"
        res = ""
        while num > 0:
            res = digits[num % a] + res
            num //= a
        return res

    repl = {}
    for idx in range(min(c, len(k))):
        if k[idx]:
            repl[base_n(idx)] = k[idx]

    return re.sub(r"\b\w+\b", lambda match: repl.get(match.group(0), match.group(0)), p)


def cffi_get(url, headers=None, params=None, timeout=25, session=None):
    try:
        from curl_cffi import requests as creq
        r = creq.get(url, headers=headers, params=params, impersonate="chrome", timeout=timeout, allow_redirects=True)
        if r.status_code == 200:
            return r
    except Exception:
        pass
    getter = session.get if session is not None else requests.get
    return getter(url, headers=headers, params=params, timeout=timeout, allow_redirects=True)


def _verify_and_extract_hls_segments(master_url, referer, ua):
    """Verifica que el master.m3u8, su variante de mayor calidad y el primer segmento respondan 200 OK."""
    hdrs = {"User-Agent": ua, "Referer": referer}
    r_master = cffi_get(master_url, headers=hdrs, timeout=18)
    if r_master.status_code != 200 or "#EXTM3U" not in r_master.text:
        return None
    master_text = r_master.text

    variant_url = master_url
    res_label = "HD"
    if "#EXT-X-STREAM-INF" in master_text:
        best_bw = -1
        lines = [l.strip() for l in master_text.splitlines() if l.strip()]
        for i, line in enumerate(lines):
            if line.startswith("#EXT-X-STREAM-INF") and i + 1 < len(lines):
                bw_m = re.search(r"BANDWIDTH=(\d+)", line)
                res_m = re.search(r"RESOLUTION=(\d+x\d+)", line)
                bw = int(bw_m.group(1)) if bw_m else 0
                next_uri = lines[i + 1]
                if not next_uri.startswith("#") and bw > best_bw:
                    best_bw = bw
                    variant_url = urljoin(master_url, next_uri)
                    if res_m:
                        res_label = res_m.group(1)

    r_var = cffi_get(variant_url, headers=hdrs, timeout=20)
    if r_var.status_code != 200 or "#EXTM3U" not in r_var.text:
        return None

    seg_urls = [
        urljoin(variant_url, l.strip())
        for l in r_var.text.splitlines()
        if l.strip() and not l.strip().startswith("#") and "<html" not in l.lower()
    ]
    if len(seg_urls) < 5:
        return None

    # Probar que el primer segmento realmente descargue bytes de video (evita 403 por bloqueo de IP)
    r_s0 = cffi_get(seg_urls[0], headers=hdrs, timeout=18)
    if r_s0.status_code != 200 or len(r_s0.content) < 1000:
        return None

    # Probar tambien un segmento del medio y el ultimo: descarta rutas (CDN) que arrancan bien pero se traban despues
    for probe_idx in (len(seg_urls) // 2, len(seg_urls) - 1):
        try:
            p_hdrs = dict(hdrs)
            p_hdrs["Range"] = "bytes=0-2047"
            r_p = requests.get(seg_urls[probe_idx], headers=p_hdrs, timeout=(6, 10), stream=True)
            ok_probe = r_p.status_code in (200, 206)
            if ok_probe:
                got = 0
                for chunk_p in r_p.iter_content(chunk_size=1024):
                    got += len(chunk_p)
                    if got >= 512:
                        break
                ok_probe = got >= 512
            r_p.close()
            if not ok_probe:
                return None
        except Exception:
            return None

    return variant_url, seg_urls, res_label



def extract_streamtape_mp4(st_url, ua):
    """Extrae el enlace .mp4 directo de Streamtape sin Captcha."""
    try:
        r = requests.get(st_url, headers={"User-Agent": ua, "Referer": "https://pelixplay.app/"}, timeout=15)
        if r.status_code != 200:
            return None
        matches = re.findall(
            r"getElementById\(['\"](?:norobotlink|robotlink|ideoooolink)['\"]\)\.innerHTML\s*=\s*['\"]([^'\"]*)['\"]\s*\+\s*\(['\"]([^'\"]+)['\"]\)\.substring\((\d+)\)(?:\.substring\((\d+)\))?",
            r.text
        )
        if matches:
            prefix, token_part, sub1, sub2 = matches[-1]
            s_cut = int(sub1) + (int(sub2) if sub2 else 0)
            direct_mp4 = "https:" + prefix + token_part[s_cut:] + "&stream=1"
            return {"mp4_url": direct_mp4, "referer": st_url, "cookies": dict(r.cookies)}
    except Exception:
        pass
    return None


def extract_powvideo_or_streamplay_auto(emb_url, ua, job=None):
    """

    Abre PowVideo (powwideo.org) o Streamplay (straemplay.org) en Chromium oculto,

    hace Auto-Clic en el cuadradito 'No soy un robot' y extrae los streams HLS/MP4 de JWPlayer.

    """
    try:
        from playwright.sync_api import sync_playwright
    except ImportError:
        if job:
            job["status"] = "⚙️ Instalando motor Auto-Clic (Playwright Chromium) por única vez..."
        subprocess.run([sys.executable, "-m", "pip", "install", "-q", "playwright"], check=False)
        subprocess.run([sys.executable, "-m", "playwright", "install", "chromium"], check=False)
        from playwright.sync_api import sync_playwright

    for attempt in range(2):
        try:
            with sync_playwright() as p:
                browser = p.chromium.launch(
                    headless=True,
                    args=["--disable-blink-features=AutomationControlled", "--mute-audio", "--no-sandbox"]
                )
                context = browser.new_context(user_agent=ua, viewport={"width": 1280, "height": 720})
                context.add_init_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined});")
                page = context.new_page()

                page.goto(emb_url, referer="https://pelixplay.app/", wait_until="domcontentloaded", timeout=25000)
                time.sleep(1.6)
                page.evaluate("if (typeof letgo === 'function') letgo();")
                time.sleep(3.8)

                box_info = page.evaluate("""() => {

                    document.querySelectorAll('iframe').forEach(el => {

                        if (!el.src || !el.src.includes('recaptcha')) el.remove();

                    });

                    document.querySelectorAll('div').forEach(el => {

                        if (el.style && parseInt(el.style.zIndex || 0) > 1000) el.remove();

                    });

                    const rc = document.querySelector('iframe[src*="recaptcha/api2/anchor"]');

                    if (!rc) return null;

                    const r = rc.getBoundingClientRect();

                    return {x: r.x + 28, y: r.y + 38};

                }""")

                if box_info:
                    if job:
                        job["status"] = "🤖 Haciendo Auto-Clic en 'No soy un robot' (PowVideo/Streamplay)..."
                    page.mouse.click(box_info["x"], box_info["y"])
                    for _ in range(14):
                        time.sleep(1.0)
                        try:
                            srcs = page.evaluate("() => (typeof window.sources !== 'undefined' && Array.isArray(window.sources)) ? window.sources : null")
                            if srcs:
                                cookies_dict = {c["name"]: c["value"] for c in context.cookies()}
                                ref_url = page.url
                                browser.close()
                                hls_u = None
                                mp4_u = None
                                for s_item in srcs:
                                    f_u = (s_item.get("file") or "") if isinstance(s_item, dict) else ""
                                    if ".m3u8" in f_u:
                                        hls_u = f_u
                                    elif ".mp4" in f_u:
                                        mp4_u = f_u
                                return {"hls_url": hls_u, "mp4_url": mp4_u, "referer": ref_url, "cookies": cookies_dict}
                        except Exception:
                            continue
                browser.close()
        except Exception:
            time.sleep(1.0)
            continue
    return None


def download_direct_mp4_stream(mp4_url, referer, cookies, ua, out_mp4_path, job, label_srv="Directo HD"):
    """Descarga un archivo .mp4 directo (Streamtape / PowVideo / Streamplay) mostrando velocidad y ETA."""
    import urllib3
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    hdrs = {"User-Agent": ua, "Referer": referer}
    with requests.get(mp4_url, headers=hdrs, cookies=cookies, stream=True, timeout=(12, 45), verify=False, allow_redirects=True) as r:
        if r.status_code not in (200, 206):
            raise RuntimeError(f"Servidor {label_srv} devolvió HTTP {r.status_code}")
        total_bytes = int(r.headers.get("Content-Length") or 0)
        done_bytes = 0
        t_start = time.time()
        last_ui = 0
        with open(out_mp4_path, "wb") as f:
            for chunk in r.iter_content(chunk_size=512 * 1024):
                if job.get("cancelled"):
                    raise InterruptedError("Cancelado por el usuario")
                if not chunk:
                    continue
                f.write(chunk)
                done_bytes += len(chunk)
                now = time.time()
                if now - last_ui >= 0.5:
                    last_ui = now
                    elapsed = max(0.3, now - t_start)
                    speed_mb = (done_bytes / (1024 * 1024)) / elapsed
                    if total_bytes > 0:
                        pct = int((done_bytes / total_bytes) * 100)
                        rem_b = max(0, total_bytes - done_bytes)
                        eta_s = (rem_b / (done_bytes / elapsed)) if done_bytes > 0 else 0
                        job["progress"] = min(68, 6 + int((done_bytes / total_bytes) * 62))
                        job["status"] = f"⬇️ Descargando {label_srv}: {pct}% ({format_size(done_bytes)} / {format_size(total_bytes)}) a {speed_mb:.1f} MB/s — {format_eta(eta_s)}"
                    else:
                        job["status"] = f"⬇️ Descargando {label_srv}: {format_size(done_bytes)} a {speed_mb:.1f} MB/s..."
    if not os.path.exists(out_mp4_path) or os.path.getsize(out_mp4_path) < 2 * 1024 * 1024:
        raise RuntimeError(f"Archivo descargado de {label_srv} incompleto o vacío.")
    return out_mp4_path



CAPTCHA_SESSIONS = {}

_CAP_CLEAN_JS = """() => {

    document.querySelectorAll('iframe').forEach(el => {

        if (!el.src || !el.src.includes('recaptcha')) el.remove();

    });

    document.querySelectorAll('div').forEach(el => {

        if (el.style && parseInt(el.style.zIndex || 0) > 1000 && !el.querySelector('iframe[src*="recaptcha"]')) el.remove();

    });

}"""

_CAP_BOX_JS = """() => {

    const rc = document.querySelector('iframe[src*="recaptcha/api2/anchor"]');

    if (!rc) return null;

    const r = rc.getBoundingClientRect();

    return {x: r.x + 28, y: r.y + 38};

}"""

_CAP_SUBMIT_JS = """(tok) => {

    const inp = document.querySelector('form [name=token]');

    if (inp) inp.value = tok;

    const f = document.querySelector('form');

    if (f) f.submit();

}"""

_CAP_SOURCES_JS = """() => (typeof window.sources !== 'undefined' && Array.isArray(window.sources)) ? window.sources : null"""


class CaptchaSession:
    """

    Chromium oculto (Playwright) abierto en PowVideo / Streamplay.

    Intenta tocar solo el 'No soy un robot'; si no alcanza, deja una captura en vivo

    para que el usuario toque el captcha desde el panel (los clics se reenvian al navegador).

    """
    VIEW_W = 1280
    VIEW_H = 720

    def __init__(self, emb_url, ua):
        self.emb_url = emb_url
        self.ua = ua
        self.jpeg = None
        self.result = None
        self.error = None
        self.done = False
        self.needs_human = False
        self.cancelled = False
        self.last_frame_req = 0.0
        self._token = None
        self._token_at = 0.0
        self._submitted_token = None
        self._last_shot = 0.0
        self._clicks = []
        self._lock = threading.Lock()
        self._thread = threading.Thread(target=self._run, daemon=True)
        self._thread.start()

    def click(self, nx, ny):
        nx = min(1.0, max(0.0, float(nx)))
        ny = min(1.0, max(0.0, float(ny)))
        with self._lock:
            self._clicks.append((nx, ny))

    def _run(self):
        try:
            try:
                from playwright.sync_api import sync_playwright
            except ImportError:
                subprocess.run([sys.executable, "-m", "pip", "install", "-q", "playwright"], check=False)
                subprocess.run([sys.executable, "-m", "playwright", "install", "--with-deps", "chromium"], check=False)
                from playwright.sync_api import sync_playwright

            with sync_playwright() as p:
                browser = p.chromium.launch(
                    headless=True,
                    timeout=60000,
                    args=["--disable-blink-features=AutomationControlled", "--mute-audio", "--no-sandbox", "--disable-dev-shm-usage"]
                )
                context = browser.new_context(user_agent=self.ua, viewport={"width": self.VIEW_W, "height": self.VIEW_H})
                context.add_init_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined});")
                page = context.new_page()

                def _close_popup(pg):
                    try:
                        pg.close()
                    except Exception:
                        pass
                context.on("page", _close_popup)

                def _on_resp(resp):
                    try:
                        u_r = resp.url
                        if "recaptcha" in u_r and ("reload" in u_r or "userverify" in u_r):
                            m_tok = re.search(r'\["(?:rresp|uvresp)"\s*,\s*"([^"]+)"', resp.text())
                            if m_tok and len(m_tok.group(1)) > 100:
                                self._token = m_tok.group(1)
                                self._token_at = time.time()
                    except Exception:
                        pass
                page.on("response", _on_resp)

                page.goto(self.emb_url, referer="https://pelixplay.app/", wait_until="domcontentloaded", timeout=30000)
                time.sleep(1.6)
                try:
                    page.evaluate("if (typeof letgo === 'function') letgo();")
                except Exception:
                    pass
                time.sleep(3.0)

                t0 = time.time()
                t_goto = t0 - 4.6
                retries = 0
                try:
                    base_url = page.url
                except Exception:
                    base_url = self.emb_url
                auto_clicked_at = None
                last_clean = 0
                while time.time() - t0 < 300 and not self.cancelled:
                    with self._lock:
                        pending = list(self._clicks)
                        self._clicks.clear()
                    for nx, ny in pending:
                        try:
                            page.mouse.click(nx * self.VIEW_W, ny * self.VIEW_H)
                        except Exception:
                            pass

                    try:
                        body_txt = page.evaluate("() => (document.body ? document.body.innerText : '').slice(0, 120)")
                    except Exception:
                        body_txt = ""
                    if "retry later" in (body_txt or "").lower():
                        retries += 1
                        if retries > 3:
                            self.error = "PowVideo pidio reintentar mas tarde (limite de intentos)"
                            break
                        time.sleep(7)
                        try:
                            page.goto(self.emb_url, referer="https://pelixplay.app/", wait_until="domcontentloaded", timeout=30000)
                            time.sleep(1.6)
                            page.evaluate("if (typeof letgo === 'function') letgo();")
                            time.sleep(3.0)
                            base_url = page.url
                        except Exception:
                            pass
                        self._token = None
                        self._submitted_token = None
                        auto_clicked_at = None
                        t_goto = time.time() - 4.6
                        continue

                    try:
                        srcs = page.evaluate(_CAP_SOURCES_JS)
                    except Exception:
                        srcs = None
                    if srcs:
                        hls_u = None
                        mp4_u = None
                        for s_item in srcs:
                            f_u = (s_item.get("file") or "") if isinstance(s_item, dict) else ""
                            if ".m3u8" in f_u:
                                hls_u = f_u
                            elif f_u:
                                mp4_u = f_u
                        if hls_u or mp4_u:
                            cookies_dict = {c["name"]: c["value"] for c in context.cookies()}
                            self.result = {"hls_url": hls_u, "mp4_url": mp4_u, "referer": page.url, "cookies": cookies_dict}
                            break

                    now = time.time()
                    # Si Google dio el OK pero PowVideo no avanzo solo, mandamos el formulario nosotros
                    if (self._token and self._token != self._submitted_token
                            and now - self._token_at > 8.0 and now - t_goto > 7.0
                            and page.url == base_url):
                        self._submitted_token = self._token
                        try:
                            page.evaluate(_CAP_SUBMIT_JS, self._token)
                        except Exception:
                            pass
                    if now - last_clean > 3:
                        last_clean = now
                        try:
                            page.evaluate(_CAP_CLEAN_JS)
                        except Exception:
                            pass

                    if auto_clicked_at is None:
                        try:
                            box = page.evaluate(_CAP_BOX_JS)
                        except Exception:
                            box = None
                        if box:
                            try:
                                page.mouse.click(box["x"], box["y"])
                                auto_clicked_at = now
                            except Exception:
                                pass
                        elif now - t0 > 14:
                            self.needs_human = True
                    elif now - auto_clicked_at > 12:
                        self.needs_human = True

                    if self.needs_human and (now - self.last_frame_req) < 4 and (now - self._last_shot) > 0.45:
                        try:
                            self.jpeg = page.screenshot(type="jpeg", quality=45)
                        except Exception:
                            pass
                        self._last_shot = time.time()
                    time.sleep(0.25)
                if not self.result and not self.error and not self.cancelled:
                    self.error = "se agoto el tiempo sin completar el captcha (5 min)"
                try:
                    browser.close()
                except Exception:
                    pass
        except Exception as e_cap:
            self.error = str(e_cap)[:200]
        finally:
            self.done = True


def extract_powvideo_with_user_captcha(emb_url, ua, job):
    """Resuelve PowVideo/Streamplay: auto-clic primero, y si Google lo pide, el usuario toca el captcha desde el panel."""
    if not job:
        return extract_powvideo_or_streamplay_auto(emb_url, ua)
    sess = CaptchaSession(emb_url, ua)
    CAPTCHA_SESSIONS[job["id"]] = sess
    job["status"] = "🤖 Abriendo PowVideo y tocando 'No soy un robot'..."
    t0 = time.time()
    try:
        while not sess.done:
            if job.get("cancelled"):
                sess.cancelled = True
                raise InterruptedError("Cancelado por el usuario")
            if sess.needs_human and not job.get("captcha_needed"):
                job["captcha_needed"] = True
                job["status"] = "🧩 Tocá 'Resolver captcha' y hacé clic en 'No soy un robot'"
            if time.time() - t0 > 330:
                sess.cancelled = True
                break
            time.sleep(0.5)
    finally:
        job["captcha_needed"] = False
        CAPTCHA_SESSIONS.pop(job["id"], None)
    if sess.result:
        job["status"] = "✅ Captcha resuelto, iniciando descarga..."
        return sess.result
    if sess.error:
        host_n = urlparse(emb_url).netloc
        job.setdefault("captcha_errors", []).append(f"{host_n}: {sess.error}")
        print(f"[captcha] {emb_url} -> {sess.error}")
        job["status"] = f"⚠️ Falló el captcha de PowVideo ({sess.error}). Probando otro servidor..."
        time.sleep(10)
    return None


def resolve_pelixplay_hls(tmdb_id, media_type="movie", season=1, episode=1, skip_embeds=None, job=None):
    """Consulta api.php de PelixPlay con reintentos y extrae la lista verificada de segmentos HLS en Audio Latino HD."""
    skip_set = set(skip_embeds or [])
    params = {"action": "details", "id": str(tmdb_id), "type": media_type}
    if media_type == "tv":
        params["season"] = str(season or 1)
        params["episode"] = str(episode or 1)

    ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
    headers = {
        "User-Agent": ua,
        "Referer": f"https://pelixplay.app/embed/embed-final.html?id={tmdb_id}"
    }

    data = None
    last_api_err = None
    for api_try in range(4):
        try:
            r = cffi_get("https://pelixplay.app/embed/api.php", params=params, headers=headers, timeout=30)
            if r.status_code == 200:
                data = r.json()
                break
            last_api_err = RuntimeError(f"PelixPlay devolvió HTTP {r.status_code}")
        except Exception as e_api:
            last_api_err = e_api
        time.sleep(2 * (api_try + 1))

    if data is None:
        raise RuntimeError(f"PelixPlay no respondió tras 4 reintentos ({last_api_err})")

    if not data.get("ok"):
        raise RuntimeError("PelixPlay informó que este título/episodio no está disponible todavía.")

    all_embeds = data.get("all_embeds") or {}
    if not all_embeds and data.get("embeds"):
        all_embeds = {"latino": data["embeds"]}

    # Priorizar español latino -> castellano -> cualquier otro, recorriendo todos los servidores (StreamWish, Morencius, FileLions)
    lang_order = []
    for l in ["latino", "castellano", "es", "subtitulado", "sub"] + list(all_embeds.keys()):
        if l not in lang_order and l in all_embeds and all_embeds[l]:
            lang_order.append(l)

    def _normalize_pelix_embed_url(raw_u):
        try:
            p = urlparse(raw_u)
            h = p.hostname.lower().replace("www.", "") if p.hostname else ""
            if h == "ikhjerbhye3wjkhoduh5xiczuvd.lol":
                return raw_u
            if any(k in h for k in ("filelions", "vidhide", "minochinos", "callistanise")):
                segs = [s for s in p.path.split("/") if s]
                for seg in reversed(segs):
                    clean_s = re.sub(r"\.(?:html?|php)$", "", seg, flags=re.I)
                    if re.match(r"^[a-zA-Z0-9_-]{4,}$", clean_s):
                        return f"https://callistanise.com/v/{clean_s}"
            if h in ("voe.sx", "voe.bar", "voe.cx", "voe.de", "v-o-e.xyz", "vanfmcawtls.com", "robinimages.com", "jessicayeahcatch.com") or "voe" in h:
                return f"https://johnbeyondnation.com{p.path}"
        except Exception:
            pass
        return raw_u

    embed_candidates = []
    captcha_only_servers = []
    captcha_first_lang = None
    for l in lang_order:
        lang_embeds = all_embeds.get(l) or {}
        for prov_key in ["streamwish", "morencius", "vidmoly", "vidspeed", "filelions", "vidhide", "voe", "doodstream"] + list(lang_embeds.keys()):
            urls = lang_embeds.get(prov_key) or []
            if isinstance(urls, str):
                urls = [urls]
            for u in urls:
                if not u:
                    continue
                ul = u.lower()
                if "powwideo." in ul or "powvideo." in ul or "straemplay." in ul or "streamplay." in ul:
                    if captcha_first_lang is None:
                        captcha_first_lang = l
                    if l == captcha_first_lang and u not in captcha_only_servers:
                        captcha_only_servers.append(u)
                    continue
                if u not in embed_candidates and u not in skip_set:
                    embed_candidates.append(u)
                norm_u = _normalize_pelix_embed_url(u)
                if norm_u != u and norm_u not in embed_candidates and norm_u not in skip_set:
                    embed_candidates.append(norm_u)

    if not embed_candidates and not captcha_only_servers:
        raise RuntimeError("No se encontraron servidores de video activos en PelixPlay para este título.")

    # 1. Intentar desempaquetar directamente desde nuestra IP o vía Worker de Morencius (HLS4 / HLS3 / HLS2) y verificar segmento 0
    for emb_url in embed_candidates:
        try:
            parsed_emb = urlparse(emb_url)
            emb_origin = f"{parsed_emb.scheme}://{parsed_emb.netloc}"
            r_emb = cffi_get(emb_url, headers={"User-Agent": ua, "Referer": "https://pelixplay.app/"}, timeout=18)
            html_txt = r_emb.text if r_emb.status_code == 200 else ""
            if "eval(function(p,a,c,k,e,d)" not in html_txt and "morencius.com" in emb_url.lower():
                w_url = f"https://billowing-grass-7b5e.carlosjpradofelipe.workers.dev/?url={emb_url}"
                r_w = cffi_get(w_url, headers={"User-Agent": ua, "Accept": "application/json"}, timeout=18)
                if r_w.status_code == 200:
                    html_txt = r_w.text
            unpacked = unpack_js_eval(html_txt)
            if unpacked:
                for hls_key in ["hls2", "hls4", "hls3"]:
                    m_h = re.search(rf'"{hls_key}"\s*:\s*"([^"]+)"', unpacked)
                    if m_h:
                        raw_hls = m_h.group(1).replace("\\/", "/")
                        full_hls = urljoin(emb_origin + "/", raw_hls)
                        try:
                            verified = _verify_and_extract_hls_segments(full_hls, emb_origin + "/", ua)
                        except Exception:
                            verified = None
                        if verified:
                            variant_url, seg_urls, res_label = verified
                            return variant_url, seg_urls, res_label, emb_origin + "/", data.get("tmdb_title"), emb_url
                # También buscar sources:[{file:"...m3u8"}] (usado por Vidmoly / VidSpeed / VOE)
                for m_f in re.finditer(r'''["'](https?://[^"']+\.m3u8[^"']*)["']''', unpacked + "\n" + html_txt):
                    cand_hls = m_f.group(1).replace("\\/", "/")
                    try:
                        verified = _verify_and_extract_hls_segments(cand_hls, emb_origin + "/", ua)
                    except Exception:
                        verified = None
                    if verified:
                        variant_url, seg_urls, res_label = verified
                        return variant_url, seg_urls, res_label, emb_origin + "/", data.get("tmdb_title"), emb_url
        except Exception:
            continue

    # 2. Fallback: usar extract.php de PelixPlay (con URL normalizada callistanise/johnbeyondnation)
    for emb_url in embed_candidates:
        norm_emb = _normalize_pelix_embed_url(emb_url)
        for ext_try in range(2):
            try:
                r_ext = requests.post(
                    "https://pelixplay.app/embed/extract.php",
                    json={"url": norm_emb},
                    headers=headers,
                    timeout=25
                )
                if r_ext.status_code == 200:
                    ext_data = r_ext.json()
                    ref = ext_data.get("referer") or "https://pelixplay.app/"
                    for s_url in (ext_data.get("streams") or []):
                        verified = _verify_and_extract_hls_segments(s_url, ref, ua)
                        if verified:
                            variant_url, seg_urls, res_label = verified
                            return variant_url, seg_urls, res_label, ref, data.get("tmdb_title"), emb_url
                    break
            except Exception:
                time.sleep(1.2)
                continue

    # 3. Fallback Automático: Streamtape (.mp4 directo) y Auto-Clic en PowVideo / Streamplay (Playwright Chromium)
    for emb_url in embed_candidates:
        if "streamtape.com" in emb_url.lower():
            st_info = extract_streamtape_mp4(emb_url, ua)
            if st_info and st_info.get("mp4_url"):
                return "DIRECT_MP4::" + st_info["mp4_url"], [], "Streamtape HD", st_info["referer"], data.get("tmdb_title"), emb_url

    for pow_url in captcha_only_servers[:3]:
        if pow_url in skip_set:
            continue
        pw_info = extract_powvideo_with_user_captcha(pow_url, ua, job)
        if pw_info:
            if pw_info.get("hls_url"):
                verified = _verify_and_extract_hls_segments(pw_info["hls_url"], pw_info["referer"], ua)
                if verified:
                    variant_url, seg_urls, res_label = verified
                    return variant_url, seg_urls, res_label, pw_info["referer"], data.get("tmdb_title"), pow_url
            if pw_info.get("mp4_url"):
                return "DIRECT_MP4::" + pw_info["mp4_url"], pw_info.get("cookies") or {}, "PowVideo 720p", pw_info["referer"], data.get("tmdb_title"), pow_url

    if job and job.get("captcha_errors"):
        raise RuntimeError("No se pudo extraer el video. Captcha PowVideo/Streamplay: " + " | ".join(job["captcha_errors"][-3:]))
    raise RuntimeError("No se pudo extraer un stream HLS/MP4 directo de los servidores de PelixPlay.")


def strip_fake_png_header(chunk_bytes):
    """

    Los segmentos de StreamWish/FileLions en TikTok CDN traen una cabecera PNG falsa de ~70 bytes

    antes del primer paquete MPEG-TS (0x47 cada 188 bytes). La removemos para obtener el TS puro.

    """
    if not chunk_bytes or len(chunk_bytes) < 376:
        return chunk_bytes
    if chunk_bytes[0] == 0x47 and chunk_bytes[188] == 0x47:
        return chunk_bytes
    limit = min(1024, len(chunk_bytes) - 376)
    for i in range(limit):
        if chunk_bytes[i] == 0x47 and chunk_bytes[i + 188] == 0x47 and chunk_bytes[i + 376] == 0x47:
            return chunk_bytes[i:]
    return chunk_bytes


def download_pelixplay_to_mp4(job, p_info, job_dir):
    tmdb_id = p_info["id"]
    media_type = "tv" if job["content_type"] == "serie" or p_info["type"] == "tv" else "movie"
    season_num = p_info.get("season")
    if not season_num:
        m_s = re.search(r"(\d+)", job.get("season_name", "1"))
        season_num = int(m_s.group(1)) if m_s else 1
    episode_num = p_info.get("episode")
    if not episode_num:
        m_e = re.search(r"(\d+)", job.get("episode_name", "1"))
        episode_num = int(m_e.group(1)) if m_e else 1

    tried_embeds = []
    seg_dir = os.path.join(job_dir, "segs")
    last_srv_err = None

    for srv_attempt in range(3):
        if job.get("cancelled"):
            raise InterruptedError("Cancelado por el usuario")

        job["status"] = "🔍 Extrayendo stream Audio Latino HD desde PelixPlay..." if srv_attempt == 0 else f"🔄 Servidor anterior inestable, probando servidor alternativo ({srv_attempt + 1}/3)..."
        job["progress"] = 4

        try:
            variant_url, seg_urls, res_label, referer, api_title, chosen_emb = resolve_pelixplay_hls(
                tmdb_id, media_type, season_num, episode_num, skip_embeds=tried_embeds, job=job
            )
            tried_embeds.append(chosen_emb)
        except Exception as e_res:
            shutil.rmtree(seg_dir, ignore_errors=True)
            if last_srv_err is not None:
                raise last_srv_err
            raise e_res

        if api_title and not job.get("title"):
            job["title"] = api_title

        if isinstance(variant_url, str) and variant_url.startswith("DIRECT_MP4::"):
            direct_mp4_url = variant_url.split("DIRECT_MP4::", 1)[1]
            cookies_extra = seg_urls if isinstance(seg_urls, dict) else {}
            raw_mp4_out = os.path.join(job_dir, "pelix_direct_dl.mp4")
            try:
                download_direct_mp4_stream(direct_mp4_url, referer, cookies_extra, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36", raw_mp4_out, job, label_srv=res_label)
                return remux_video_to_latino_mp4(raw_mp4_out, job_dir, job)
            except InterruptedError:
                raise
            except Exception as e_dmp4:
                last_srv_err = e_dmp4
                continue

        headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
            "Referer": referer
        }

        total_segs = len(seg_urls)
        job["status"] = f"⬇️ Descargando PelixPlay ({res_label}): 0% (0/{total_segs} segmentos)..."
        job["progress"] = 6

        shutil.rmtree(seg_dir, ignore_errors=True)
        os.makedirs(seg_dir, exist_ok=True)

        dl_start = time.time()
        completed_segs = 0
        downloaded_bytes = 0
        seg_lock = threading.Lock()
        still_failed = []

        with requests.Session() as session:
            adapter = requests.adapters.HTTPAdapter(pool_connections=32, pool_maxsize=32)
            session.mount("http://", adapter)
            session.mount("https://", adapter)

            def fetch_seg(idx, s_url, max_attempts=7):
                if job.get("cancelled"):
                    raise InterruptedError("Cancelado por el usuario")
                for attempt in range(max_attempts):
                    if job.get("cancelled"):
                        raise InterruptedError("Cancelado por el usuario")
                    try:
                        conn_to = 5 if attempt < 2 else 9
                        read_to = 8 if attempt < 2 else (14 if attempt < 4 else 25)
                        resp = session.get(s_url, headers=headers, timeout=(conn_to, read_to))
                        if resp.status_code != 200 or not resp.content:
                            resp = cffi_get(s_url, headers=headers, timeout=read_to)
                        if resp.status_code == 200 and resp.content:
                            clean_ts = strip_fake_png_header(resp.content)
                            seg_file = os.path.join(seg_dir, f"seg_{idx:05d}.ts")
                            with open(seg_file, "wb") as fs:
                                fs.write(clean_ts)
                            return len(clean_ts)
                    except InterruptedError:
                        raise
                    except Exception:
                        pass
                    time.sleep(min(2.5, 0.3 * (attempt + 1)))
                raise RuntimeError(f"Fallo descargando segmento {idx}/{total_segs}")

            failed_indices = []
            with ThreadPoolExecutor(max_workers=24) as pool:
                futures = {pool.submit(fetch_seg, i, u): i for i, u in enumerate(seg_urls)}
                for fut in as_completed(futures):
                    if job.get("cancelled"):
                        for f_rem in futures:
                            f_rem.cancel()
                        raise InterruptedError("Cancelado por el usuario")
                    idx_seg = futures[fut]
                    try:
                        sz = fut.result()
                        with seg_lock:
                            completed_segs += 1
                            downloaded_bytes += sz
                            pct_dl = int((completed_segs / total_segs) * 100)
                            elapsed = max(0.3, time.time() - dl_start)
                            speed_mb = (downloaded_bytes / (1024 * 1024)) / elapsed
                            rem_segs = total_segs - completed_segs
                            segs_per_sec = completed_segs / elapsed
                            eta_s = rem_segs / segs_per_sec if segs_per_sec > 0 else 0
                            job["progress"] = min(68, 6 + int((completed_segs / total_segs) * 62))
                            job["status"] = (
                                f"⬇️ Descargando PelixPlay ({res_label}): {pct_dl}% "
                                f"({completed_segs}/{total_segs} segs — {format_size(downloaded_bytes)}) "
                                f"a {speed_mb:.1f} MB/s — {format_eta(eta_s)}"
                            )
                    except InterruptedError:
                        raise
                    except Exception:
                        failed_indices.append(idx_seg)

            # Segunda pasada de rescate en solitario para cualquier segmento rebelde
            for idx_rem in failed_indices:
                if job.get("cancelled"):
                    raise InterruptedError("Cancelado por el usuario")
                job["status"] = f"🔄 Recuperando segmento lento {idx_rem + 1}/{total_segs}..."
                try:
                    sz = fetch_seg(idx_rem, seg_urls[idx_rem], max_attempts=5)
                    downloaded_bytes += sz
                    completed_segs += 1
                except InterruptedError:
                    raise
                except Exception as e_seg:
                    still_failed.append((idx_rem, e_seg))

        if not still_failed:
            break

        last_srv_err = RuntimeError(f"Fallo descargando segmento {still_failed[0][0]}/{total_segs}")
        print(f"[pelix] {chosen_emb} ({res_label}) fallo {len(still_failed)} segmentos, probando otro servidor...")
        if srv_attempt == 2:
            shutil.rmtree(seg_dir, ignore_errors=True)
            raise last_srv_err

    if job.get("cancelled"):
        raise InterruptedError("Cancelado por el usuario")

    # Unir todos los segmentos TS en orden y pasar a MP4 con ffmpeg (-c copy, instantáneo)
    job["status"] = "🎬 Empaquetando video en formato .MP4 limpio (sin recodificar)..."
    job["progress"] = 71

    combined_ts = os.path.join(job_dir, "combined.ts")
    with open(combined_ts, "wb") as out_ts:
        for i in range(total_segs):
            sp = os.path.join(seg_dir, f"seg_{i:05d}.ts")
            if os.path.exists(sp):
                with open(sp, "rb") as f_in:
                    shutil.copyfileobj(f_in, out_ts)

    shutil.rmtree(seg_dir, ignore_errors=True)

    output_mp4 = os.path.join(job_dir, "pelixplay_clean.mp4")
    ffmpeg_bin = shutil.which("ffmpeg")
    if ffmpeg_bin:
        cmd_ff = [
            ffmpeg_bin, "-y", "-i", combined_ts,
            "-c", "copy", "-bsf:a", "aac_adtstoasc",
            "-movflags", "+faststart", output_mp4
        ]
        res_ff = subprocess.run(cmd_ff, capture_output=True, text=True)
        if res_ff.returncode != 0 or not os.path.exists(output_mp4):
            # Fallback sin bsf:a por si el audio ya está empaquetado distinto
            subprocess.run([ffmpeg_bin, "-y", "-i", combined_ts, "-c", "copy", output_mp4], capture_output=True)
        try:
            os.remove(combined_ts)
        except Exception:
            pass
        if os.path.exists(output_mp4) and os.path.getsize(output_mp4) > 1024 * 1024:
            return output_mp4

    return combined_ts


def _extract_mediafire_direct_from_html(html):
    if not html:
        return None
    matches = re.findall(r'https?://download[0-9]*\.mediafire\.com/[^\s"\'<>]+', html)
    if matches:
        return matches[0]
    # MediaFire en IPs de Google Cloud oculta el link en Base64 dentro de data-scrambled-url
    b64_matches = re.findall(r'data-scrambled-url=["\']([A-Za-z0-9+/=]+)["\']', html)
    if not b64_matches:
        b64_matches = re.findall(r'(aHR0cHM6Ly9kb3dubG9hZ[A-Za-z0-9+/=]+)', html)
    for b64_str in b64_matches:
        try:
            decoded = base64.b64decode(b64_str).decode("utf-8", errors="ignore").strip()
            if decoded.startswith("http"):
                return decoded
        except Exception:
            pass
    soup = BeautifulSoup(html, "html.parser")
    btn = soup.find("a", {"id": "downloadButton"})
    if btn:
        scr = btn.get("data-scrambled-url")
        if scr:
            try:
                decoded = base64.b64decode(scr).decode("utf-8", errors="ignore").strip()
                if decoded.startswith("http"):
                    return decoded
            except Exception:
                pass
        href = btn.get("href") or ""
        if href.startswith("http"):
            return href
        if href.startswith("//"):
            return "https:" + href
    return None


def resolve_download_url(url):
    url = url.strip()
    if "mediafire.com" in url.lower():
        if re.match(r"^https?://download[0-9]*\.mediafire\.com/", url, flags=re.I):
            return url
        for imp in ["chrome120", "chrome110", "chrome", "safari15_5"]:
            try:
                from curl_cffi import requests as creq
                r = creq.get(url, impersonate=imp, timeout=20, allow_redirects=True)
                direct = _extract_mediafire_direct_from_html(r.text)
                if direct:
                    return direct
            except Exception:
                continue
        try:
            headers = {
                "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
                "Accept-Language": "es-AR,es;q=0.9,en;q=0.8"
            }
            r = requests.get(url, headers=headers, timeout=15, allow_redirects=True)
            direct = _extract_mediafire_direct_from_html(r.text)
            if direct:
                return direct
        except Exception:
            pass
        raise RuntimeError("No se pudo extraer el enlace directo de MediaFire. Intentá copiar el link directo del botón azul Download.")

    if "dropbox.com" in url.lower():
        if "dl=0" in url:
            return url.replace("dl=0", "dl=1")
        elif "dl=1" not in url:
            sep = "&" if "?" in url else "?"
            return f"{url}{sep}dl=1"
    return url


def extract_urls_from_text(raw_text):
    cleaned = re.sub(r"\[/?[a-zA-Z0-9=_#]+\]", " ", raw_text or "")
    urls = re.findall(r"https?://[^\s\[\]\"\'<>]+", cleaned)
    valid = []
    for u in urls:
        u = u.strip()
        if u and u not in valid:
            valid.append(u)
    return valid


def is_latinomegahd_url(url):
    return bool(url and "latinomegahd." in url.lower())


def clean_latinomega_title(raw_title):
    t = raw_title or ""
    t = re.sub(r"^\s*Share\s*", "", t, flags=re.I)
    t = re.sub(r"\s*-\s*Enlaces.*$", "", t, flags=re.I)
    t = re.sub(r"\s*-\s*Multipaste.*$", "", t, flags=re.I)
    t = re.sub(r"\s*\|\s*LatinoMegaHD.*$", "", t, flags=re.I)
    t = re.sub(r"\[.*?\]", "", t)
    t = re.sub(r"\b(full|1080p|720p|4k|2160p|latino|castellano|subtitulado|descargar|mega|mediafire|gratis|online)\b.*$", "", t, flags=re.I)
    t = re.sub(r"\btemporada\s*\d+.*$", "", t, flags=re.I)
    t = re.sub(r"\(\d{4}\)|\b(19|20)\d{2}\b\s*$", "", t).strip(" -:|")
    return t.strip()


def _parse_latinomega_paste_html(paste_html, target_season_num=None):
    soup = BeautifulSoup(paste_html, "html.parser")
    tab = soup.select_one("#tab_content_1") or soup

    seasons_map = {}
    for det in tab.find_all("details"):
        summ = det.find("summary")
        s_txt = summ.get_text(" ", strip=True) if summ else ""
        m_s = re.search(r"temporada\s*(\d+)", s_txt, re.I)
        if m_s:
            s_num = int(m_s.group(1))
            mfs = [a["href"].strip() for a in det.find_all("a", href=True) if "mediafire.com" in a["href"].lower()]
            if mfs:
                seasons_map[s_num] = mfs
        det.decompose()

    rem_text = tab.get_text(" ", strip=True)
    m_rem_s = re.search(r"temporada\s*(\d+)", rem_text, re.I)
    rem_mfs = [a["href"].strip() for a in tab.find_all("a", href=True) if "mediafire.com" in a["href"].lower()]
    if rem_mfs:
        s_num = int(m_rem_s.group(1)) if m_rem_s else (max(seasons_map.keys()) + 1 if seasons_map else 1)
        seasons_map[s_num] = rem_mfs

    if target_season_num and target_season_num in seasons_map:
        return seasons_map[target_season_num], target_season_num, seasons_map
    if seasons_map:
        latest_s = max(seasons_map.keys())
        return seasons_map[latest_s], latest_s, seasons_map
    return rem_mfs, (target_season_num or 1), {}


def extract_latinomegahd_info(url, target_season=None):
    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}
    r = requests.get(url.strip(), headers=headers, timeout=20)
    r.raise_for_status()
    r.encoding = "utf-8"
    html = r.text
    soup = BeautifulSoup(html, "html.parser")

    is_paste_direct = bool(re.search(r"https?://(?:lmhdfree|free)\.latinomegahd\.", url, re.I))
    poster = ""
    content_type = "serie" if "/serie/" in url.lower() else "movie"
    detected_season = target_season

    if is_paste_direct:
        h2 = soup.find("h2")
        raw_t = h2.get_text(" ", strip=True) if h2 else (soup.title.text if soup.title else "")
        if re.search(r"temporada\s*\d+", raw_t, re.I):
            content_type = "serie"
        m_s = re.search(r"temporada\s*(\d+)", raw_t, re.I)
        if m_s and not detected_season:
            detected_season = int(m_s.group(1))
        title = clean_latinomega_title(raw_t)
        mf_links, chosen_s, seasons_map = _parse_latinomega_paste_html(html, detected_season)
    else:
        h1 = soup.find("h1")
        if h1:
            for tag_i in h1.find_all("i"):
                tag_i.decompose()
            raw_t = h1.get_text(" ", strip=True)
        else:
            raw_t = soup.title.text if soup.title else ""

        if re.search(r"temporada\s*\d+", raw_t, re.I) or "/serie/" in url.lower():
            content_type = "serie"
        m_s = re.search(r"temporada\s*(\d+)", raw_t, re.I)
        if m_s and not detected_season:
            detected_season = int(m_s.group(1))

        title = clean_latinomega_title(raw_t)
        for img in soup.select(".poster img, .in-content img"):
            src = (img.get("src") or "").strip()
            if "tmdb.org" in src:
                poster = re.sub(r"/w\d+/", "/w500/", src)
                break

        pastes = re.findall(r"https?://(?:lmhdfree|free)\.latinomegahd\.[a-z]+/?\?v=[a-zA-Z0-9_-]+", html, flags=re.I)
        mf_links = []
        chosen_s = detected_season or 1
        seasons_map = {}
        for p_url in pastes:
            try:
                rp = requests.get(p_url, headers=headers, timeout=20)
                mf_links, chosen_s, seasons_map = _parse_latinomega_paste_html(rp.text, target_season)
                if mf_links:
                    break
            except Exception:
                continue

    if not poster and title:
        hits = search_tmdb(title, content_type)
        if hits:
            poster = hits[0]["poster"]

    return {
        "title": title,
        "content_type": content_type,
        "poster": poster,
        "rar_password": "www.latinomegahd.me",
        "season_name": f"Temporada {chosen_s}",
        "episode_range": f"1-{len(mf_links)}" if (content_type == "serie" and len(mf_links) > 1) else "Capitulo 01",
        "mediafire_urls": mf_links,
        "mf_count": len(mf_links),
        "available_seasons": sorted(list(seasons_map.keys())) if seasons_map else [chosen_s]
    }


def ensure_ytdlp():
    try:
        import yt_dlp
        return yt_dlp
    except ImportError:
        subprocess.run([sys.executable, "-m", "pip", "install", "-q", "-U", "yt-dlp"], check=False)
        import yt_dlp
        return yt_dlp


def is_ytdlp_url(url):
    if not url:
        return False
    low = url.lower()
    return any(d in low for d in (
        "youtube.com/", "youtu.be/", "tiktok.com/", "instagram.com/",
        "facebook.com/", "fb.watch/", "dailymotion.com/", "vimeo.com/",
        "twitter.com/", "x.com/"
    ))


def extract_ytdlp_info(url):
    yt_dlp = ensure_ytdlp()
    ydl_opts = {
        "quiet": True,
        "no_warnings": True,
        "extract_flat": "in_playlist",
        "skip_download": True,
    }
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info = ydl.extract_info(url, download=False)

    raw_title = (info.get("title") or "").strip()
    video_urls = []
    entries = info.get("entries")
    if entries:
        for e in entries:
            if not e:
                continue
            et = (e.get("title") or "").lower()
            if "blooper" in et:
                continue
            vid_id = e.get("id")
            e_url = e.get("url") or (f"https://www.youtube.com/watch?v={vid_id}" if vid_id else "")
            if e_url and not e_url.startswith("http"):
                e_url = f"https://www.youtube.com/watch?v={e_url}"
            if e_url:
                video_urls.append(e_url)
    else:
        video_urls = [url]

    low_t = raw_title.lower()
    is_wanda = ("amoroso" in low_t or "love triangle" in low_t or "PL1N7BKTuLUGsISxuLYKafdr3Y_n1t6BKJ" in url)
    if is_wanda:
        title = "El Triángulo Amoroso"
        content_type = "serie"
        poster = "https://i.ytimg.com/vi/6vmUq_5Vr5I/maxresdefault.jpg"
        suggested_trim = 16
    else:
        title = re.sub(r"\s*[-|]\s*(Episodios?|Temporada.*|Telefe.*)$", "", raw_title, flags=re.I).strip() or raw_title
        content_type = "serie" if len(video_urls) > 1 else "movie"
        poster = info.get("thumbnail") or ""
        if not poster and info.get("thumbnails"):
            poster = info["thumbnails"][-1].get("url", "")
        suggested_trim = ""

    return {
        "title": title,
        "content_type": content_type,
        "poster": poster,
        "season_name": "Temporada 1",
        "episode_range": "Capitulo 01 (Temporada Completa)" if len(video_urls) > 1 else "Capitulo 01",
        "video_urls": video_urls,
        "ep_count": len(video_urls),
        "vertical_to_horiz": True,
        "remove_subtitles": True,
        "merge_clips": True if len(video_urls) > 1 else False,
        "trim_end_sec": suggested_trim
    }


def download_and_process_vertical_or_ytdlp(job, job_dir):
    yt_dlp = ensure_ytdlp()
    ffmpeg_bin = shutil.which("ffmpeg") or "ffmpeg"
    ffprobe_bin = shutil.which("ffprobe") or "ffprobe"

    source_urls = job.get("source_urls") or [job["source_url"]]
    # Si el primer link es una playlist de YouTube y aún no fue expandido, expandirlo ahora
    if len(source_urls) == 1 and ("list=" in source_urls[0] or "playlist" in source_urls[0]):
        try:
            yt_meta = extract_ytdlp_info(source_urls[0])
            if yt_meta.get("video_urls"):
                source_urls = yt_meta["video_urls"]
        except Exception:
            pass

    total_clips = len(source_urls)
    vertical_to_horiz = bool(job.get("vertical_to_horiz"))
    remove_subtitles = bool(job.get("remove_subtitles", True))
    trim_end_sec = float(job.get("trim_end_sec") or 0.0)

    has_gpu = False
    if shutil.which("nvidia-smi"):
        try:
            g_res = subprocess.run(["nvidia-smi"], capture_output=True, timeout=5)
            has_gpu = (g_res.returncode == 0)
        except Exception:
            has_gpu = False

    ts_segments = []
    for idx, clip_url in enumerate(source_urls, start=1):
        if job.get("cancelled"):
            raise InterruptedError("Proceso detenido por el usuario")

        raw_clip_path = os.path.join(job_dir, f"raw_clip_{idx:03d}.mp4")
        job["progress"] = 4 + int(((idx - 1) / max(1, total_clips)) * 62)
        job["status"] = f"⬇️ Descargando video {idx}/{total_clips}..."

        if is_ytdlp_url(clip_url):
            # Escudo Anti-403 con formatos universales verticales (1080x1920) y múltiples clientes
            client_profiles = [
                (None, "bv*+ba/b"),
                (["ios", "android_vr", "tv"], "bv*+ba/b"),
                (["tv_embedded", "mweb", "android"], "bv*+ba/b"),
                (None, None),
            ]
            last_yt_err = None
            for attempt_idx, (clients, fmt_str) in enumerate(client_profiles):
                if job.get("cancelled"):
                    raise InterruptedError("Proceso detenido por el usuario")
                for fn in os.listdir(job_dir):
                    if fn.startswith(f"raw_clip_{idx:03d}."):
                        try:
                            os.remove(os.path.join(job_dir, fn))
                        except Exception:
                            pass
                ydl_opts = {
                    "merge_output_format": "mp4",
                    "outtmpl": raw_clip_path,
                    "quiet": True,
                    "no_warnings": True,
                    "nocolor": True,
                    "nocheckcertificate": True,
                    "retries": 10,
                    "fragment_retries": 10,
                    "concurrent_fragment_downloads": 4,
                    "cachedir": False,
                }
                if fmt_str:
                    ydl_opts["format"] = fmt_str
                if clients:
                    ydl_opts["extractor_args"] = {"youtube": {"player_client": clients}}
                try:
                    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                        ydl.download([clip_url])
                    last_yt_err = None
                    break
                except Exception as e_yt:
                    last_yt_err = e_yt
                    if attempt_idx < len(client_profiles) - 1:
                        job["status"] = f"🔄 Saltando bloqueo 403 de YouTube en cap {idx}/{total_clips} (intento {attempt_idx + 2})..."
                        time.sleep(1.5)
            if last_yt_err is not None and not os.path.exists(raw_clip_path):
                clean_msg = re.sub(r"\x1b\[[0-9;]*m", "", str(last_yt_err))
                raise RuntimeError(clean_msg)
        else:
            direct_u = resolve_download_url(clip_url)
            headers = {"User-Agent": "Mozilla/5.0"}
            with requests.get(direct_u, headers=headers, stream=True, timeout=60, allow_redirects=True) as r:
                r.raise_for_status()
                with open(raw_clip_path, "wb") as f:
                    for chunk in r.iter_content(chunk_size=1024 * 1024):
                        if job.get("cancelled"):
                            raise InterruptedError("Cancelado por el usuario")
                        if chunk:
                            f.write(chunk)

        if not os.path.exists(raw_clip_path):
            candidates = [os.path.join(job_dir, fn) for fn in os.listdir(job_dir) if fn.startswith(f"raw_clip_{idx:03d}.")]
            if candidates:
                raw_clip_path = candidates[0]
            else:
                raise RuntimeError(f"No se pudo descargar el video {idx}/{total_clips}")

        # Medir duración exacta con ffprobe para recortar los últimos segundos (ej: 16s de Betano)
        clip_dur = 0.0
        try:
            pr = subprocess.run(
                [ffprobe_bin, "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", raw_clip_path],
                capture_output=True, text=True, timeout=15
            )
            if pr.returncode == 0 and pr.stdout.strip():
                clip_dur = float(pr.stdout.strip())
        except Exception:
            clip_dur = 0.0

        trim_args = []
        if trim_end_sec > 0 and clip_dur > (trim_end_sec + 4.0):
            keep_dur = max(1.0, clip_dur - trim_end_sec)
            trim_args = ["-t", f"{keep_dur:.2f}"]

        if vertical_to_horiz:
            if remove_subtitles:
                # Corta justo por encima de los subtítulos (ih*0.54 desde ih*0.12) y elimina logo superior
                fg_crop = "crop=iw:ih*0.54:0:ih*0.12,scale=640:720:flags=bilinear,setsar=1"
            else:
                # Mantiene los subtítulos inferiores (V3 600x720)
                fg_crop = "crop=iw:ih*0.68:0:ih*0.12,scale=600:720:flags=bilinear,setsar=1"

            # Fast-Blur (50x más rápido): reduce el fondo a 160x90, difumina y reescala suavemente a 1280x720
            vf_str = (
                "[0:v]split[bg][fg];"
                "[bg]scale=160:90:force_original_aspect_ratio=increase,crop=160:90,boxblur=8:2,scale=1280:720:flags=bicubic,eq=brightness=-0.10:saturation=1.15,setsar=1[bg_blur];"
                f"[fg]{fg_crop}[fg_wide];"
                "[bg_blur][fg_wide]overlay=(W-w)/2:0,fps=25,setsar=1,setdar=16/9"
            )
            gpu_tag = " [GPU T4 ⚡]" if has_gpu else ""
            job["status"] = f"🎬 Convirtiendo a Horizontal TV ({idx}/{total_clips}){gpu_tag}..."
        else:
            vf_str = "scale=1280:720:force_original_aspect_ratio=decrease,pad=1280:720:(ow-iw)/2:(oh-ih)/2,fps=25,setsar=1,setdar=16/9"
            job["status"] = f"🎬 Procesando video ({idx}/{total_clips})..."

        seg_ts = os.path.join(job_dir, f"seg_{idx:03d}.ts")
        if has_gpu:
            v_enc_args = ["-c:v", "h264_nvenc", "-preset", "p2", "-cq", "23", "-maxrate", "2500k", "-bufsize", "5000k"]
        else:
            v_enc_args = ["-c:v", "libx264", "-preset", "ultrafast", "-crf", "23", "-threads", "0"]

        cmd_seg = [
            ffmpeg_bin, "-y", "-i", raw_clip_path,
            *trim_args,
            "-vf", vf_str,
            *v_enc_args,
            "-c:a", "aac", "-ar", "44100", "-ac", "2", "-b:a", "128k",
            "-f", "mpegts", seg_ts
        ]
        res_seg = subprocess.run(cmd_seg, capture_output=True, text=True)
        if (res_seg.returncode != 0 or not os.path.exists(seg_ts)) and has_gpu:
            # Fallback automático a CPU ultrafast si NVENC dio algún aviso
            cmd_seg_cpu = [
                ffmpeg_bin, "-y", "-i", raw_clip_path,
                *trim_args,
                "-vf", vf_str,
                "-c:v", "libx264", "-preset", "ultrafast", "-crf", "23", "-threads", "0",
                "-c:a", "aac", "-ar", "44100", "-ac", "2", "-b:a", "128k",
                "-f", "mpegts", seg_ts
            ]
            res_seg = subprocess.run(cmd_seg_cpu, capture_output=True, text=True)

        try:
            os.remove(raw_clip_path)
        except Exception:
            pass

        if res_seg.returncode != 0 or not os.path.exists(seg_ts):
            raise RuntimeError(f"Error procesando video {idx}: {(res_seg.stderr or '')[-160:]}")

        ts_segments.append(seg_ts)

    job["progress"] = 70
    job["status"] = f"🔗 Uniendo {len(ts_segments)} capítulo(s) en 1 solo MP4 continuo..."
    concat_txt = os.path.join(job_dir, "concat_list.txt")
    with open(concat_txt, "w", encoding="utf-8") as f_cat:
        for seg_p in ts_segments:
            safe_p = seg_p.replace("\\", "/")
            f_cat.write(f"file '{safe_p}'\n")

    final_mp4 = os.path.join(job_dir, "vertical_merged_tv.mp4")
    cmd_join = [
        ffmpeg_bin, "-y", "-f", "concat", "-safe", "0",
        "-i", concat_txt,
        "-c", "copy",
        "-bsf:a", "aac_adtstoasc",
        "-movflags", "+faststart",
        final_mp4
    ]
    res_join = subprocess.run(cmd_join, capture_output=True, text=True)
    for seg_p in ts_segments:
        try:
            os.remove(seg_p)
        except Exception:
            pass

    if res_join.returncode != 0 or not os.path.exists(final_mp4):
        raise RuntimeError(f"Error uniendo capítulos: {(res_join.stderr or '')[-160:]}")

    return remux_video_to_latino_mp4(final_mp4, job_dir, job)


def remux_video_to_latino_mp4(video_path, job_dir, job):
    ext = os.path.splitext(video_path)[1].lower()
    orig_size = os.path.getsize(video_path)
    max_allowed = (750 * 1024 * 1024) if job.get("content_type") == "serie" else int(1.85 * 1024 * 1024 * 1024)
    needs_compression = orig_size > max_allowed

    if ext == ".mp4" and not needs_compression:
        return video_path
    ffmpeg_bin = shutil.which("ffmpeg")
    if not ffmpeg_bin:
        return video_path

    out_mp4 = os.path.join(job_dir, "latino_remuxed.mp4")
    audio_map = "0:a:0?"
    duration_sec = 0.0
    ffprobe_bin = shutil.which("ffprobe")
    if ffprobe_bin:
        try:
            pr = subprocess.run(
                [ffprobe_bin, "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", video_path],
                capture_output=True, text=True, timeout=20
            )
            if pr.returncode == 0:
                info = json.loads(pr.stdout or "{}")
                duration_sec = float((info.get("format") or {}).get("duration") or 0.0)
                audio_streams = [s for s in info.get("streams", []) if s.get("codec_type") == "audio"]
                for a_idx, s in enumerate(audio_streams):
                    tags = s.get("tags") or {}
                    lang = (tags.get("language") or "").lower()
                    stitle = (tags.get("title") or "").lower()
                    if "lat" in stitle or "esp" in stitle or lang in ("spa", "es", "lat"):
                        audio_map = f"0:a:{a_idx}"
                        break
        except Exception:
            pass

    if not needs_compression:
        job["status"] = "🎬 Pasando MKV a MP4 (Audio Latino AAC)..."
        job["progress"] = 72
        cmd = [
            ffmpeg_bin, "-y", "-i", video_path,
            "-map", "0:v:0", "-map", audio_map,
            "-c:v", "copy",
            "-c:a", "aac", "-ac", "2", "-b:a", "192k",
            "-movflags", "+faststart",
            out_mp4
        ]
        res = subprocess.run(cmd, capture_output=True, text=True)
        if res.returncode == 0 and os.path.exists(out_mp4) and os.path.getsize(out_mp4) > 5 * 1024 * 1024:
            try:
                os.remove(video_path)
            except Exception:
                pass
            return out_mp4
        return video_path

    # El archivo supera el peso ideal (>1.85 GB en peli o >750 MB en serie): comprimir automáticamente a HD Ligero (~1 GB)
    orig_str = format_size(orig_size)
    has_gpu = False
    if shutil.which("nvidia-smi"):
        try:
            g_res = subprocess.run(["nvidia-smi"], capture_output=True, timeout=5)
            has_gpu = (g_res.returncode == 0)
        except Exception:
            has_gpu = False

    if has_gpu:
        v_Args = ["-vf", "scale='min(1280,iw)':-2", "-c:v", "h264_nvenc", "-preset", "p2", "-cq", "27", "-maxrate", "1450k", "-bufsize", "2900k"]
    else:
        v_Args = ["-vf", "scale='min(1280,iw)':-2", "-c:v", "libx264", "-preset", "ultrafast", "-crf", "26", "-maxrate", "1350k", "-bufsize", "2700k", "-threads", "0"]

    cmd_comp = [
        ffmpeg_bin, "-y", "-i", video_path,
        "-map", "0:v:0", "-map", audio_map,
        *v_Args,
        "-c:a", "aac", "-ac", "2", "-b:a", "128k",
        "-movflags", "+faststart",
        "-progress", "pipe:1", "-nostats",
        out_mp4
    ]
    job["status"] = f"⚡ Comprimiendo video pesado ({orig_str} ➔ ~1 GB HD Ligero): 0%..."
    job["progress"] = 68

    proc = subprocess.Popen(cmd_comp, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
    try:
        for line in proc.stdout:
            if job.get("cancelled"):
                proc.kill()
                raise InterruptedError("Compresión cancelada por el usuario")
            if "out_time_ms=" in line and duration_sec > 0:
                try:
                    ms = int(line.strip().split("=")[1])
                    cur_s = ms / 1_000_000.0
                    pct = min(99, max(0, int((cur_s / duration_sec) * 100)))
                    job["progress"] = 68 + int((pct / 100.0) * 7)
                    job["status"] = f"⚡ Comprimiendo video pesado ({orig_str} ➔ ~1 GB HD Ligero): {pct}%..."
                except Exception:
                    pass
        proc.wait()
    except InterruptedError:
        proc.kill()
        raise

    if proc.returncode == 0 and os.path.exists(out_mp4) and os.path.getsize(out_mp4) > 5 * 1024 * 1024:
        try:
            os.remove(video_path)
        except Exception:
            pass
        return out_mp4
    return video_path


def process_job(job):
    global ACTIVE_UPLOAD_JOB
    job_dir = os.path.join(WORK_DIR, job["id"])
    os.makedirs(job_dir, exist_ok=True)
    try:
        p_info = parse_pelixplay_url(job["source_url"])
        if p_info:
            # Ruta A: Descarga desde PelixPlay (16 hilos HLS + limpieza PNG + remux MP4)
            target_video_path = download_pelixplay_to_mp4(job, p_info, job_dir)
        elif (
            is_ytdlp_url(job["source_url"])
            or job.get("vertical_to_horiz")
            or job.get("merge_clips")
            or float(job.get("trim_end_sec") or 0) > 0
        ):
            # Ruta C: Series Verticales / YouTube / Microseries (16:9 TV + sin subtítulos + corte de últimos seg + unión en 1 archivo)
            target_video_path = download_and_process_vertical_or_ytdlp(job, job_dir)
        else:
            # Ruta B: Descarga desde MediaFire / LatinoMegaHD / Directo (.rar, .part1.rar, .zip, .mkv, .mp4)
            source_urls = job.get("source_urls") or [job["source_url"]]
            total_parts = len(source_urls)
            downloaded_paths = []
            headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}

            for part_idx, src_u in enumerate(source_urls, start=1):
                if job.get("cancelled"):
                    raise InterruptedError("Descarga detenida por el usuario")

                part_prefix = f"Parte {part_idx}/{total_parts}: " if total_parts > 1 else ""
                job["status"] = f"🔍 {part_prefix}Resolviendo enlace de MediaFire..."
                job["progress"] = 2 + int(((part_idx - 1) / total_parts) * 60)

                direct_url = resolve_download_url(src_u)
                job["status"] = f"⬇️ {part_prefix}Iniciando descarga a alta velocidad..."
                dl_start = time.time()

                with requests.get(direct_url, headers=headers, stream=True, timeout=60, allow_redirects=True) as r:
                    r.raise_for_status()
                    total_bytes = int(r.headers.get("Content-Length", 0))
                    job["total_bytes"] = total_bytes

                    cd = r.headers.get("Content-Disposition", "")
                    fname = None
                    if "filename=" in cd:
                        m = re.search(r'filename\*?=["\']?(?:UTF-8\'\')?([^"\';\r\n]+)', cd, flags=re.I)
                        if m:
                            fname = unquote(m.group(1).strip())
                    if not fname:
                        parsed_path = unquote(urlparse(direct_url).path)
                        base = os.path.basename(parsed_path)
                        fname = base if (base and base.lower() != "file") else f"download_part{part_idx}.bin"

                    fname = re.sub(r'[<>:"/\\|?*]', '_', fname)
                    download_path = os.path.join(job_dir, fname)

                    downloaded = 0
                    last_update = time.time()
                    with open(download_path, "wb") as f:
                        for chunk in r.iter_content(chunk_size=1024 * 1024):
                            if job.get("cancelled"):
                                raise InterruptedError("Descarga detenida por el usuario")
                            if chunk:
                                f.write(chunk)
                                downloaded += len(chunk)
                                now = time.time()
                                if now - last_update >= 0.4:
                                    last_update = now
                                    elapsed = max(0.2, now - dl_start)
                                    speed_mb = (downloaded / (1024 * 1024)) / elapsed
                                    if total_bytes > 0:
                                        pct_dl = int((downloaded / total_bytes) * 100)
                                        rem_bytes = total_bytes - downloaded
                                        eta_s = (rem_bytes / (downloaded / elapsed)) if downloaded > 0 else 0
                                        base_prog = 5 + int(((part_idx - 1) / total_parts) * 60)
                                        part_prog = int((downloaded / total_bytes) * (60 / total_parts))
                                        job["progress"] = min(65, base_prog + part_prog)
                                        job["status"] = f"⬇️ {part_prefix}{pct_dl}% ({format_size(downloaded)} / {format_size(total_bytes)}) a {speed_mb:.1f} MB/s — {format_eta(eta_s)}"
                                    else:
                                        job["status"] = f"⬇️ {part_prefix}{format_size(downloaded)} a {speed_mb:.1f} MB/s"

                downloaded_paths.append(download_path)

            first_dl = downloaded_paths[0]
            for dp in downloaded_paths:
                if re.search(r"\.part0*1\.rar$", dp, re.I):
                    first_dl = dp
                    break

            lower_name = first_dl.lower()
            extract_dir = os.path.join(job_dir, "extracted")
            os.makedirs(extract_dir, exist_ok=True)

            is_archive = lower_name.endswith((".rar", ".zip", ".7z"))
            if not is_archive:
                with open(first_dl, "rb") as f_chk:
                    magic = f_chk.read(8)
                if magic.startswith(b"Rar!") or magic.startswith(b"PK\x03\x04") or magic.startswith(b"7z\xbc\xaf"):
                    is_archive = True

            if is_archive:
                job["status"] = "📦 Descomprimiendo RAR/ZIP y uniendo partes..."
                job["progress"] = 68
                user_pwd = (job.get("rar_password") or "").strip()
                candidate_pwds = []
                for cp in [user_pwd, "www.latinomegahd.me", "peliculas-dvdrip.com", "Ricky19", "latinomegahd.me", ""]:
                    if cp not in candidate_pwds:
                        candidate_pwds.append(cp)

                unrar_bin, sevenz_bin = find_extractor_binaries()
                extracted_ok = False
                last_err = ""

                for pwd in candidate_pwds:
                    if unrar_bin:
                        cmd_unrar = [unrar_bin, "x", "-y", "-o+"]
                        cmd_unrar.append(f"-p{pwd}" if pwd else "-p-")
                        cmd_unrar.extend([first_dl, f"{extract_dir}{os.sep}"])
                        res = subprocess.run(cmd_unrar, capture_output=True, text=True)
                        if res.returncode == 0:
                            extracted_ok = True
                            break
                        else:
                            last_err = (res.stderr or res.stdout or "").strip()

                    if not extracted_ok and sevenz_bin:
                        cmd_7z = [sevenz_bin, "x", "-y", f"-o{extract_dir}"]
                        cmd_7z.append(f"-p{pwd}" if pwd else "-p")
                        cmd_7z.append(first_dl)
                        res7 = subprocess.run(cmd_7z, capture_output=True, text=True)
                        if res7.returncode == 0:
                            extracted_ok = True
                            break
                        else:
                            last_err = (res7.stderr or res7.stdout or "").strip()

                if not extracted_ok:
                    raise RuntimeError(f"Error al descomprimir RAR/ZIP: {last_err[-180:]}")

                for dp in downloaded_paths:
                    try:
                        os.remove(dp)
                    except Exception:
                        pass

                video_candidates = []
                for root, _, files in os.walk(extract_dir):
                    for file in files:
                        ext = os.path.splitext(file)[1].lower()
                        full_p = os.path.join(root, file)
                        sz = os.path.getsize(full_p)
                        if ext in (".mp4", ".mkv", ".avi", ".mov", ".ts", ".m4v") or sz > 15 * 1024 * 1024:
                            video_candidates.append((sz, full_p))

                if not video_candidates:
                    raise RuntimeError("No se encontró ningún archivo de video adentro del RAR.")

                video_candidates.sort(key=lambda x: x[0], reverse=True)
                target_video_path = video_candidates[0][1]
            else:
                target_video_path = first_dl

            target_video_path = remux_video_to_latino_mp4(target_video_path, job_dir, job)

        if job.get("cancelled"):
            raise InterruptedError("Cancelado por el usuario")

        video_size = os.path.getsize(target_video_path)
        size_str = format_size(video_size)

        repo_id = job.get("dataset_repo") or CATALOG.get("dataset_repo") or DEFAULT_DATASET_REPO
        with STATE_LOCK:
            idx = CATALOG.get("counter", 1)
            CATALOG["counter"] = idx + 1

        if job["content_type"] == "serie":
            ep_slug = re.sub(r"[^0-9]", "", job.get("episode_name", "01")) or "01"
            camouflaged_name = f"s_{idx:04d}_e{int(ep_slug):02d}.mp4"
        else:
            camouflaged_name = f"v_{idx:04d}.mp4"

        if job.get("cancelled"):
            raise InterruptedError("Cancelado por el usuario")

        job["camouflaged_name"] = camouflaged_name
        job["video_size_bytes"] = video_size
        job["upload_start_ts"] = time.time()
        job["progress"] = 75
        job["status"] = f"☁️ Subiendo a HF ({camouflaged_name} - {size_str})..."
        ACTIVE_UPLOAD_JOB = job

        try:
            hf_api.create_repo(
                repo_id=repo_id,
                repo_type="dataset",
                private=False,
                exist_ok=True,
                token=HF_TOKEN if HF_TOKEN else None
            )
        except Exception:
            pass

        hf_api.upload_file(
            path_or_fileobj=target_video_path,
            path_in_repo=camouflaged_name,
            repo_id=repo_id,
            repo_type="dataset",
            token=HF_TOKEN if HF_TOKEN else None,
            commit_message=f"Add {camouflaged_name}"
        )
        ACTIVE_UPLOAD_JOB = None

        stream_uri = f"https://huggingface.co/datasets/{repo_id}/resolve/main/{camouflaged_name}"
        now_str = time.strftime("%d/%m/%Y %H:%M")

        poster_url = (job.get("poster_url") or "").strip()
        if not poster_url:
            tmdb_hits = search_tmdb(job["title"], job["content_type"])
            poster_url = tmdb_hits[0]["poster"] if tmdb_hits else "https://image.tmdb.org/t/p/w500/uWCL01IPrfDTjO2VTzMwZvVPzXv.jpg"

        with STATE_LOCK:
            if job["content_type"] == "serie":
                serie_title = job["title"].strip()
                season_label = (job.get("season_name") or "Temporada 1").strip()
                full_serie_name = f"{serie_title} - {season_label}" if season_label.lower() not in serie_title.lower() else serie_title
                serie_key = full_serie_name.lower().strip()

                if serie_key not in CATALOG["series"]:
                    CATALOG["series"][serie_key] = {
                        "id": str(uuid.uuid4())[:8],
                        "tipo": "serie",
                        "name": full_serie_name,
                        "ico": poster_url,
                        "temporada": [],
                        "date": now_str,
                        "repo": repo_id
                    }
                else:
                    if poster_url:
                        CATALOG["series"][serie_key]["ico"] = poster_url
                    CATALOG["series"][serie_key]["date"] = now_str

                ep_name = (job.get("episode_name") or "Capitulo 01").strip()
                ep_obj = {
                    "name": ep_name,
                    "ico": CATALOG["series"][serie_key]["ico"],
                    "uri": stream_uri,
                    "code": camouflaged_name,
                    "size_str": size_str
                }

                existing_eps = CATALOG["series"][serie_key]["temporada"]
                replaced = False
                for i, ep in enumerate(existing_eps):
                    if ep["name"].lower() == ep_name.lower():
                        existing_eps[i] = ep_obj
                        replaced = True
                        break
                if not replaced:
                    existing_eps.append(ep_obj)

                existing_eps.sort(key=lambda e: int(re.findall(r"\d+", e.get("name", ""))[0]) if re.findall(r"\d+", e.get("name", "")) else 9999)
            else:
                movie_obj = {
                    "id": str(uuid.uuid4())[:8],
                    "name": job["title"].strip(),
                    "ico": poster_url,
                    "uri": stream_uri,
                    "code": camouflaged_name,
                    "size_str": size_str,
                    "date": now_str,
                    "repo": repo_id
                }
                CATALOG["movies"].insert(0, movie_obj)

        save_catalog_to_hf()
        job["progress"] = 100
        job["status"] = f"✅ ¡Completado! Subido a Hugging Face como {camouflaged_name} ({size_str})"
        job["state"] = "done"

    except InterruptedError:
        ACTIVE_UPLOAD_JOB = None
        job["state"] = "error"
        job["status"] = "🛑 Proceso detenido por el usuario."
        job["progress"] = 0
    except Exception as e:
        ACTIVE_UPLOAD_JOB = None
        job["state"] = "error"
        job["status"] = f"❌ Error: {str(e)}"
    finally:
        ACTIVE_UPLOAD_JOB = None
        shutil.rmtree(job_dir, ignore_errors=True)


def background_worker():
    global WORKER_RUNNING
    while True:
        next_job = None
        with STATE_LOCK:
            for j in JOBS:
                if j.get("cancelled"):
                    continue
                if j["state"] == "queued":
                    j["state"] = "running"
                    next_job = j
                    break
            if not next_job:
                WORKER_RUNNING = False
                return
        process_job(next_job)


def start_worker_if_needed():
    global WORKER_RUNNING
    with STATE_LOCK:
        if not WORKER_RUNNING:
            WORKER_RUNNING = True
            t = threading.Thread(target=background_worker, daemon=True)
            t.start()


@app.route("/api/tmdb/search", methods=["GET"])
def api_tmdb_search():
    q = request.args.get("q", "")
    ctype = request.args.get("type", "movie")
    return jsonify({"success": True, "results": search_tmdb(q, ctype)})


@app.route("/api/pelixplay/meta", methods=["GET"])
def api_pelixplay_meta():
    url = request.args.get("url", "")
    if is_latinomegahd_url(url):
        try:
            lm_info = extract_latinomegahd_info(url)
            return jsonify({"success": True, "source": "latinomegahd", **lm_info})
        except Exception as e:
            return jsonify({"success": False, "message": str(e)})

    if is_ytdlp_url(url):
        try:
            yt_info = extract_ytdlp_info(url)
            return jsonify({"success": True, "source": "youtube", **yt_info})
        except Exception as e:
            return jsonify({"success": False, "message": str(e)})

    p_info = parse_pelixplay_url(url)
    if not p_info:
        return jsonify({"success": False})
    meta = get_tmdb_by_id(p_info["id"], p_info["type"])
    if meta:
        return jsonify({"success": True, "source": "pelixplay", **meta})
    return jsonify({"success": False})


@app.route("/api/jobs/enqueue", methods=["POST"])
def api_enqueue():
    data = request.get_json() or {}
    content_type = data.get("content_type", "movie")
    raw_urls = data.get("urls", "")
    title = (data.get("title") or "").strip()
    poster_url = (data.get("poster_url") or "").strip()
    rar_password = (data.get("rar_password") or "").strip()
    season_name = (data.get("season_name") or "Temporada 1").strip()
    episode_start = (data.get("episode_name") or "Capitulo 01").strip()
    dataset_repo = (data.get("dataset_repo") or CATALOG.get("dataset_repo") or DEFAULT_DATASET_REPO).strip()

    vertical_to_horiz = bool(data.get("vertical_to_horiz"))
    remove_subtitles = bool(data.get("remove_subtitles", True))
    merge_clips = bool(data.get("merge_clips"))
    trim_end_raw = str(data.get("trim_end_sec") or "").strip().replace(",", ".")
    try:
        trim_end_sec = max(0.0, float(trim_end_raw)) if trim_end_raw else 0.0
    except Exception:
        trim_end_sec = 0.0

    urls = extract_urls_from_text(raw_urls)
    if not urls:
        return jsonify({"success": False, "message": "Pegá al menos un enlace válido."}), 400

    # Si es una Playlist o video de YouTube / Serie Vertical, extraer lista de capítulos y metadatos
    if is_ytdlp_url(urls[0]):
        try:
            if len(urls) == 1:
                yt_info = extract_ytdlp_info(urls[0])
                if not title and yt_info.get("title"):
                    title = yt_info["title"]
                if not poster_url and yt_info.get("poster"):
                    poster_url = yt_info["poster"]
                if yt_info.get("video_urls") and len(yt_info["video_urls"]) > 1:
                    urls = yt_info["video_urls"]
        except Exception as e:
            print(f"Aviso leyendo YouTube meta: {e}")

    # Si es un enlace de LatinoMegaHD, extraer automáticamente los enlaces MediaFire internos y metadatos
    is_lmhd = is_latinomegahd_url(urls[0])
    lm_movie_multipart = False
    if is_lmhd:
        s_num_m = re.search(r"(\d+)", season_name)
        target_s = int(s_num_m.group(1)) if s_num_m else None
        try:
            lm_info = extract_latinomegahd_info(urls[0], target_season=target_s)
        except Exception as e:
            return jsonify({"success": False, "message": f"Error leyendo LatinoMegaHD: {e}"}), 400

        if not title and lm_info.get("title"):
            title = lm_info["title"]
        if not poster_url and lm_info.get("poster"):
            poster_url = lm_info["poster"]
        if lm_info.get("content_type") == "serie":
            content_type = "serie"
        rar_password = lm_info.get("rar_password") or "www.latinomegahd.me"

        mf_urls = lm_info.get("mediafire_urls") or []
        if not mf_urls:
            return jsonify({"success": False, "message": "Esta publicación de LatinoMegaHD no tiene enlaces de MediaFire activos."}), 400

        if content_type == "movie":
            urls = mf_urls
            lm_movie_multipart = True
        else:
            m_range_lm = re.search(r"(\d+)\s*-\s*(\d+)", episode_start)
            if m_range_lm:
                ep_from = max(1, int(m_range_lm.group(1)))
                ep_to = min(len(mf_urls), int(m_range_lm.group(2)))
                urls = mf_urls[ep_from - 1:ep_to]
                episode_start = f"Capitulo {ep_from:02d}"
            else:
                m_single = re.search(r"(\d+)", episode_start)
                ep_idx = int(m_single.group(1)) if m_single else 1
                if 1 <= ep_idx <= len(mf_urls) and len(mf_urls) > 1:
                    urls = [mf_urls[ep_idx - 1]]
                else:
                    urls = mf_urls

    # Si es PelixPlay y no pusieron título/póster, obtenerlo automáticamente por el ID de la URL
    first_p = parse_pelixplay_url(urls[0]) if urls else None
    if first_p and (not title or not poster_url):
        meta = get_tmdb_by_id(first_p["id"], first_p["type"])
        if meta:
            if not title:
                title = meta["title"]
            if not poster_url:
                poster_url = meta["poster"]
            if first_p["type"] == "tv":
                content_type = "serie"

    if not title:
        return jsonify({"success": False, "message": "Escribí el título de la Película o Serie."}), 400

    with STATE_LOCK:
        CATALOG["dataset_repo"] = dataset_repo

    if not poster_url:
        hits = search_tmdb(title, content_type)
        if hits:
            poster_url = hits[0]["poster"]

    # Si tildaron "Unir todos los capítulos en 1 solo video continuo" (ej: Microseries verticales), agrupar todo en 1 único Job
    if merge_clips and len(urls) > 1:
        ep_label = episode_start if content_type == "serie" else ""
        if content_type == "serie" and re.match(r"^\d+\s*-\s*\d+$", ep_label):
            ep_label = "Capitulo 01 (Temporada Completa)"
        job = {
            "id": str(uuid.uuid4())[:8],
            "content_type": content_type,
            "source_url": urls[0],
            "source_urls": urls,
            "title": title,
            "display_label": f"{title} ({len(urls)} caps unidos en 1 video continuo)",
            "poster_url": poster_url,
            "rar_password": rar_password,
            "season_name": season_name,
            "episode_name": ep_label or "Capitulo 01 (Temporada Completa)",
            "dataset_repo": dataset_repo,
            "vertical_to_horiz": vertical_to_horiz,
            "remove_subtitles": remove_subtitles,
            "merge_clips": True,
            "trim_end_sec": trim_end_sec,
            "state": "queued",
            "status": f"En cola ({len(urls)} capítulos para unir en 1 solo video)...",
            "progress": 0,
            "created_at": time.strftime("%H:%M:%S")
        }
        with STATE_LOCK:
            JOBS.insert(0, job)
        start_worker_if_needed()
        return jsonify({"success": True, "jobs": [job]})

    # Si es Película y pegaron varias partes (.part1.rar, .part2.rar) o viene de LatinoMegaHD, agrupar en 1 solo Job
    if content_type == "movie" and len(urls) > 1 and (lm_movie_multipart or any(".part" in u.lower() for u in urls)):
        job = {
            "id": str(uuid.uuid4())[:8],
            "content_type": "movie",
            "source_url": urls[0],
            "source_urls": urls,
            "title": title,
            "display_label": f"{title} ({len(urls)} partes RAR)",
            "poster_url": poster_url,
            "rar_password": rar_password,
            "season_name": season_name,
            "episode_name": "",
            "dataset_repo": dataset_repo,
            "vertical_to_horiz": vertical_to_horiz,
            "remove_subtitles": remove_subtitles,
            "merge_clips": merge_clips,
            "trim_end_sec": trim_end_sec,
            "state": "queued",
            "status": f"En cola ({len(urls)} partes MediaFire)...",
            "progress": 0,
            "created_at": time.strftime("%H:%M:%S")
        }
        with STATE_LOCK:
            JOBS.insert(0, job)
        start_worker_if_needed()
        return jsonify({"success": True, "jobs": [job]})

    # Soporte de rango de capítulos en serie (ej: "1-6" o "Capitulo 01-06") cuando se pega 1 link de serie de PelixPlay
    m_range = re.search(r"(\d+)\s*-\s*(\d+)", episode_start)
    if content_type == "serie" and len(urls) == 1 and first_p and m_range:
        ep_from = int(m_range.group(1))
        ep_to = int(m_range.group(2))
        if ep_to >= ep_from and (ep_to - ep_from) <= 50:
            base_u = urls[0].split("?")[0]
            s_num = re.search(r"(\d+)", season_name)
            s_val = int(s_num.group(1)) if s_num else 1
            urls = [f"{base_u}?season={s_val}&episode={ep_i}" for ep_i in range(ep_from, ep_to + 1)]
            start_num = ep_from
        else:
            start_num = 1
    else:
        start_num = 1
        m_num = re.search(r"(\d+)", episode_start)
        if m_num:
            start_num = int(m_num.group(1))

    created_jobs = []
    for idx, u in enumerate(urls):
        if content_type == "serie":
            ep_num = start_num + idx
            if len(urls) > 1:
                m_se = re.search(r"[sS]\d+[eE](\d+)|episode=(\d+)", u)
                if m_se:
                    ep_num = int(m_se.group(1) or m_se.group(2))
            ep_label = f"Capitulo {ep_num:02d}"
            display_label = f"{title} ({season_name} - {ep_label})"
        else:
            ep_label = ""
            display_label = title if len(urls) == 1 else f"{title} ({idx + 1})"

        job = {
            "id": str(uuid.uuid4())[:8],
            "content_type": content_type,
            "source_url": u,
            "source_urls": [u],
            "title": title,
            "display_label": display_label,
            "poster_url": poster_url,
            "rar_password": rar_password,
            "season_name": season_name,
            "episode_name": ep_label,
            "dataset_repo": dataset_repo,
            "vertical_to_horiz": vertical_to_horiz,
            "remove_subtitles": remove_subtitles,
            "merge_clips": merge_clips,
            "trim_end_sec": trim_end_sec,
            "state": "queued",
            "status": "En cola esperando turno...",
            "progress": 0,
            "created_at": time.strftime("%H:%M:%S")
        }
        with STATE_LOCK:
            JOBS.insert(0, job)
        created_jobs.append(job)

    start_worker_if_needed()
    return jsonify({"success": True, "jobs": created_jobs})


@app.route("/api/captcha/frame/<job_id>", methods=["GET"])
def api_captcha_frame(job_id):
    s = CAPTCHA_SESSIONS.get(job_id)
    if s:
        s.last_frame_req = time.time()
    if not s or not s.jpeg:
        return Response(b"", status=204)
    return Response(s.jpeg, mimetype="image/jpeg", headers={"Cache-Control": "no-store"})


@app.route("/api/captcha/click", methods=["POST"])
def api_captcha_click():
    d = request.get_json() or {}
    s = CAPTCHA_SESSIONS.get(str(d.get("job_id")))
    if not s:
        return jsonify({"success": False, "message": "No hay captcha activo"}), 404
    try:
        s.click(d.get("x"), d.get("y"))
    except Exception:
        return jsonify({"success": False}), 400
    return jsonify({"success": True})


@app.route("/api/state", methods=["GET"])
def api_state():
    with STATE_LOCK:
        return jsonify({
            "success": True,
            "dataset_repo": CATALOG.get("dataset_repo", DEFAULT_DATASET_REPO),
            "jobs": JOBS[:25],
            "movies": CATALOG["movies"],
            "series": list(CATALOG["series"].values())
        })


@app.route("/api/item/delete", methods=["POST"])
def api_item_delete():
    data = request.get_json() or {}
    item_type = data.get("type")
    item_id = data.get("id")
    files_to_delete = []

    with STATE_LOCK:
        if item_type == "movie":
            for m in CATALOG.get("movies", []):
                if m.get("id") == item_id:
                    code = m.get("code")
                    m_uri = m.get("uri", "")
                    repo = m.get("repo") or CATALOG.get("dataset_repo", DEFAULT_DATASET_REPO)
                    if "huggingface.co/datasets/" in m_uri and "/resolve/" in m_uri:
                        repo = m_uri.split("huggingface.co/datasets/")[1].split("/resolve/")[0]
                    if code:
                        files_to_delete.append((repo, code))
            CATALOG["movies"] = [m for m in CATALOG["movies"] if m.get("id") != item_id]
        elif item_type == "serie":
            for k, v in list(CATALOG.get("series", {}).items()):
                if v.get("id") == item_id:
                    repo = v.get("repo") or CATALOG.get("dataset_repo", DEFAULT_DATASET_REPO)
                    for ep in v.get("temporada", []):
                        code = ep.get("code")
                        ep_uri = ep.get("uri", "")
                        ep_repo = repo
                        if "huggingface.co/datasets/" in ep_uri and "/resolve/" in ep_uri:
                            ep_repo = ep_uri.split("huggingface.co/datasets/")[1].split("/resolve/")[0]
                        if code:
                            files_to_delete.append((ep_repo, code))
                    del CATALOG["series"][k]

    save_catalog_to_hf()

    # Eliminar físicamente los archivos de video .mp4 de los servidores de Hugging Face
    def _delete_files_hf():
        for repo, file_path in files_to_delete:
            try:
                hf_api.delete_file(
                    path_in_repo=file_path,
                    repo_id=repo,
                    repo_type="dataset",
                    token=HF_TOKEN if HF_TOKEN else None,
                    commit_message=f"Delete {file_path}"
                )
            except Exception as e:
                print(f"Error borrando {file_path} en HF: {e}")

    if files_to_delete:
        threading.Thread(target=_delete_files_hf, daemon=True).start()

    return jsonify({"success": True, "deleted_files": [f[1] for f in files_to_delete]})


@app.route("/api/jobs/cancel", methods=["POST"])
def api_jobs_cancel():
    data = request.get_json() or {}
    job_id = data.get("id")
    with STATE_LOCK:
        for j in JOBS:
            if j.get("id") == job_id:
                j["cancelled"] = True
                if j.get("state") == "queued":
                    j["state"] = "error"
                    j["status"] = "🛑 Cancelado antes de iniciar."
                elif j.get("state") == "running":
                    j["status"] = "🛑 Cancelando y limpiando temporales..."
                break
    return jsonify({"success": True})


@app.route("/api/jobs/cancel-all", methods=["POST"])
def api_jobs_cancel_all():
    with STATE_LOCK:
        for j in JOBS:
            j["cancelled"] = True
            if j.get("state") == "queued":
                j["state"] = "error"
                j["status"] = "🛑 Cancelado."
            elif j.get("state") == "running":
                j["status"] = "🛑 Cancelando y deteniendo..."
    return jsonify({"success": True})


@app.route("/api/jobs/clear", methods=["POST"])
def api_jobs_clear():
    global JOBS
    with STATE_LOCK:
        JOBS[:] = [j for j in JOBS if j.get("state") == "running" and not j.get("cancelled")]
    return jsonify({"success": True})


@app.route("/api/dataset/set", methods=["POST"])
def api_dataset_set():
    data = request.get_json() or {}
    repo = (data.get("dataset_repo") or "").strip()
    if not repo:
        return jsonify({"success": False, "message": "Repositorio vacío"}), 400
    with STATE_LOCK:
        CATALOG["dataset_repo"] = repo
    try:
        if HF_TOKEN:
            hf_api.create_repo(repo_id=repo, repo_type="dataset", private=False, exist_ok=True)
    except Exception as e:
        print(f"Aviso creando repo {repo}: {e}")
    save_catalog_to_hf()
    return jsonify({"success": True, "dataset_repo": repo})



FLYER_META_CACHE = {}
MARTV_HEADER_B64 = "data:image/webp;base64,UklGRggjAABXRUJQVlA4WAoAAAAQAAAAOgIAvwAAQUxQSGUCAAAFBomSJJu2Ncc+59q27/9/hm37HmOta2OvmH33w+qJiAl4IOt/63/rf+t/63/rf+t/63/rf+t/63/rf+t/63/rf+t/63/rf+t/6/+/tysOhU2lfoWSpiryR3MI9Wa6If4qFsVTJiqUGaRZhE6feR6OiMGKRxgwzzY4rJkU7TXNXpVFikloaTXL2TmxWHMJA3UmyW4TjxWbMJU0R3GRmKz5FJqNmaIyp7mk+ITUTNQM1fkC/T6hcTpmgsrCFbFZcwotU0nnKy6eE58Vq9A+Wed02aUTYrTmFdrHW53tbOWEOK2YhbaxXifbWz0lVmtuoWls1OdUD2url8RrxS7UjYymnKmwtp4lZmt+IToinU50tC5VcFsxDL6h4cGo01S3NjYfiN2aY0DHIDqc5XgLx8RwxTOkB9Cfco7Czrbk8XsG9Etfb8gZ9N7ujhDPNdtQ14se+H7ewz72kCWmK74BXT3dEN/Pejg8kP1DYrvmHCJd3Z3SEf456vhIDg5rxHfFOiDZKe1oq/sZ2dMTHEmROK+ZByQ72tAqzdHvVr04k1M5LhLvFfuAWFtrSzOaGqPfp3p1eYHzs9MKcV+7AICvpbkJjfUNdZnA193lstc3V5e4OH8g/itXAEC8sUHq6zJISTLh+6yHUrEgOcneXMtVmVxB7RYAiNW9kkA8JhGEgyJ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WYuZuxA8JdbTCy8bZbbXaDqH+1kaeN7+Bg6iBc9J8NgjjI2VsvsZhRWanITKp3OBd3wVNywXq1HfXcVt1ic6WvlsIConyrSvFqmHu5MXOVMJNZP6WFd5MNMCL1pq8H/xFGBb8+aM1pO5O1TgeiaQ2xNQ8ybHGaYzPgVezLau0ySEyIytLtZoCnWAMDnndneXdOEvRG0FnTcasBrq0UsSug4/UQNY90IRXxDLxrfKsIwGwY/KAAA="

GENRE_HOOKS_MAP = {
    "terror": ("El origen de la pesadilla", "Sobrevive a la noche más oscura", "Miedo, supervivencia y tensión"),
    "accion": ("Adrenalina sin límites", "Cada segundo cuenta para sobrevivir", "Acción, impacto y pura adrenalina"),
    "drama": ("Un destino que lo cambia todo", "Donde las emociones no tienen reglas", "Drama, intensidad y misterio"),
    "misterio": ("Nada es lo que parece", "Cada secreto tiene un precio", "Misterio, intriga y suspenso"),
    "comedia": ("Risas aseguradas de principio a fin", "Una aventura fuera de control", "Humor, diversión y grandes momentos"),
    "ciencia ficcion": ("El futuro está en juego", "Más allá de los límites humanos", "Ciencia ficción, acción y destino"),
    "romance": ("Cuando el corazón dicta las reglas", "Un amor contra todo pronóstico", "Romance, pasión y destino"),
    "thriller": ("El peligro acecha en cada sombra", "Nadie está a salvo de la verdad", "Suspenso, tensión y giros inesperados"),
    "crimen": ("En este mundo nadie es inocente", "El golpe perfecto tiene consecuencias", "Crimen, poder y venganza"),
    "animacion": ("Una aventura mágica e inolvidable", "Un mundo lleno de sorpresas", "Aventura, magia y diversión"),
}


def _clean_title_for_tmdb(raw_title):
    t = (raw_title or "").strip()
    t = re.sub(r"\s*-\s*Temporada\s*\d+.*$", "", t, flags=re.I)
    t = re.sub(r"\(\d{4}\)", "", t)
    t = re.sub(r"\[.*?\]", "", t)
    return t.strip() or raw_title


def _summarize_overview_es(overview, genres_str, is_serie=False):
    ov = re.sub(r"\s+", " ", (overview or "").strip())
    if not ov:
        g_clean = (genres_str or "DRAMA Y ACCIÓN").upper()
        if is_serie:
            return (
                f"UNA HISTORIA DE {g_clean} QUE TE ATRAPARÁ DESDE EL PRIMER CAPÍTULO. DESCUBRILA AHORA EN MAR TV.",
                f"Una atrapante serie de {g_clean.lower()} llena de giros inesperados en cada episodio."
            )
        return (
            f"UNA HISTORIA DE {g_clean} LLENA DE INTENSIDAD Y EMOCIÓN. LA AVENTURA COMIENZA AQUÍ.",
            f"Una intensa película de {g_clean.lower()} que te mantendrá al borde del asiento."
        )

    # Split into sentences
    sents = [s.strip() for s in re.split(r"(?<=[.!?])\s+", ov) if s.strip()]
    first_sent = sents[0] if sents else ov

    # Build short uppercase description for Individual Flyer bottom box (~120-150 chars max)
    if len(first_sent) <= 135:
        if len(sents) > 1 and len(first_sent) + 1 + len(sents[1]) <= 150:
            bot_desc = f"{first_sent} {sents[1]}".upper()
        else:
            bot_desc = first_sent.upper()
    else:
        # Cut cleanly at comma or word boundary around 135 chars
        cut = first_sent[:138]
        if "," in cut[70:]:
            cut = cut[:70 + cut[70:].rfind(",")] + "."
        elif " " in cut:
            cut = cut[:cut.rfind(" ")] + "..."
        bot_desc = cut.upper()

    # Build card description for Multi-Poster cards (~125 chars)
    card_desc = first_sent
    if len(card_desc) > 130:
        cut_c = card_desc[:128]
        if " " in cut_c:
            cut_c = cut_c[:cut_c.rfind(" ")] + "..."
        card_desc = cut_c

    return bot_desc, card_desc


def fetch_flyer_tmdb_meta(raw_title, content_type="movie"):
    clean_q = _clean_title_for_tmdb(raw_title)
    cache_key = f"{content_type}::{clean_q.lower()}"
    if cache_key in FLYER_META_CACHE:
        return FLYER_META_CACHE[cache_key]

    endpoint = "tv" if content_type in ("serie", "tv") else "movie"
    tmdb_id = None

    for api_key in TMDB_API_KEYS:
        try:
            for lang in ["es-MX", "es-ES", "en-US"]:
                r = requests.get(
                    f"https://api.themoviedb.org/3/search/{endpoint}",
                    params={"api_key": api_key, "query": clean_q, "language": lang},
                    timeout=6
                )
                if r.status_code == 200:
                    results = r.json().get("results", [])
                    if results:
                        tmdb_id = results[0].get("id")
                        break
            if tmdb_id:
                break
        except Exception:
            continue

    genres_list = []
    overview = ""
    tagline = ""

    if tmdb_id:
        for api_key in TMDB_API_KEYS:
            try:
                for lang in ["es-MX", "es-ES"]:
                    r_det = requests.get(
                        f"https://api.themoviedb.org/3/{endpoint}/{tmdb_id}",
                        params={"api_key": api_key, "language": lang},
                        timeout=6
                    )
                    if r_det.status_code == 200:
                        d = r_det.json()
                        if not genres_list and d.get("genres"):
                            genres_list = [g.get("name", "") for g in d.get("genres", []) if g.get("name")]
                        if not overview and d.get("overview"):
                            overview = d.get("overview", "").strip()
                        if not tagline and d.get("tagline"):
                            tagline = d.get("tagline", "").strip()
                        if overview and genres_list:
                            break
                if overview:
                    break
            except Exception:
                continue

    # Clean genre names in Spanish
    norm_genres = []
    for g in genres_list:
        gl = g.lower()
        if "action" in gl or "acción" in gl:
            norm_genres.append("Acción")
        elif "sci-fi" in gl or "ciencia" in gl:
            norm_genres.append("Ciencia Ficción")
        elif "mystery" in gl or "misterio" in gl:
            norm_genres.append("Misterio")
        elif "horror" in gl or "terror" in gl:
            norm_genres.append("Terror")
        elif "comedy" in gl or "comedia" in gl:
            norm_genres.append("Comedia")
        elif "crime" in gl or "crimen" in gl:
            norm_genres.append("Crimen")
        elif "war" in gl or "guerra" in gl or "política" in gl:
            norm_genres.append("Guerra y Acción")
        elif "Suspense" in g or "suspense" in gl or "thriller" in gl:
            norm_genres.append("Suspenso")
        else:
            norm_genres.append(g)

    # Deduplicate keeping order
    seen_g = set()
    unique_g = []
    for g in norm_genres:
        if g.lower() not in seen_g:
            seen_g.add(g.lower())
            unique_g.append(g)

    if len(unique_g) >= 2:
        conj = " E " if unique_g[1].upper().startswith("I") else " Y "
        genres_str = f"{unique_g[0].upper()}{conj}{unique_g[1].upper()}"
    elif len(unique_g) == 1:
        genres_str = unique_g[0].upper()
    else:
        genres_str = "DRAMA Y MISTERIO" if endpoint == "tv" else "ACCIÓN Y SUSPENSO"

    # Determine hooks based on primary genre or tagline
    hook1, hook2, mini_footer = ("Una historia atrapante", "Viví cada minuto al máximo", "Emoción, suspenso y adrenalina")
    g_joined = " ".join(unique_g).lower()
    for gk, h_tuple in GENRE_HOOKS_MAP.items():
        if gk in g_joined:
            hook1, hook2, mini_footer = h_tuple
            break

    if tagline and 8 <= len(tagline) <= 55:
        hook1 = tagline.rstrip(".")

    if len(unique_g) >= 2:
        mini_footer = f"{unique_g[0]}, {unique_g[1].lower()} y emoción"

    bottom_desc, card_desc = _summarize_overview_es(overview, genres_str, is_serie=(endpoint == "tv"))

    res = {
        "genres_str": genres_str,
        "pill_genre": genres_str,
        "hook1": hook1,
        "hook2": hook2,
        "mini_footer": mini_footer,
        "bottom_desc": bottom_desc,
        "card_desc": card_desc,
        "overview": overview
    }
    FLYER_META_CACHE[cache_key] = res
    return res



SENSACINE_CACHE = {}

def scrape_sensacine_upcoming(target_url="https://www.sensacine.com/peliculas/estrenos/mas-esperadas/"):
    target_url = (target_url or "https://www.sensacine.com/peliculas/estrenos/mas-esperadas/").strip()
    if target_url in SENSACINE_CACHE and (time.time() - SENSACINE_CACHE[target_url]["ts"] < 1800):
        return SENSACINE_CACHE[target_url]["items"]

    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
        "Accept-Language": "es-ES,es;q=0.9"
    }
    r = requests.get(target_url, headers=headers, timeout=15)
    soup = BeautifulSoup(r.text, "html.parser")
    is_serie_page = "/series/" in target_url.lower()

    items = []
    seen_titles = set()

    for idx, c in enumerate(soup.select(".card.entity-card")):
        title_el = c.select_one(".meta-title-link")
        if not title_el:
            continue
        title = title_el.get_text(strip=True)
        if not title or title.lower() in seen_titles:
            continue
        seen_titles.add(title.lower())

        date_el = c.select_one(".meta-body-info .date")
        date_str = date_el.get_text(strip=True) if date_el else "Próximamente"

        # Shorten date string for badges (e.g. "20 de noviembre de 2026" -> "20 NOV 2026")
        months_map = {
            "enero": "ENE", "febrero": "FEB", "marzo": "MAR", "abril": "ABR",
            "mayo": "MAY", "junio": "JUN", "julio": "JUL", "agosto": "AGO",
            "septiembre": "SEP", "setiembre": "SEP", "octubre": "OCT",
            "noviembre": "NOV", "diciembre": "DIC"
        }
        short_date = date_str.upper()
        m_d = re.search(r"(\d{1,2})\s+de\s+([a-záéíóú]+)\s+de\s+(\d{4})", date_str, flags=re.I)
        if m_d:
            day_s, mon_s, yr_s = m_d.group(1), m_d.group(2).lower(), m_d.group(3)
            short_date = f"{day_s} {months_map.get(mon_s, mon_s[:3].upper())} {yr_s}"

        info_el = c.select_one(".meta-body-info")
        genres = []
        if info_el:
            raw_info = info_el.get_text(" | ", strip=True)
            parts = [p.strip() for p in raw_info.split("|") if p.strip()]
            genres = [
                p for p in parts
                if p not in ("/", ",") and not re.search(r"\d{4}|\d+\s*h|\d+\s*min|de\s+enero|de\s+febrero|de\s+marzo|de\s+abril|de\s+mayo|de\s+junio|de\s+julio|de\s+agosto|de\s+septiembre|de\s+octubre|de\s+noviembre|de\s+diciembre", p, flags=re.I)
            ]

        if len(genres) >= 2:
            conj = " E " if genres[1].upper().startswith("I") else " Y "
            genres_str = f"{genres[0].upper()}{conj}{genres[1].upper()}"
        elif len(genres) == 1:
            genres_str = genres[0].upper()
        else:
            genres_str = "ESTRENO ESPERADO"

        syn_el = c.select_one(".synopsis .content-txt, .synopsis")
        syn = syn_el.get_text(" ", strip=True) if syn_el else ""

        img_el = c.select_one("img.thumbnail-img")
        img_url = ""
        if img_el:
            img_url = img_el.get("data-src") or img_el.get("src") or ""
            img_url = re.sub(r"/c_\d+_\d+/", "/r_800_1200/", img_url)

        if not img_url or "empty_photo" in img_url or img_url.startswith("data:"):
            tmdb_hits = search_tmdb(title, "serie" if is_serie_page else "movie")
            if tmdb_hits:
                img_url = tmdb_hits[0]["poster"]

        bot_desc, card_desc = _summarize_overview_es(syn, genres_str, is_serie=is_serie_page)

        hook1, hook2, mini_footer = ("El estreno más esperado", "Muy pronto en tu pantalla", "Emoción, impacto y adrenalina")
        for gk, h_tuple in GENRE_HOOKS_MAP.items():
            if gk in genres_str.lower():
                hook1, hook2, mini_footer = h_tuple
                break

        items.append({
            "id": f"sc_{idx}",
            "type": "serie" if is_serie_page else "movie",
            "name": title,
            "cleanTitle": title.upper(),
            "ico": img_url,
            "date": date_str,
            "short_date": short_date,
            "genres_str": genres_str,
            "synopsis": syn,
            "bottom_desc": bot_desc,
            "card_desc": card_desc,
            "hook1": hook1,
            "hook2": hook2,
            "mini_footer": mini_footer,
            "defaultBadge": f"🔥 MUY PRONTO • {short_date}",
            "shortBadge": f"PRÓXIMAMENTE • {short_date}"
        })

    SENSACINE_CACHE[target_url] = {"ts": time.time(), "items": items}
    return items


@app.route("/api/sensacine/upcoming", methods=["GET"])
def api_sensacine_upcoming():
    url = request.args.get("url", "https://www.sensacine.com/peliculas/estrenos/mas-esperadas/")
    try:
        items = scrape_sensacine_upcoming(url)
        return jsonify({"success": True, "items": items})
    except Exception as e:
        return jsonify({"success": False, "message": str(e), "items": []})


@app.route("/api/flyer/assets", methods=["GET"])
def api_flyer_assets():
    return jsonify({
        "success": True,
        "header_b64": MARTV_HEADER_B64,
        "single_bg_b64": MARTV_FULL_BG_B64
    })


@app.route("/api/flyer/meta", methods=["GET"])
def api_flyer_meta():
    title = request.args.get("title", "")
    ctype = request.args.get("type", "movie")
    meta = fetch_flyer_tmdb_meta(title, ctype)
    return jsonify({"success": True, **meta})


@app.route("/api/flyer/proxy-image", methods=["GET"])
def api_flyer_proxy_image():
    url = (request.args.get("url") or "").strip()
    if not url or not url.startswith("http"):
        return Response(status=404)
    try:
        r = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=12)
        if r.status_code == 200:
            ct = r.headers.get("Content-Type", "image/jpeg")
            return Response(r.content, mimetype=ct, headers={
                "Cache-Control": "public, max-age=86400",
                "Access-Control-Allow-Origin": "*"
            })
    except Exception:
        pass
    return Response(status=404)


HTML_TEMPLATE = r"""<!DOCTYPE html>

<html lang="es">

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Nuevo Media Server - Hugging Face CDN + PelixPlay</title>

    <link href="https://fonts.googleapis.com/css2?family=Anton&family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@400;600&family=Oswald:wght@600;700&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">

    <style>

        :root {

            --bg-main: #0b0e17;

            --bg-card: #121726;

            --bg-input: #0d111d;

            --border: #1f2942;

            --accent: #6366f1;

            --accent-hover: #4f46e5;

            --cyan: #06b6d4;

            --green: #10b981;

            --text: #f1f5f9;

            --muted: #94a3b8;

        }

        * { box-sizing: border-box; margin: 0; padding: 0; }

        body {

            font-family: 'Inter', sans-serif;

            background: var(--bg-main);

            color: var(--text);

            min-height: 100vh;

            padding: 24px 32px;

        }

        .header-bar {

            display: flex;

            justify-content: space-between;

            align-items: center;

            margin-bottom: 24px;

            flex-wrap: wrap;

            gap: 16px;

        }

        .brand-box {

            display: flex;

            align-items: center;

            gap: 14px;

        }

        .brand-logo {

            width: 44px;

            height: 44px;

            border-radius: 12px;

            background: linear-gradient(135deg, #a855f7, #ec4899);

            display: flex;

            align-items: center;

            justify-content: center;

            font-size: 20px;

            box-shadow: 0 4px 15px rgba(168, 85, 247, 0.35);

        }

        .brand-title h1 { font-size: 22px; font-weight: 800; letter-spacing: -0.3px; }

        .brand-title p { font-size: 13px; color: var(--muted); margin-top: 2px; }

        .repo-badge {

            display: flex;

            align-items: center;

            gap: 10px;

            background: var(--bg-card);

            border: 1px solid var(--border);

            padding: 8px 14px;

            border-radius: 10px;

            font-size: 13px;

        }

        .repo-badge select {

            background: var(--bg-input);

            border: 1px solid var(--border);

            color: #38bdf8;

            padding: 6px 12px;

            border-radius: 6px;

            font-family: 'JetBrains Mono', monospace;

            font-size: 12px;

            font-weight: 600;

            width: 265px;

            cursor: pointer;

        }

        .repo-badge select option {

            background: #0d111d;

            color: #38bdf8;

            font-family: 'JetBrains Mono', monospace;

            padding: 8px;

        }

        .card {

            background: var(--bg-card);

            border: 1px solid var(--border);

            border-radius: 14px;

            padding: 24px;

            margin-bottom: 24px;

            box-shadow: 0 10px 30px rgba(0,0,0,0.25);

        }

        .card-header {

            display: flex;

            justify-content: space-between;

            align-items: center;

            margin-bottom: 20px;

            flex-wrap: wrap;

            gap: 12px;

        }

        .card-title {

            font-size: 17px;

            font-weight: 700;

            display: flex;

            align-items: center;

            gap: 10px;

        }

        .card-sub {

            font-size: 12px;

            color: var(--muted);

            margin-top: 3px;

        }

        .form-label {

            display: block;

            font-size: 12px;

            font-weight: 600;

            color: #cbd5e1;

            margin-bottom: 7px;

        }

        .form-control, select, textarea {

            width: 100%;

            background: var(--bg-input);

            border: 1px solid var(--border);

            color: var(--text);

            padding: 11px 14px;

            border-radius: 8px;

            font-size: 13.5px;

            font-family: inherit;

            outline: none;

            transition: border-color 0.2s;

        }

        .form-control:focus, select:focus, textarea:focus {

            border-color: var(--accent);

        }

        textarea {

            resize: vertical;

            min-height: 76px;

            font-family: 'JetBrains Mono', monospace;

            font-size: 12.5px;

        }

        .grid-row {

            display: grid;

            grid-template-columns: 2fr 1.2fr 1fr 1fr;

            gap: 14px;

            margin-top: 16px;

            align-items: end;

        }

        @media (max-width: 960px) {

            .grid-row { grid-template-columns: 1fr 1fr; }

        }

        .btn {

            border: none;

            cursor: pointer;

            padding: 11px 18px;

            border-radius: 8px;

            font-weight: 600;

            font-size: 13.5px;

            display: inline-flex;

            align-items: center;

            justify-content: center;

            gap: 8px;

            color: #fff;

            transition: all 0.15s;

        }

        .btn-tmdb { background: #0284c7; }

        .btn-tmdb:hover { background: #0369a1; }

        .btn-primary {

            background: linear-gradient(135deg, #6366f1, #4f46e5);

            box-shadow: 0 4px 14px rgba(99, 102, 241, 0.35);

        }

        .btn-primary:hover { transform: translateY(-1px); }

        .btn-green { background: #059669; }

        .btn-green:hover { background: #047857; }

        .btn-sm { padding: 7px 12px; font-size: 12px; border-radius: 6px; }

        .title-group {

            display: flex;

            gap: 8px;

        }

        .selected-poster-bar {

            margin-top: 14px;

            display: none;

            align-items: center;

            gap: 14px;

            background: rgba(15, 23, 42, 0.7);

            padding: 10px 14px;

            border-radius: 10px;

            border: 1px solid var(--border);

        }

        .selected-poster-bar img {

            width: 44px;

            height: 64px;

            object-fit: cover;

            border-radius: 6px;

        }

        .tmdb-results-box {

            display: none;

            margin-top: 14px;

            background: var(--bg-input);

            border: 1px solid var(--border);

            border-radius: 10px;

            padding: 14px;

        }

        .tmdb-grid {

            display: flex;

            gap: 12px;

            overflow-x: auto;

            padding-bottom: 6px;

        }

        .tmdb-card {

            width: 110px;

            flex-shrink: 0;

            cursor: pointer;

            border-radius: 8px;

            overflow: hidden;

            border: 2px solid transparent;

            background: #161f33;

            transition: transform 0.15s, border-color 0.15s;

        }

        .tmdb-card:hover {

            transform: scale(1.04);

            border-color: #38bdf8;

        }

        .tmdb-card img {

            width: 100%;

            height: 155px;

            object-fit: cover;

            display: block;

        }

        .tmdb-card-title {

            font-size: 11px;

            padding: 6px;

            text-align: center;

            white-space: nowrap;

            overflow: hidden;

            text-overflow: ellipsis;

        }

        .job-item {

            background: var(--bg-input);

            border: 1px solid var(--border);

            border-radius: 9px;

            padding: 12px 16px;

            margin-bottom: 10px;

        }

        .job-top {

            display: flex;

            justify-content: space-between;

            font-size: 13px;

            font-weight: 600;

            margin-bottom: 6px;

        }

        .progress-track {

            width: 100%;

            height: 7px;

            background: #1e293b;

            border-radius: 99px;

            overflow: hidden;

        }

        .progress-fill {

            height: 100%;

            background: linear-gradient(90deg, #6366f1, #06b6d4);

            transition: width 0.3s;

        }

        table {

            width: 100%;

            border-collapse: collapse;

            margin-top: 12px;

        }

        th {

            text-align: left;

            font-size: 12px;

            color: var(--muted);

            padding: 12px;

            border-bottom: 1px solid var(--border);

        }

        td {

            padding: 12px;

            border-bottom: 1px solid rgba(31, 41, 66, 0.6);

            font-size: 13.5px;

            vertical-align: middle;

        }

        .poster-thumb {

            width: 44px;

            height: 64px;

            object-fit: cover;

            border-radius: 6px;

            border: 1px solid var(--border);

        }

        .badge-movie {

            background: rgba(99, 102, 241, 0.2);

            color: #818cf8;

            padding: 3px 8px;

            border-radius: 5px;

            font-size: 11px;

            font-weight: 700;

        }

        .badge-serie {

            background: rgba(16, 185, 129, 0.2);

            color: #34d399;

            padding: 3px 8px;

            border-radius: 5px;

            font-size: 11px;

            font-weight: 700;

        }

        .code-pill {

            font-family: 'JetBrains Mono', monospace;

            font-size: 11.5px;

            color: #38bdf8;

            background: rgba(56, 189, 248, 0.1);

            padding: 4px 8px;

            border-radius: 5px;

        }

        .modal-backdrop {

            display: none;

            position: fixed;

            inset: 0;

            background: rgba(0, 0, 0, 0.75);

            z-index: 999;

            align-items: center;

            justify-content: center;

            padding: 20px;

        }

        .modal-box {

            background: var(--bg-card);

            border: 1px solid var(--border);

            border-radius: 14px;

            max-width: 720px;

            width: 100%;

            padding: 22px;

        }

        .modal-pre {

            background: #070a12;

            border: 1px solid var(--border);

            padding: 14px;

            border-radius: 8px;

            color: #a5f3fc;

            font-family: 'JetBrains Mono', monospace;

            font-size: 12px;

            max-height: 400px;

            overflow-y: auto;

            white-space: pre-wrap;

            margin: 14px 0;

        }

        .filter-pills {

            display: flex;

            gap: 8px;

        }

        .pill-btn {

            background: var(--bg-input);

            border: 1px solid var(--border);

            color: var(--muted);

            padding: 7px 14px;

            border-radius: 20px;

            font-size: 12.5px;

            font-weight: 600;

            cursor: pointer;

        }

        .pill-btn.active {

            background: var(--accent);

            color: #fff;

            border-color: var(--accent);

        }

    </style>

</head>

<body>



    <div class="header-bar">

        <div class="brand-box">

            <div class="brand-logo"><i class="fa-solid fa-play"></i></div>

            <div class="brand-title">

                <h1>Gestor de Descargas & Media Server <span style="font-size:12px; background:#10b981; color:#042f2e; padding:3px 8px; border-radius:6px; vertical-align:middle;">HF CDN + PELIXPLAY + LATINOMEGAHD</span></h1>

                <p>Soporta <strong>latinomegahd.me</strong> (1080p sin acortadores), <strong>MediaFire</strong> (RAR/multiparte) y <strong>pelixplay.app</strong> en Audio Latino HD.</p>

            </div>

        </div>



        <div class="repo-badge">

            <span><i class="fa-solid fa-database" style="color:#a855f7;"></i> Dataset Activo:</span>

            <select id="datasetRepoInput" onchange="onDatasetRepoChanged()" title="Seleccioná el Dataset donde se guardarán las próximas películas/series">

                <option value="visionhdstream/data-vision-01" {% if dataset_repo == 'visionhdstream/data-vision-01' %}selected{% endif %}>visionhdstream/data-vision-01</option>

                <option value="visionhdstream/data-vision-02" {% if dataset_repo == 'visionhdstream/data-vision-02' %}selected{% endif %}>visionhdstream/data-vision-02</option>

                <option value="visionhdstream/data-vision-03" {% if dataset_repo == 'visionhdstream/data-vision-03' %}selected{% endif %}>visionhdstream/data-vision-03</option>

                <option value="visionhdstream/data-vision-04" {% if dataset_repo == 'visionhdstream/data-vision-04' %}selected{% endif %}>visionhdstream/data-vision-04</option>

                <option value="visionhdstream/data-vision-05" {% if dataset_repo == 'visionhdstream/data-vision-05' %}selected{% endif %}>visionhdstream/data-vision-05</option>

            </select>

            <span id="repoSavedBadge" style="display:none; color:#34d399; font-size:11.5px; font-weight:700;">✓ Listo</span>

        </div>

    </div>



    <!-- DESCARGADOR & EXTRACTOR -->

    <div class="card">

        <div class="card-header">

            <div>

                <div class="card-title"><i class="fa-solid fa-cloud-arrow-down" style="color:#818cf8;"></i> Descargador LatinoMegaHD / MediaFire / PelixPlay en Segundo Plano</div>

                <div class="card-sub">Pegá el link de <strong>latinomegahd.me</strong> (extrae MediaFire sin publicidad), de <strong>MediaFire</strong> (.rar/.mp4) o de <strong>pelixplay.app/web/...</strong> y se sube como .mp4 camuflado a Hugging Face.</div>

            </div>

            <div style="display:flex; align-items:center; gap:10px;">

                <span style="font-size:12.5px; color:var(--muted);"><i class="fa-solid fa-layer-group"></i> Tipo de Contenido:</span>

                <select id="contentType" style="width:170px; font-weight:700;" onchange="toggleTypeFields()">

                    <option value="movie">🎬 Película</option>

                    <option value="serie">📺 Serie</option>

                </select>

            </div>

        </div>



        <div>

            <label class="form-label"><i class="fa-solid fa-link"></i> Enlace(s) de Descarga (<span style="color:#38bdf8;">latinomegahd.me/...</span>, <span style="color:#f43f5e;">pelixplay.app/web/...</span>, MediaFire o Directo RAR/MP4)</label>

            <textarea id="downloadUrls" oninput="onUrlInputChanged()" placeholder="Pegá acá el link de LatinoMegaHD (ej: https://www.latinomegahd.me/pelicula/...), de PelixPlay o de MediaFire..."></textarea>

        </div>



        <div class="grid-row">

            <div>

                <label class="form-label" id="titleLabel"><i class="fa-solid fa-film"></i> Título del Contenido <span id="autoFillBadge" style="display:none; color:#34d399; font-size:11px;">(✨ Autocompletado de PelixPlay)</span></label>

                <div class="title-group">

                    <input type="text" id="contentTitle" class="form-control" placeholder="Ej: El amor de tu vida o Cautiva">

                    <button type="button" class="btn btn-tmdb" onclick="buscarTMDB()"><i class="fa-solid fa-magnifying-glass"></i> TMDB</button>

                </div>

            </div>



            <div>

                <label class="form-label"><i class="fa-solid fa-key"></i> Clave RAR/ZIP (si es RAR)</label>

                <input type="text" id="rarPassword" class="form-control" value="peliculas-dvdrip.com">

            </div>



            <div id="seasonBox" style="display:none;">

                <label class="form-label"><i class="fa-solid fa-folder-tree"></i> Temporada</label>

                <input type="text" id="seasonName" class="form-control" value="Temporada 1">

            </div>



            <div id="episodeBox" style="display:none;">

                <label class="form-label"><i class="fa-solid fa-list-ol"></i> Capítulo (o rango ej: 1-6)</label>

                <input type="text" id="episodeName" class="form-control" value="Capitulo 01">

            </div>



            <div id="submitBox" style="grid-column: span 2; display:flex; justify-content:flex-end;">

                <button type="button" class="btn btn-primary" style="width:100%; max-width:340px;" onclick="iniciarDescarga()">

                    <i class="fa-solid fa-cloud-arrow-up"></i> Iniciar Descarga en Segundo Plano

                </button>

            </div>

        </div>



        <!-- Barra Especial para Series Verticales / Microseries / YouTube -->

        <div style="margin-top:16px; background:rgba(15, 23, 42, 0.75); border:1px solid #334155; border-radius:10px; padding:12px 16px; display:flex; flex-wrap:wrap; align-items:center; justify-content:space-between; gap:14px;">

            <div style="display:flex; flex-wrap:wrap; align-items:center; gap:18px;">

                <span style="font-size:12.5px; font-weight:700; color:#a855f7;"><i class="fa-solid fa-mobile-screen-button"></i> Series Verticales / Microseries:</span>

                <label style="display:flex; align-items:center; gap:7px; font-size:12.5px; cursor:pointer;">

                    <input type="checkbox" id="verticalToHoriz" style="width:16px; height:16px; accent-color:#a855f7;">

                    <span>Convertir Vertical a Horizontal TV (16:9)</span>

                </label>

                <label style="display:flex; align-items:center; gap:7px; font-size:12.5px; cursor:pointer;">

                    <input type="checkbox" id="removeSubtitles" checked style="width:16px; height:16px; accent-color:#a855f7;">

                    <span>Quitar Subtítulos inferiores</span>

                </label>

                <label style="display:flex; align-items:center; gap:7px; font-size:12.5px; cursor:pointer;">

                    <input type="checkbox" id="mergeClips" style="width:16px; height:16px; accent-color:#10b981;">

                    <span style="color:#34d399; font-weight:600;">Unir todos los capítulos en 1 solo video continuo</span>

                </label>

            </div>

            <div style="display:flex; align-items:center; gap:8px;">

                <label for="trimEndSec" style="font-size:12px; color:#cbd5e1; white-space:nowrap;"><i class="fa-solid fa-scissors" style="color:#f43f5e;"></i> Cortar últimos seg. (Opcional):</label>

                <input type="number" id="trimEndSec" class="form-control" style="width:130px; padding:6px 10px; font-size:12.5px;" min="0" max="120" step="0.5" placeholder="Vacío = 0">

            </div>

        </div>



        <!-- Barra de Póster Seleccionado -->

        <div class="selected-poster-bar" id="selectedPosterBar">

            <img id="posterPreviewImg" src="" alt="Poster">

            <div style="flex:1;">

                <div style="font-size:12px; color:var(--muted);">Póster TMDB seleccionado (podés editar el link si querés):</div>

                <input type="text" id="posterUrlInput" class="form-control" style="margin-top:4px; padding:7px 10px; font-size:12px;">

            </div>

        </div>



        <!-- Resultados de búsqueda TMDB -->

        <div class="tmdb-results-box" id="tmdbResultsBox">

            <div style="display:flex; justify-content:space-between; margin-bottom:8px; font-size:12px; color:var(--muted);">

                <span>Hacé clic en la portada correcta para seleccionarla:</span>

                <span style="cursor:pointer; color:#f87171;" onclick="document.getElementById('tmdbResultsBox').style.display='none'">✖ Cerrar</span>

            </div>

            <div class="tmdb-grid" id="tmdbGrid"></div>

        </div>

    </div>



    <!-- COLA DE DESCARGAS EN CURSO -->

    <div class="card" id="jobsCard" style="display:none;">

        <div class="card-header" style="margin-bottom:12px;">

            <div class="card-title"><i class="fa-solid fa-bolt" style="color:#facc15;"></i> Procesos en Segundo Plano</div>

            <div style="display:flex; gap:8px;">

                <button type="button" class="btn btn-sm" style="background:#dc2626;" onclick="cancelAllJobs()">

                    <i class="fa-solid fa-circle-stop"></i> 🛑 Detener Todo

                </button>

                <button type="button" class="btn btn-sm" style="background:#475569;" onclick="clearCompletedJobs()">

                    <i class="fa-solid fa-broom"></i> Limpiar Lista

                </button>

            </div>

        </div>

        <div id="jobsContainer"></div>

    </div>



    <!-- BIBLIOTECA & GENERADOR JSON -->

    <div class="card">

        <div class="card-header">

            <div>

                <div class="card-title"><i class="fa-solid fa-box-archive" style="color:#38bdf8;"></i> Biblioteca de Contenidos & Generador JSON</div>

                <div class="card-sub">Archivos alojados y camuflados en Hugging Face CDN, listos para copiar el JSON exacto para tu app.</div>

            </div>

            <div style="display:flex; flex-wrap:wrap; align-items:center; gap:10px;">

                <button class="btn btn-sm" style="background:linear-gradient(135deg, #10b981, #047857); box-shadow:0 3px 12px rgba(16,185,129,0.3);" onclick="openMultiFlyerModal('movie')">

                    <i class="fa-solid fa-wand-magic-sparkles"></i> 🔥 Póster Últimas Pelis

                </button>

                <button class="btn btn-sm" style="background:linear-gradient(135deg, #a855f7, #6366f1); box-shadow:0 3px 12px rgba(168,85,247,0.3);" onclick="openMultiFlyerModal('serie')">

                    <i class="fa-solid fa-layer-group"></i> 🔥 Póster Últimas Series

                </button>

                <button class="btn btn-sm" style="background:linear-gradient(135deg, #f59e0b, #d97706); color:#fff; box-shadow:0 3px 12px rgba(245,158,11,0.35);" onclick="openSensacineModal()">

                    <i class="fa-solid fa-wand-sparkles"></i> 🔮 Lo Que Se Viene (SensaCine)

                </button>

                <div class="filter-pills">

                    <button class="pill-btn active" id="tabAll" onclick="setFilter('all')">Todas (<span id="countAll">0</span>)</button>

                    <button class="pill-btn" id="tabMovies" onclick="setFilter('movie')">🎬 Películas (<span id="countMovies">0</span>)</button>

                    <button class="pill-btn" id="tabSeries" onclick="setFilter('serie')">📺 Series (<span id="countSeries">0</span>)</button>

                </div>

            </div>

        </div>



        <table>

            <thead>

                <tr>

                    <th>Póster & Tipo</th>

                    <th>Título en tu App</th>

                    <th>Archivo Camuflado (HF)</th>

                    <th>Detalles / Capítulos</th>

                    <th>Fecha</th>

                    <th style="text-align:right;">Acciones & JSON</th>

                </tr>

            </thead>

            <tbody id="libraryBody">

                <tr><td colspan="6" style="text-align:center; color:var(--muted); padding:28px;">Cargando biblioteca...</td></tr>

            </tbody>

        </table>

    </div>



    <!-- MODAL PARA VER/COPIAR JSON -->

    <div class="modal-backdrop" id="jsonModal">

        <div class="modal-box">

            <div style="display:flex; justify-content:space-between; align-items:center;">

                <h3 style="font-size:16px;"><i class="fa-solid fa-code" style="color:#38bdf8;"></i> JSON Generado (Formato Exacto de tu App)</h3>

                <button class="btn btn-sm" style="background:#334155;" onclick="closeJsonModal()">✖</button>

            </div>

            <pre class="modal-pre" id="jsonModalText"></pre>

            <div style="display:flex; justify-content:flex-end; gap:10px;">

                <button class="btn btn-green" onclick="copyModalJson()"><i class="fa-solid fa-copy"></i> Copiar JSON al Portapapeles</button>

            </div>

        </div>

    </div>



    <!-- MODAL ESTUDIO DE FLYERS & PÓSTERS MAR TV -->

    <div class="modal-backdrop" id="flyerModal">

        <div class="modal-box" style="max-width:1060px; max-height:94vh; overflow-y:auto; padding:20px 24px;">

            <div style="display:flex; justify-content:space-between; align-items:center; flex-wrap:wrap; gap:12px; border-bottom:1px solid var(--border); padding-bottom:14px; margin-bottom:16px;">

                <div style="display:flex; align-items:center; gap:12px; flex-wrap:wrap;">

                    <h3 style="font-size:17px; display:flex; align-items:center; gap:8px;">

                        <i class="fa-solid fa-wand-magic-sparkles" style="color:#10b981;"></i> Generador Automático de Flyers MAR TV

                    </h3>

                    <div style="display:flex; gap:6px; background:#090d16; padding:4px; border-radius:9px; border:1px solid var(--border);">

                        <button type="button" id="btnModeSingle" class="btn btn-sm" style="background:#10b981; color:#042f2e; font-weight:800;" onclick="switchFlyerMode('single')">

                            🎨 Flyer Individual

                        </button>

                        <button type="button" id="btnModeMulti" class="btn btn-sm" style="background:transparent; color:#94a3b8;" onclick="switchFlyerMode('multi')">

                            🔥 Póster Últimas Agregadas

                        </button>

                        <button type="button" id="btnModeUpcoming" class="btn btn-sm" style="background:transparent; color:#fbbf24;" onclick="openSensacineModal()">

                            🔮 Lo Que Se Viene (SensaCine)

                        </button>

                    </div>

                </div>

                <button class="btn btn-sm" style="background:#334155;" onclick="closeFlyerModal()">✖ Cerrar</button>

            </div>



            <div style="display:grid; grid-template-columns: 350px 1fr; gap:22px; align-items:start;">

                <!-- COLUMNA IZQUIERDA: VISTA PREVIA EN VIVO + DESCARGAR/COPIAR -->

                <div style="display:flex; flex-direction:column; align-items:center; background:#080b12; border:1px solid var(--border); border-radius:12px; padding:14px;">

                    <div style="position:relative; width:100%; max-width:320px; aspect-ratio: 571 / 1024; border-radius:10px; overflow:hidden; box-shadow:0 8px 28px rgba(0,0,0,0.65); border:1px solid #1e293b;">

                        <canvas id="flyerCanvas" width="856" height="1536" style="width:100%; height:100%; display:block;"></canvas>

                    </div>

                    <div id="flyerLoadingBadge" style="display:none; margin-top:8px; font-size:12px; color:#38bdf8; font-weight:600;">

                        <i class="fa-solid fa-spinner fa-spin"></i> Buscando sinopsis y géneros en TMDB...

                    </div>

                    <div style="display:flex; flex-direction:column; width:100%; gap:8px; margin-top:12px;">

                        <button type="button" class="btn btn-green" style="width:100%; font-weight:700;" onclick="downloadFlyerImage()">

                            <i class="fa-solid fa-download"></i> ⬇️ Descargar Póster HD (.jpg)

                        </button>

                        <button type="button" class="btn btn-primary" style="width:100%; font-weight:700;" onclick="copyFlyerImageToClipboard()">

                            <i class="fa-solid fa-copy"></i> 📋 Copiar Imagen (Pegar con Ctrl+V)

                        </button>

                        <div id="flyerCopyToast" style="display:none; text-align:center; font-size:12px; color:#34d399; font-weight:700; margin-top:2px;">

                            ✓ ¡Imagen copiada al portapapeles!

                        </div>

                    </div>

                </div>



                <!-- COLUMNA DERECHA: CONTROLES AUTOMÁTICOS Y PERSONALIZACIÓN -->

                <div>

                    <!-- CONTROLES MODO INDIVIDUAL -->

                    <div id="singleFlyerControls">

                        <div style="background:rgba(16,185,129,0.1); border:1px solid rgba(16,185,129,0.3); border-radius:9px; padding:10px 14px; margin-bottom:14px; font-size:12.5px; color:#a7f3d0;">

                            <i class="fa-solid fa-bolt"></i> <strong>¡Todo completado automáticamente!</strong> El póster, los capítulos y la descripción se armaron solos. Si querés cambiar alguna frase, editá abajo y la imagen se actualiza en vivo.

                        </div>



                        <div style="display:grid; grid-template-columns:1fr 1fr; gap:12px;">

                            <div>

                                <label class="form-label">Seleccionar Película / Serie de tu Biblioteca</label>

                                <select id="singleItemSelect" class="form-control" onchange="onSingleItemSelectChanged()"></select>

                            </div>

                            <div>

                                <label class="form-label">Etiqueta Superior (Tipo y Género)</label>

                                <input type="text" id="sfTopTag" class="form-control" oninput="renderFlyerCanvas()" placeholder="Ej: PELÍCULA • TERROR Y ACCIÓN">

                            </div>

                            <div>

                                <label class="form-label">Frase Gancho 1 (Arriba Izquierda)</label>

                                <input type="text" id="sfHook1" class="form-control" oninput="renderFlyerCanvas()">

                            </div>

                            <div>

                                <label class="form-label">Frase Gancho 2 (Debajo Gancho 1)</label>

                                <input type="text" id="sfHook2" class="form-control" oninput="renderFlyerCanvas()">

                            </div>

                            <div>

                                <label class="form-label">Título Caja Neón (DISPONIBLE o PRÓXIMAMENTE)</label>

                                <input type="text" id="sfHudTop" class="form-control" value="DISPONIBLE" oninput="renderFlyerCanvas()">

                            </div>

                            <div>

                                <label class="form-label">Subtítulo Caja Neón (Ej: PELÍCULA COMPLETA / ESTRENO...)</label>

                                <input type="text" id="sfHudSub" class="form-control" oninput="renderFlyerCanvas()">

                            </div>

                            <div>

                                <label class="form-label" style="color:#34d399;">Texto Principal Caja Neón (Ej: YA DISPONIBLE / T1 • CAP. 1-10)</label>

                                <input type="text" id="sfHudMain" class="form-control" oninput="renderFlyerCanvas()">

                            </div>

                            <div>

                                <label class="form-label">Píldora de Género</label>

                                <input type="text" id="sfPillGenre" class="form-control" oninput="renderFlyerCanvas()">

                            </div>

                            <div>

                                <label class="form-label">Sello Candado & Pie Izquierdo</label>

                                <input type="text" id="sfMiniFooter" class="form-control" oninput="renderFlyerCanvas()">

                            </div>

                            <div>

                                <label class="form-label">Título Gigante Inferior</label>

                                <input type="text" id="sfBottomTitle" class="form-control" oninput="renderFlyerCanvas()">

                            </div>

                            <div>

                                <label class="form-label" style="color:#34d399;">Subtítulo Verde Inferior (Capítulos / Estado)</label>

                                <input type="text" id="sfBottomSub" class="form-control" oninput="renderFlyerCanvas()">

                            </div>

                        </div>



                        <div style="margin-top:12px;">

                            <label class="form-label" style="color:#fde68a;">Breve Descripción Inferior (en Dorado - se ajusta sola en 2 o 3 líneas)</label>

                            <textarea id="sfBottomDesc" class="form-control" style="min-height:66px; font-family:inherit;" oninput="renderFlyerCanvas()"></textarea>

                        </div>

                    </div>



                    <!-- CONTROLES MODO MÚLTIPLE ("ÚLTIMAS AGREGADAS") -->

                    <div id="multiFlyerControls" style="display:none;">

                        <div id="multiLibraryBanner" style="background:rgba(168,85,247,0.12); border:1px solid rgba(168,85,247,0.35); border-radius:9px; padding:10px 14px; margin-bottom:14px; font-size:12.5px; color:#e9d5ff;">

                            <i class="fa-solid fa-layer-group"></i> <strong>Póster de Últimas Agregadas:</strong> Ideal para cuando subís varias películas o series en el día. Elegí cuántas mostrar o tildá cuáles incluir.

                        </div>



                        <!-- BARRA ESPECIAL SENSACINE ("LO QUE SE VIENE") -->

                        <div id="sensacineBar" style="display:none; background:rgba(245,158,11,0.12); border:1px solid rgba(245,158,11,0.4); border-radius:9px; padding:12px 14px; margin-bottom:14px;">

                            <div style="font-size:12.5px; color:#fde68a; margin-bottom:8px;">

                                <i class="fa-solid fa-wand-sparkles"></i> <strong>🔮 Modo "Lo Que Se Viene" (Conectado en vivo a SensaCine):</strong> Tildá los estrenos que quieras promocionar en tus Estados o tocá <strong>"🎨 Flyer Individual"</strong> en cualquiera de la lista.

                            </div>

                            <div style="display:flex; flex-wrap:wrap; gap:6px; margin-bottom:8px;">

                                <button type="button" class="btn btn-sm" style="background:#b45309;" onclick="loadSensacineUrl('https://www.sensacine.com/peliculas/estrenos/mas-esperadas/')">🔥 Más Esperadas (Pág 1)</button>

                                <button type="button" class="btn btn-sm" style="background:#1e293b;" onclick="loadSensacineUrl('https://www.sensacine.com/peliculas/estrenos/mas-esperadas/?page=2')">🔥 Más Esperadas (Pág 2)</button>

                                <button type="button" class="btn btn-sm" style="background:#1e293b;" onclick="loadSensacineUrl('https://www.sensacine.com/peliculas/agenda/')">📅 Próximos Estrenos Cine</button>

                                <button type="button" class="btn btn-sm" style="background:#1e293b;" onclick="loadSensacineUrl('https://www.sensacine.com/series/mas-esperadas/')">📺 Series Más Esperadas</button>

                            </div>

                            <div style="display:flex; gap:8px;">

                                <input type="text" id="sensacineCustomUrl" class="form-control" style="padding:6px 10px; font-size:12px;" value="https://www.sensacine.com/peliculas/estrenos/mas-esperadas/" placeholder="Pegá cualquier link de SensaCine...">

                                <button type="button" class="btn btn-sm" style="background:#d97706; white-space:nowrap;" onclick="loadSensacineUrl(document.getElementById('sensacineCustomUrl').value)">🔄 Cargar Lista</button>

                            </div>

                        </div>



                        <div id="libraryQuickFilterBar" style="display:flex; flex-wrap:wrap; gap:8px; margin-bottom:12px; align-items:center;">

                            <span style="font-size:12px; color:var(--muted); font-weight:600;">Filtro rápido:</span>

                            <button type="button" class="btn btn-sm" style="background:#1e293b;" onclick="selectLastItems('movie', 3)">🎬 Últimas 3 Pelis</button>

                            <button type="button" class="btn btn-sm" style="background:#1e293b;" onclick="selectLastItems('movie', 4)">🎬 Últimas 4 Pelis</button>

                            <button type="button" class="btn btn-sm" style="background:#1e293b;" onclick="selectLastItems('serie', 3)">📺 Últimas 3 Series</button>

                            <button type="button" class="btn btn-sm" style="background:#1e293b;" onclick="selectLastItems('serie', 4)">📺 Últimas 4 Series</button>

                            <button type="button" class="btn btn-sm" style="background:#1e293b;" onclick="selectLastItems('all', 6)">🔥 Últimos 6 Estrenos</button>

                        </div>



                        <div style="display:grid; grid-template-columns:1fr 1fr 1fr; gap:10px; margin-bottom:12px;">

                            <div>

                                <label class="form-label">Título del Póster</label>

                                <input type="text" id="mfHeaderTitle" class="form-control" value="NUEVOS ESTRENOS EN MAR TV" oninput="renderFlyerCanvas()">

                            </div>

                            <div>

                                <label class="form-label" style="color:#34d399;">Subtítulo Verde Superior</label>

                                <input type="text" id="mfHeaderSub" class="form-control" value="RECIÉN AGREGADOS • YA DISPONIBLES" oninput="renderFlyerCanvas()">

                            </div>

                            <div>

                                <label class="form-label">Estilo de Diseño</label>

                                <select id="mfLayoutStyle" class="form-control" onchange="renderFlyerCanvas()">

                                    <option value="cards">🗂️ Tarjetas con Sinopsis (Ideal 2 a 4)</option>

                                    <option value="grid">🖼️ Cartelera Pósters Grandes (Ideal 3 a 6)</option>

                                </select>

                            </div>

                        </div>



                        <label class="form-label">Contenidos incluidos en el Póster (podés tildar/destildar y editar los capítulos o resumen de cada uno):</label>

                        <div id="multiItemsChecklist" style="max-height:360px; overflow-y:auto; background:#090d16; border:1px solid var(--border); border-radius:10px; padding:10px; display:flex; flex-direction:column; gap:8px;">

                        </div>

                    </div>

                </div>

            </div>

        </div>

    </div>



    <script>

        let currentFilter = 'all';

        let stateData = { movies: [], series: [], jobs: [] };

        let lastDetectedPelixUrl = '';



        async function onDatasetRepoChanged() {

            const dataset_repo = document.getElementById('datasetRepoInput').value;

            const badge = document.getElementById('repoSavedBadge');

            try {

                const res = await fetch('/api/dataset/set', {

                    method: 'POST',

                    headers: {'Content-Type': 'application/json'},

                    body: JSON.stringify({ dataset_repo })

                });

                const data = await res.json();

                if (data.success && badge) {

                    badge.style.display = 'inline';

                    setTimeout(() => { badge.style.display = 'none'; }, 2500);

                }

            } catch (e) {}

        }



        function toggleTypeFields() {

            const type = document.getElementById('contentType').value;

            const seasonBox = document.getElementById('seasonBox');

            const epBox = document.getElementById('episodeBox');

            const submitBox = document.getElementById('submitBox');

            if (type === 'serie') {

                seasonBox.style.display = 'block';

                epBox.style.display = 'block';

                submitBox.style.gridColumn = 'span 4';

            } else {

                seasonBox.style.display = 'none';

                epBox.style.display = 'none';

                submitBox.style.gridColumn = 'span 2';

            }

        }



        async function onUrlInputChanged() {

            const val = document.getElementById('downloadUrls').value.trim();

            const isYt = val.includes('youtube.com/') || val.includes('youtu.be/') || val.includes('tiktok.com/');

            if ((val.includes('pelixplay.app') || val.includes('latinomegahd.') || isYt) && val !== lastDetectedPelixUrl) {

                lastDetectedPelixUrl = val;

                const badge = document.getElementById('autoFillBadge');

                if (badge) {

                    badge.style.display = 'inline';

                    badge.textContent = '(⏳ Leyendo datos y enlaces internos...)';

                }

                try {

                    const res = await fetch(`/api/pelixplay/meta?url=${encodeURIComponent(val)}`);

                    const data = await res.json();

                    if (data.success && data.title) {

                        document.getElementById('contentTitle').value = data.title;

                        if (badge) {

                            badge.style.display = 'inline';

                            if (data.source === 'latinomegahd') {

                                badge.textContent = `(✨ LatinoMegaHD: ${data.mf_count || 1} link(s) MediaFire listos sin publicidad)`;

                            } else if (data.source === 'youtube') {

                                badge.textContent = `(✨ Serie Vertical detectada: ${data.ep_count || 1} capítulo(s) listos para unir en 16:9)`;

                            } else {

                                badge.textContent = '(✨ Autocompletado de PelixPlay)';

                            }

                        }

                        if (data.rar_password) {

                            document.getElementById('rarPassword').value = data.rar_password;

                        }

                        if (data.season_name) {

                            document.getElementById('seasonName').value = data.season_name;

                        }

                        if (data.episode_range) {

                            document.getElementById('episodeName').value = data.episode_range;

                        }

                        if (data.content_type) {

                            document.getElementById('contentType').value = data.content_type;

                            toggleTypeFields();

                        }

                        if (data.vertical_to_horiz !== undefined) {

                            document.getElementById('verticalToHoriz').checked = !!data.vertical_to_horiz;

                        }

                        if (data.remove_subtitles !== undefined) {

                            document.getElementById('removeSubtitles').checked = !!data.remove_subtitles;

                        }

                        if (data.merge_clips !== undefined) {

                            document.getElementById('mergeClips').checked = !!data.merge_clips;

                        }

                        if (data.trim_end_sec !== undefined) {

                            document.getElementById('trimEndSec').value = data.trim_end_sec;

                        }

                        if (data.poster) {

                            selectPoster(data.poster, data.title, true);

                        }

                    } else if (badge) {

                        badge.style.display = 'none';

                    }

                } catch (e) {

                    if (badge) badge.style.display = 'none';

                }

            }

        }



        async function buscarTMDB() {

            const q = document.getElementById('contentTitle').value.trim();

            const type = document.getElementById('contentType').value;

            if (!q) {

                alert('Escribí primero el nombre de la película o serie.');

                return;

            }

            const box = document.getElementById('tmdbResultsBox');

            const grid = document.getElementById('tmdbGrid');

            box.style.display = 'block';

            grid.innerHTML = '<div style="padding:12px; color:#94a3b8;">Buscando pósters en TMDB...</div>';



            try {

                const res = await fetch(`/api/tmdb/search?q=${encodeURIComponent(q)}&type=${type}`);

                const data = await res.json();

                if (!data.results || data.results.length === 0) {

                    grid.innerHTML = '<div style="padding:12px; color:#f87171;">No se encontraron portadas con ese nombre. Podés pegar un link de imagen manualmente.</div>';

                    document.getElementById('selectedPosterBar').style.display = 'flex';

                    return;

                }

                grid.innerHTML = '';

                data.results.forEach(item => {

                    const card = document.createElement('div');

                    card.className = 'tmdb-card';

                    card.onclick = () => selectPoster(item.poster, item.title);

                    card.innerHTML = `

                        <img src="${item.poster}" alt="">

                        <div class="tmdb-card-title" title="${item.title} (${item.year})">${item.title} ${item.year ? '('+item.year+')' : ''}</div>

                    `;

                    grid.appendChild(card);

                });

                selectPoster(data.results[0].poster, null, false);

            } catch (e) {

                grid.innerHTML = '<div style="padding:12px; color:#f87171;">Error consultando TMDB.</div>';

            }

        }



        function selectPoster(url, title, closeBox = true) {

            document.getElementById('selectedPosterBar').style.display = 'flex';

            document.getElementById('posterPreviewImg').src = url;

            document.getElementById('posterUrlInput').value = url;

            if (closeBox) {

                document.getElementById('tmdbResultsBox').style.display = 'none';

            }

        }



        async function iniciarDescarga() {

            const content_type = document.getElementById('contentType').value;

            const urls = document.getElementById('downloadUrls').value.trim();

            const title = document.getElementById('contentTitle').value.trim();

            const poster_url = document.getElementById('posterUrlInput').value.trim();

            const rar_password = document.getElementById('rarPassword').value.trim();

            const season_name = document.getElementById('seasonName').value.trim();

            const episode_name = document.getElementById('episodeName').value.trim();

            const dataset_repo = document.getElementById('datasetRepoInput').value.trim();

            const vertical_to_horiz = document.getElementById('verticalToHoriz').checked;

            const remove_subtitles = document.getElementById('removeSubtitles').checked;

            const merge_clips = document.getElementById('mergeClips').checked;

            const trim_end_sec = document.getElementById('trimEndSec').value.trim();



            if (!urls) {

                alert('Pegá el enlace de PelixPlay, LatinoMegaHD, YouTube o MediaFire.');

                return;

            }



            const res = await fetch('/api/jobs/enqueue', {

                method: 'POST',

                headers: {'Content-Type': 'application/json'},

                body: JSON.stringify({

                    content_type, urls, title, poster_url,

                    rar_password, season_name, episode_name, dataset_repo,

                    vertical_to_horiz, remove_subtitles, merge_clips, trim_end_sec

                })

            });

            const data = await res.json();

            if (!data.success) {

                alert(data.message || 'Error al encolar descarga');

                return;

            }

            document.getElementById('downloadUrls').value = '';

            document.getElementById('autoFillBadge').style.display = 'none';

            lastDetectedPelixUrl = '';

            if (content_type === 'serie' && data.jobs && data.jobs.length === 1) {

                const m = episode_name.match(/(\d+)/);

                if (m) {

                    const nextNum = String(parseInt(m[1], 10) + 1).padStart(2, '0');

                    document.getElementById('episodeName').value = `Capitulo ${nextNum}`;

                }

            }

            refreshState();

        }



        function setFilter(f) {

            currentFilter = f;

            document.getElementById('tabAll').classList.toggle('active', f === 'all');

            document.getElementById('tabMovies').classList.toggle('active', f === 'movie');

            document.getElementById('tabSeries').classList.toggle('active', f === 'serie');

            renderLibrary();

        }



        function buildMovieJson(m) {

            const obj = {

                name: m.name,

                ico: m.ico,

                uri: m.uri

            };

            return JSON.stringify(obj, null, 2) + ",";

        }



        function buildSerieJson(s) {

            const obj = {

                tipo: "serie",

                name: s.name,

                ico: s.ico,

                temporada: (s.temporada || []).map(ep => ({

                    name: ep.name,

                    ico: s.ico,

                    uri: ep.uri

                }))

            };

            return JSON.stringify(obj, null, 2) + ",";

        }



        function openJsonModal(jsonStr) {

            document.getElementById('jsonModalText').textContent = jsonStr;

            document.getElementById('jsonModal').style.display = 'flex';

        }



        function closeJsonModal() {

            document.getElementById('jsonModal').style.display = 'none';

        }



        function copyModalJson() {

            const txt = document.getElementById('jsonModalText').textContent;

            navigator.clipboard.writeText(txt);

            alert('¡JSON copiado al portapapeles!');

        }



        function copyDirectJson(type, id) {

            let jsonStr = '';

            if (type === 'movie') {

                const m = stateData.movies.find(x => x.id === id);

                if (m) jsonStr = buildMovieJson(m);

            } else {

                const s = stateData.series.find(x => x.id === id);

                if (s) jsonStr = buildSerieJson(s);

            }

            if (jsonStr) {

                openJsonModal(jsonStr);

                navigator.clipboard.writeText(jsonStr);

            }

        }



        async function deleteItem(type, id) {

            if (!confirm('¿Quitar este registro de la lista del panel?')) return;

            await fetch('/api/item/delete', {

                method: 'POST',

                headers: {'Content-Type': 'application/json'},

                body: JSON.stringify({type, id})

            });

            refreshState();

        }



        function renderLibrary() {

            const tbody = document.getElementById('libraryBody');

            const movies = stateData.movies || [];

            const series = stateData.series || [];



            document.getElementById('countAll').textContent = movies.length + series.length;

            document.getElementById('countMovies').textContent = movies.length;

            document.getElementById('countSeries').textContent = series.length;



            let rows = [];



            if (currentFilter === 'all' || currentFilter === 'serie') {

                series.forEach(s => {

                    const epCount = (s.temporada || []).length;

                    const codes = (s.temporada || []).map(e => e.code || '').filter(Boolean).join(', ');

                    rows.push(`

                        <tr>

                            <td>

                                <div style="display:flex; align-items:center; gap:10px;">

                                    <img class="poster-thumb" src="${s.ico}" alt="">

                                    <span class="badge-serie">SERIE</span>

                                </div>

                            </td>

                            <td style="font-weight:700;">${s.name}</td>

                            <td><span class="code-pill">${codes || 's_xxxx.mp4'}</span></td>

                            <td><span style="color:#34d399; font-weight:600;">${epCount} capítulo(s) cargados</span></td>

                            <td style="color:var(--muted); font-size:12px;">${s.date || ''}</td>

                            <td style="text-align:right; white-space:nowrap;">

                                <button class="btn btn-sm" style="background:linear-gradient(135deg, #059669, #10b981); margin-right:5px;" onclick="openSingleFlyerModal('serie', '${s.id}')">

                                    <i class="fa-solid fa-image"></i> 🎨 Flyer MAR TV

                                </button>

                                <button class="btn btn-green btn-sm" onclick="copyDirectJson('serie', '${s.id}')">

                                    <i class="fa-solid fa-code"></i> JSON

                                </button>

                                <button class="btn btn-sm" style="background:#ef4444; margin-left:5px;" onclick="deleteItem('serie', '${s.id}')">

                                    <i class="fa-solid fa-trash"></i>

                                </button>

                            </td>

                        </tr>

                    `);

                });

            }



            if (currentFilter === 'all' || currentFilter === 'movie') {

                movies.forEach(m => {

                    rows.push(`

                        <tr>

                            <td>

                                <div style="display:flex; align-items:center; gap:10px;">

                                    <img class="poster-thumb" src="${m.ico}" alt="">

                                    <span class="badge-movie">PELÍCULA</span>

                                </div>

                            </td>

                            <td style="font-weight:700;">${m.name}</td>

                            <td><span class="code-pill">${m.code || ''}</span></td>

                            <td>${m.size_str || ''}</td>

                            <td style="color:var(--muted); font-size:12px;">${m.date || ''}</td>

                            <td style="text-align:right; white-space:nowrap;">

                                <button class="btn btn-sm" style="background:linear-gradient(135deg, #059669, #10b981); margin-right:5px;" onclick="openSingleFlyerModal('movie', '${m.id}')">

                                    <i class="fa-solid fa-image"></i> 🎨 Flyer MAR TV

                                </button>

                                <button class="btn btn-green btn-sm" onclick="copyDirectJson('movie', '${m.id}')">

                                    <i class="fa-solid fa-code"></i> JSON

                                </button>

                                <button class="btn btn-sm" style="background:#ef4444; margin-left:5px;" onclick="deleteItem('movie', '${m.id}')">

                                    <i class="fa-solid fa-trash"></i>

                                </button>

                            </td>

                        </tr>

                    `);

                });

            }



            if (rows.length === 0) {

                tbody.innerHTML = '<tr><td colspan="6" style="text-align:center; color:var(--muted); padding:28px;">Todavía no hay contenidos cargados. ¡Pegá tu primer enlace arriba para empezar!</td></tr>';

            } else {

                tbody.innerHTML = rows.join('');

            }

        }



        async function cancelJob(id) {

            if (!confirm('¿Deseas cancelar / quitar este proceso?')) return;

            await fetch('/api/jobs/cancel', {

                method: 'POST',

                headers: {'Content-Type': 'application/json'},

                body: JSON.stringify({id})

            });

            refreshState();

        }



        async function cancelAllJobs() {

            if (!confirm('¿Seguro que deseas DETENER todas las descargas y procesos en cola?')) return;

            await fetch('/api/jobs/cancel-all', {

                method: 'POST',

                headers: {'Content-Type': 'application/json'}

            });

            refreshState();

        }



        async function clearCompletedJobs() {

            await fetch('/api/jobs/clear', {

                method: 'POST',

                headers: {'Content-Type': 'application/json'}

            });

            refreshState();

        }



        async function refreshState() {

            try {

                const res = await fetch('/api/state');

                const data = await res.json();

                if (!data.success) return;

                stateData = data;

                try { updateCaptchaModal(data.jobs); } catch (e_cap) {}



                const repoSelect = document.getElementById('datasetRepoInput');

                if (repoSelect && data.dataset_repo && document.activeElement !== repoSelect) {

                    repoSelect.value = data.dataset_repo;

                }



                const jobsCard = document.getElementById('jobsCard');

                const jobsContainer = document.getElementById('jobsContainer');

                if (data.jobs && data.jobs.length > 0) {

                    jobsCard.style.display = 'block';

                    jobsContainer.innerHTML = data.jobs.map(j => {

                        const isDone = j.state === 'done';

                        const isError = j.state === 'error';

                        const isRunningOrQueued = !isDone && !isError;

                        const statusColor = isError ? '#f87171' : (isDone ? '#34d399' : '#38bdf8');

                        return `

                        <div class="job-item">

                            <div class="job-top">

                                <div>

                                    <span style="font-weight:700;">${j.display_label}</span>

                                    <span style="color:${statusColor}; font-size:12px; margin-left:10px;">${j.status}</span>

                                </div>

                                <div>

                                    ${isRunningOrQueued ? `

                                        <button class="btn btn-sm" style="background:#ef4444; padding:4px 9px; font-size:11px;" onclick="cancelJob('${j.id}')">

                                            <i class="fa-solid fa-xmark"></i> Cancelar

                                        </button>

                                    ` : `

                                        <button class="btn btn-sm" style="background:#334155; padding:4px 9px; font-size:11px;" onclick="cancelJob('${j.id}')">

                                            <i class="fa-solid fa-trash"></i> Quitar

                                        </button>

                                    `}

                                </div>

                            </div>

                            <div class="progress-track" style="margin-top:6px;">

                                <div class="progress-fill" style="width:${j.progress || 0}%; background:${isError ? '#ef4444' : (isDone ? '#10b981' : 'linear-gradient(90deg, #6366f1, #06b6d4)')};"></div>

                            </div>

                        </div>

                        `;

                    }).join('');

                } else {

                    jobsCard.style.display = 'none';

                }



                renderLibrary();

            } catch (e) {}

        }





        // ── MOTOR DEL ESTUDIO DE FLYERS & PÓSTERS MAR TV ─────────────────────────

        let flyerMode = 'single'; // 'single' | 'multi'

        let flyerAssetsLoaded = false;

        let martvHeaderImg = null;

        let martvSingleBgImg = null;

        const posterImgCache = {};

        const tmdbMetaFrontCache = {};

        let multiSelectedIds = [];

        let multiCustomOverrides = {}; // key -> { badge, desc, genre }



        async function ensureFlyerAssets() {

            if (flyerAssetsLoaded) return;

            try {

                const res = await fetch('/api/flyer/assets');

                const data = await res.json();

                if (data.success) {

                    martvHeaderImg = await loadImgPromise(data.header_b64);

                    martvSingleBgImg = await loadImgPromise(data.single_bg_b64);

                    flyerAssetsLoaded = true;

                }

            } catch (e) {

                console.error('Error cargando assets de flyer:', e);

            }

        }



        function loadImgPromise(src) {

            return new Promise((resolve) => {

                if (!src) return resolve(null);

                const img = new Image();

                img.crossOrigin = 'anonymous';

                img.onload = () => resolve(img);

                img.onerror = () => resolve(null);

                img.src = src;

            });

        }



        async function loadProxiedPoster(url) {

            if (!url) return null;

            if (posterImgCache[url]) return posterImgCache[url];

            const proxiedUrl = `/api/flyer/proxy-image?url=${encodeURIComponent(url)}`;

            const img = await loadImgPromise(proxiedUrl);

            if (img) posterImgCache[url] = img;

            return img;

        }



        async function getFrontTmdbMeta(title, type) {

            const key = `${type}::${title}`;

            if (tmdbMetaFrontCache[key]) return tmdbMetaFrontCache[key];

            try {

                const res = await fetch(`/api/flyer/meta?title=${encodeURIComponent(title)}&type=${type}`);

                const data = await res.json();

                if (data.success) {

                    tmdbMetaFrontCache[key] = data;

                    return data;

                }

            } catch (e) {}

            return {

                genres_str: type === 'serie' ? 'DRAMA Y MISTERIO' : 'ACCIÓN Y SUSPENSO',

                pill_genre: type === 'serie' ? 'DRAMA Y MISTERIO' : 'ACCIÓN Y SUSPENSO',

                hook1: 'Una historia atrapante',

                hook2: 'Disfrutala en calidad HD',

                mini_footer: 'Emoción, drama y suspenso',

                bottom_desc: 'UNA HISTORIA ATRAPANTE DE PRINCIPIO A FIN. YA DISPONIBLE EN MAR TV.',

                card_desc: 'Una atrapante historia disponible ahora en calidad HD en tu app MAR TV.'

            };

        }



        function getSerieChapterStrings(s) {

            const rawName = s.name || '';

            const sMatch = rawName.match(/Temporada\s*(\d+)/i);

            const sNum = sMatch ? parseInt(sMatch[1], 10) : 1;

            const eps = s.temporada || [];

            if (eps.length === 0) {

                return {

                    hudSub: `TEMPORADA ${sNum} DISPONIBLE`,

                    hudMain: `T${sNum} • DISPONIBLE`,

                    bottomSub: `TEMPORADA ${sNum} • YA DISPONIBLE`

                };

            }

            if (eps.length === 1 && /completa/i.test(eps[0].name || '')) {

                return {

                    hudSub: `TEMPORADA ${sNum} COMPLETA`,

                    hudMain: `T${sNum} • COMPLETA`,

                    bottomSub: `TEMPORADA ${sNum} • COMPLETA`

                };

            }

            const nums = eps.map((e, idx) => {

                const m = (e.name || '').match(/(\d+)/);

                return m ? parseInt(m[1], 10) : (idx + 1);

            }).sort((a, b) => a - b);



            const minEp = nums[0];

            const maxEp = nums[nums.length - 1];

            if (minEp === maxEp) {

                return {

                    hudSub: `TEMPORADA ${sNum} • CAPÍTULO ${maxEp}`,

                    hudMain: `T${sNum} • CAP. ${maxEp}`,

                    bottomSub: `TEMPORADA ${sNum} • CAPÍTULO ${maxEp}`

                };

            }

            return {

                hudSub: `TEMPORADA ${sNum} • CAPÍTULOS ${minEp} AL ${maxEp}`,

                hudMain: `T${sNum} • CAP. ${minEp}-${maxEp}`,

                bottomSub: `TEMPORADA ${sNum} • CAPÍTULOS ${minEp} AL ${maxEp}`

            };

        }



        function cleanDisplayTitle(rawName) {

            return (rawName || '').replace(/\s*-\s*Temporada\s*\d+.*$/i, '').trim().toUpperCase();

        }



        function populateSingleItemDropdown(selectedType, selectedId) {

            const sel = document.getElementById('singleItemSelect');

            sel.innerHTML = '';

            (stateData.series || []).forEach(s => {

                const opt = document.createElement('option');

                opt.value = `serie::${s.id}`;

                opt.textContent = `📺 [SERIE] ${s.name}`;

                if (selectedType === 'serie' && s.id === selectedId) opt.selected = true;

                sel.appendChild(opt);

            });

            (stateData.movies || []).forEach(m => {

                const opt = document.createElement('option');

                opt.value = `movie::${m.id}`;

                opt.textContent = `🎬 [PELÍCULA] ${m.name}`;

                if (selectedType === 'movie' && m.id === selectedId) opt.selected = true;

                sel.appendChild(opt);

            });

        }



        async function openSingleFlyerModal(type, id) {

            document.getElementById('flyerModal').style.display = 'flex';

            switchFlyerMode('single', false);

            populateSingleItemDropdown(type, id);

            await loadSingleItemIntoFlyer(type, id);

        }



        async function onSingleItemSelectChanged() {

            const val = document.getElementById('singleItemSelect').value;

            if (!val) return;

            const [type, id] = val.split('::');

            await loadSingleItemIntoFlyer(type, id);

        }



        let sensacineItems = [];

        let isSensacineSource = false;



        async function loadSingleItemIntoFlyer(type, id) {

            const badge = document.getElementById('flyerLoadingBadge');

            badge.style.display = 'block';

            await ensureFlyerAssets();



            if (type === 'sensacine') {

                const scItem = (sensacineItems || []).find(x => x.id === id);

                if (!scItem) {

                    badge.style.display = 'none';

                    return;

                }

                document.getElementById('sfHudTop').value = 'PRÓXIMAMENTE';

                document.getElementById('sfHudSub').value = `ESTRENO: ${scItem.short_date}`;

                document.getElementById('sfHudMain').value = 'MUY PRONTO';

                document.getElementById('sfBottomTitle').value = scItem.cleanTitle;

                document.getElementById('sfBottomSub').value = `PRÓXIMAMENTE EN MAR TV • ${scItem.short_date}`;

                const prefix = scItem.type === 'serie' ? 'SERIE' : 'PELÍCULA';

                document.getElementById('sfTopTag').value = `${prefix} • ${scItem.genres_str}`;

                document.getElementById('sfHook1').value = scItem.hook1;

                document.getElementById('sfHook2').value = scItem.hook2;

                document.getElementById('sfPillGenre').value = scItem.genres_str;

                document.getElementById('sfMiniFooter').value = scItem.mini_footer;

                document.getElementById('sfBottomDesc').value = scItem.bottom_desc;

                await loadProxiedPoster(scItem.ico);

                badge.style.display = 'none';

                await renderFlyerCanvas();

                return;

            }



            let item = null;

            if (type === 'serie') {

                item = (stateData.series || []).find(x => x.id === id);

            } else {

                item = (stateData.movies || []).find(x => x.id === id);

            }

            if (!item) {

                badge.style.display = 'none';

                return;

            }



            document.getElementById('sfHudTop').value = 'DISPONIBLE';

            const cleanTitle = cleanDisplayTitle(item.name);

            document.getElementById('sfBottomTitle').value = cleanTitle;



            if (type === 'serie') {

                const ch = getSerieChapterStrings(item);

                document.getElementById('sfHudSub').value = ch.hudSub;

                document.getElementById('sfHudMain').value = ch.hudMain;

                document.getElementById('sfBottomSub').value = ch.bottomSub;

            } else {

                document.getElementById('sfHudSub').value = 'PELÍCULA COMPLETA';

                document.getElementById('sfHudMain').value = 'YA DISPONIBLE';

                document.getElementById('sfBottomSub').value = 'YA DISPONIBLE';

            }



            // Preload poster & TMDB metadata in parallel

            const [posterImg, meta] = await Promise.all([

                loadProxiedPoster(item.ico),

                getFrontTmdbMeta(item.name, type)

            ]);



            const prefix = type === 'serie' ? 'SERIE' : 'PELÍCULA';

            document.getElementById('sfTopTag').value = `${prefix} • ${meta.genres_str}`;

            document.getElementById('sfHook1').value = meta.hook1;

            document.getElementById('sfHook2').value = meta.hook2;

            document.getElementById('sfPillGenre').value = meta.pill_genre;

            document.getElementById('sfMiniFooter').value = meta.mini_footer;

            document.getElementById('sfBottomDesc').value = meta.bottom_desc;



            badge.style.display = 'none';

            await renderFlyerCanvas();

        }



        async function openMultiFlyerModal(filterType = 'movie') {

            document.getElementById('flyerModal').style.display = 'flex';

            isSensacineSource = false;

            switchFlyerMode('multi', false);

            await ensureFlyerAssets();

            await selectLastItems(filterType, 3);

        }



        function switchFlyerMode(mode, triggerRender = true) {

            const btnSingle = document.getElementById('btnModeSingle');

            const btnMulti = document.getElementById('btnModeMulti');

            const btnUpcoming = document.getElementById('btnModeUpcoming');

            const ctrlSingle = document.getElementById('singleFlyerControls');

            const ctrlMulti = document.getElementById('multiFlyerControls');

            const scBar = document.getElementById('sensacineBar');

            const libBanner = document.getElementById('multiLibraryBanner');

            const libFilterBar = document.getElementById('libraryQuickFilterBar');



            [btnSingle, btnMulti, btnUpcoming].forEach(b => {

                if (!b) return;

                b.style.background = 'transparent';

                b.style.color = '#94a3b8';

                b.style.fontWeight = '600';

            });



            if (mode === 'single') {

                flyerMode = 'single';

                btnSingle.style.background = '#10b981';

                btnSingle.style.color = '#042f2e';

                btnSingle.style.fontWeight = '800';

                ctrlSingle.style.display = 'block';

                ctrlMulti.style.display = 'none';

            } else if (mode === 'upcoming') {

                flyerMode = 'multi';

                isSensacineSource = true;

                btnUpcoming.style.background = '#f59e0b';

                btnUpcoming.style.color = '#042f2e';

                btnUpcoming.style.fontWeight = '800';

                ctrlSingle.style.display = 'none';

                ctrlMulti.style.display = 'block';

                scBar.style.display = 'block';

                libBanner.style.display = 'none';

                libFilterBar.style.display = 'none';

            } else {

                flyerMode = 'multi';

                isSensacineSource = false;

                btnMulti.style.background = '#10b981';

                btnMulti.style.color = '#042f2e';

                btnMulti.style.fontWeight = '800';

                ctrlSingle.style.display = 'none';

                ctrlMulti.style.display = 'block';

                scBar.style.display = 'none';

                libBanner.style.display = 'block';

                libFilterBar.style.display = 'flex';

                if (multiSelectedIds.length === 0 || multiSelectedIds[0].startsWith('sensacine::')) {

                    selectLastItems('movie', 3);

                    return;

                }

            }

            if (triggerRender) renderFlyerCanvas();

        }



        async function openSensacineModal() {

            document.getElementById('flyerModal').style.display = 'flex';

            isSensacineSource = true;

            switchFlyerMode('upcoming', false);

            await ensureFlyerAssets();

            const curUrl = document.getElementById('sensacineCustomUrl').value || 'https://www.sensacine.com/peliculas/estrenos/mas-esperadas/';

            await loadSensacineUrl(curUrl);

        }



        async function loadSensacineUrl(url) {

            const badge = document.getElementById('flyerLoadingBadge');

            badge.style.display = 'block';

            badge.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Leyendo próximos estrenos de SensaCine...';

            document.getElementById('sensacineCustomUrl').value = url;

            try {

                const res = await fetch(`/api/sensacine/upcoming?url=${encodeURIComponent(url)}`);

                const data = await res.json();

                if (data.success && data.items) {

                    sensacineItems = data.items;

                    const isSerie = url.includes('/series/');

                    document.getElementById('mfHeaderTitle').value = isSerie ? 'SERIES QUE SE VIENEN A MAR TV' : 'LO QUE SE VIENE A MAR TV';

                    document.getElementById('mfHeaderSub').value = 'PRÓXIMOS ESTRENOS MÁS ESPERADOS • MUY PRONTO';

                    document.getElementById('mfLayoutStyle').value = 'cards';



                    multiSelectedIds = sensacineItems.slice(0, 3).map(x => `sensacine::${x.id}`);

                    sensacineItems.forEach(it => {

                        const k = `sensacine::${it.id}`;

                        multiCustomOverrides[k] = {

                            badge: it.defaultBadge,

                            desc: it.card_desc,

                            genre: `${it.type === 'serie' ? 'SERIE' : 'PELÍCULA'} • ${it.genres_str}`

                        };

                    });

                    await Promise.all(sensacineItems.slice(0, 4).map(it => loadProxiedPoster(it.ico)));

                    renderMultiChecklistUI();

                }

            } catch (e) {

                console.error(e);

            }

            badge.style.display = 'none';

            await renderFlyerCanvas();

        }



        async function openSingleSensacineItem(scId) {

            const sel = document.getElementById('singleItemSelect');

            populateSingleItemDropdown('', '');

            const scItem = (sensacineItems || []).find(x => x.id === scId);

            if (scItem) {

                const opt = document.createElement('option');

                opt.value = `sensacine::${scItem.id}`;

                opt.textContent = `🔮 [PRÓXIMAMENTE] ${scItem.name} (${scItem.short_date})`;

                opt.selected = true;

                sel.insertBefore(opt, sel.firstChild);

            }

            switchFlyerMode('single', false);

            await loadSingleItemIntoFlyer('sensacine', scId);

        }



        function getAllLibraryItemsUnified() {

            if (isSensacineSource && sensacineItems.length > 0) {

                return sensacineItems.map(it => ({

                    key: `sensacine::${it.id}`,

                    type: it.type,

                    id: it.id,

                    name: it.name,

                    cleanTitle: it.cleanTitle,

                    ico: it.ico,

                    date: it.date,

                    defaultBadge: it.defaultBadge,

                    shortBadge: it.shortBadge,

                    isSensacine: true,

                    rawItem: it

                }));

            }

            const list = [];

            (stateData.movies || []).forEach(m => {

                list.push({

                    key: `movie::${m.id}`,

                    type: 'movie',

                    id: m.id,

                    name: m.name,

                    cleanTitle: cleanDisplayTitle(m.name),

                    ico: m.ico,

                    date: m.date || '',

                    defaultBadge: 'YA DISPONIBLE • PELÍCULA COMPLETA',

                    shortBadge: 'YA DISPONIBLE',

                    rawItem: m

                });

            });

            (stateData.series || []).forEach(s => {

                const ch = getSerieChapterStrings(s);

                list.push({

                    key: `serie::${s.id}`,

                    type: 'serie',

                    id: s.id,

                    name: s.name,

                    cleanTitle: cleanDisplayTitle(s.name),

                    ico: s.ico,

                    date: s.date || '',

                    defaultBadge: ch.bottomSub,

                    shortBadge: ch.hudMain,

                    rawItem: s

                });

            });

            return list;

        }



        async function selectLastItems(filterType, count) {

            const badge = document.getElementById('flyerLoadingBadge');

            badge.style.display = 'block';

            await ensureFlyerAssets();



            const all = getAllLibraryItemsUnified();

            let filtered = all;

            if (filterType === 'movie') {

                filtered = all.filter(x => x.type === 'movie');

                document.getElementById('mfHeaderTitle').value = 'NUEVAS PELÍCULAS EN MAR TV';

                document.getElementById('mfHeaderSub').value = 'RECIÉN AGREGADAS • YA DISPONIBLES EN HD';

            } else if (filterType === 'serie') {

                filtered = all.filter(x => x.type === 'serie');

                document.getElementById('mfHeaderTitle').value = 'NUEVAS SERIES Y CAPÍTULOS';

                document.getElementById('mfHeaderSub').value = 'TEMPORADAS ACTUALIZADAS • YA DISPONIBLES';

            } else {

                document.getElementById('mfHeaderTitle').value = 'NUEVOS ESTRENOS EN MAR TV';

                document.getElementById('mfHeaderSub').value = 'PELÍCULAS Y SERIES RECIÉN AGREGADAS';

            }



            if (count > 4) {

                document.getElementById('mfLayoutStyle').value = 'grid';

            } else {

                document.getElementById('mfLayoutStyle').value = 'cards';

            }



            multiSelectedIds = filtered.slice(0, count).map(x => x.key);



            // Fetch metadata & posters for selected items

            await preloadMultiItemsData(multiSelectedIds);

            renderMultiChecklistUI();

            badge.style.display = 'none';

            await renderFlyerCanvas();

        }



        async function preloadMultiItemsData(keys) {

            const all = getAllLibraryItemsUnified();

            const tasks = keys.map(async (k) => {

                const it = all.find(x => x.key === k);

                if (!it) return;

                const [_, meta] = await Promise.all([

                    loadProxiedPoster(it.ico),

                    getFrontTmdbMeta(it.name, it.type)

                ]);

                if (!multiCustomOverrides[k]) {

                    multiCustomOverrides[k] = {

                        badge: it.defaultBadge,

                        desc: meta.card_desc,

                        genre: `${it.type === 'serie' ? 'SERIE' : 'PELÍCULA'} • ${meta.genres_str}`

                    };

                }

            });

            await Promise.all(tasks);

        }



        function renderMultiChecklistUI() {

            const container = document.getElementById('multiItemsChecklist');

            const all = getAllLibraryItemsUnified();

            container.innerHTML = '';



            all.forEach(it => {

                const isChecked = multiSelectedIds.includes(it.key);

                const ov = multiCustomOverrides[it.key] || {

                    badge: it.defaultBadge,

                    desc: 'Cargando descripción de TMDB...',

                    genre: it.type === 'serie' ? 'SERIE' : 'PELÍCULA'

                };



                const row = document.createElement('div');

                row.style.cssText = `background:${isChecked ? 'rgba(16,185,129,0.08)' : '#0d1322'}; border:1px solid ${isChecked ? '#10b981' : '#1e293b'}; border-radius:8px; padding:8px 10px;`;

                row.innerHTML = `

                    <div style="display:flex; align-items:center; justify-content:space-between; gap:10px;">

                        <label style="display:flex; align-items:center; gap:9px; cursor:pointer; font-weight:700; font-size:13px; flex:1;">

                            <input type="checkbox" ${isChecked ? 'checked' : ''} style="width:16px; height:16px; accent-color:#10b981;" onchange="toggleMultiItem('${it.key}', this.checked)">

                            <img src="${it.ico}" style="width:28px; height:40px; object-fit:cover; border-radius:4px;">

                            <span>${it.type === 'serie' ? '📺' : '🎬'} ${it.name}</span>

                        </label>

                        <div style="display:flex; align-items:center; gap:8px;">

                            <span style="font-size:11px; color:#fbbf24; font-weight:600;">${it.date}</span>

                            ${it.isSensacine ? `<button type="button" class="btn btn-sm" style="background:#059669; padding:4px 8px; font-size:11px;" onclick="openSingleSensacineItem('${it.id}')">🎨 Flyer Individual</button>` : ''}

                        </div>

                    </div>

                    ${isChecked ? `

                    <div style="display:grid; grid-template-columns: 1fr 1.6fr; gap:8px; margin-top:8px; padding-left:26px;">

                        <div>

                            <label style="font-size:10.5px; color:#34d399; display:block; margin-bottom:2px;">Capítulos / Estado en el Póster:</label>

                            <input type="text" class="form-control" style="padding:5px 8px; font-size:11.5px;" value="${(ov.badge || '').replace(/"/g, '&quot;')}" oninput="updateMultiOverride('${it.key}', 'badge', this.value)">

                        </div>

                        <div>

                            <label style="font-size:10.5px; color:#fde68a; display:block; margin-bottom:2px;">Breve descripción:</label>

                            <input type="text" class="form-control" style="padding:5px 8px; font-size:11.5px;" value="${(ov.desc || '').replace(/"/g, '&quot;')}" oninput="updateMultiOverride('${it.key}', 'desc', this.value)">

                        </div>

                    </div>

                    ` : ''}

                `;

                container.appendChild(row);

            });

        }



        async function toggleMultiItem(key, checked) {

            if (checked) {

                if (!multiSelectedIds.includes(key)) {

                    multiSelectedIds.push(key);

                    await preloadMultiItemsData([key]);

                }

            } else {

                multiSelectedIds = multiSelectedIds.filter(k => k !== key);

            }

            if (multiSelectedIds.length > 4) {

                document.getElementById('mfLayoutStyle').value = 'grid';

            }

            renderMultiChecklistUI();

            await renderFlyerCanvas();

        }



        function updateMultiOverride(key, field, val) {

            if (!multiCustomOverrides[key]) multiCustomOverrides[key] = {};

            multiCustomOverrides[key][field] = val;

            renderFlyerCanvas();

        }



        function closeFlyerModal() {

            document.getElementById('flyerModal').style.display = 'none';

        }



        // ── FUNCIONES DE DIBUJO EN CANVAS (ALTA DEFINICIÓN 856x1536) ─────────────

        function drawRoundedRectPath(ctx, x, y, w, h, r) {

            ctx.beginPath();

            ctx.moveTo(x + r, y);

            ctx.lineTo(x + w - r, y);

            ctx.quadraticCurveTo(x + w, y, x + w, y + r);

            ctx.lineTo(x + w, y + h - r);

            ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);

            ctx.lineTo(x + r, y + h);

            ctx.quadraticCurveTo(x, y + h, x, y + h - r);

            ctx.lineTo(x, y + r);

            ctx.quadraticCurveTo(x, y, x + r, y);

            ctx.closePath();

        }



        function drawImageCover(ctx, img, x, y, w, h) {

            if (!img) return;

            const imgRatio = img.width / img.height;

            const boxRatio = w / h;

            let sx = 0, sy = 0, sw = img.width, sh = img.height;

            if (imgRatio > boxRatio) {

                sw = img.height * boxRatio;

                sx = (img.width - sw) / 2;

            } else {

                sh = img.width / boxRatio;

                sy = (img.height - sh) / 2;

            }

            ctx.drawImage(img, sx, sy, sw, sh, x, y, w, h);

        }



        function wrapCanvasLines(ctx, text, maxWidth) {

            const words = (text || '').split(/\s+/).filter(Boolean);

            const lines = [];

            let current = '';

            for (const w of words) {

                const test = current ? `${current} ${w}` : w;

                if (ctx.measureText(test).width > maxWidth && current) {

                    lines.push(current);

                    current = w;

                } else {

                    current = test;

                }

            }

            if (current) lines.push(current);

            return lines;

        }



        async function renderFlyerCanvas() {

            const canvas = document.getElementById('flyerCanvas');

            if (!canvas) return;

            const ctx = canvas.getContext('2d');

            if (flyerMode === 'single') {

                await renderSingleFlyerOnCanvas(ctx, canvas.width, canvas.height);

            } else {

                await renderMultiFlyerOnCanvas(ctx, canvas.width, canvas.height);

            }

        }



        async function renderSingleFlyerOnCanvas(ctx, W, H) {

            // Base scale relative to 571x1024 original template

            const S = W / 571.0;

            ctx.save();

            ctx.clearRect(0, 0, W, H);



            // 1. Draw the spotless MAR TV base template

            if (martvSingleBgImg) {

                ctx.drawImage(martvSingleBgImg, 0, 0, W, H);

            } else {

                const bgGrad = ctx.createLinearGradient(0, 0, 0, H);

                bgGrad.addColorStop(0, '#04221b');

                bgGrad.addColorStop(1, '#02100d');

                ctx.fillStyle = bgGrad;

                ctx.fillRect(0, 0, W, H);

            }



            // Get selected item & its poster (supports Library items AND SensaCine upcoming items!)

            const selVal = document.getElementById('singleItemSelect').value || '';

            const [type, id] = selVal.split('::');

            let item = null;

            if (selVal.startsWith('sensacine::')) {

                const scId = selVal.split('::')[1];

                item = (sensacineItems || []).find(x => x.id === scId);

            } else if (type === 'serie') {

                item = (stateData.series || []).find(x => x.id === id);

            } else {

                item = (stateData.movies || []).find(x => x.id === id);

            }

            const posterImg = item ? await loadProxiedPoster(item.ico) : null;



            // 2. Draw Poster in the right neon frame (x=248..568, y=218..708 in 571x1024 coords)

            const px = 248 * S, py = 218 * S, pw = 319 * S, ph = 490 * S, pr = 26 * S;

            if (posterImg) {

                ctx.save();

                drawRoundedRectPath(ctx, px, py, pw, ph, pr);

                ctx.clip();

                drawImageCover(ctx, posterImg, px, py, pw, ph);



                // Subtle bottom vignette inside poster for cinematic depth

                const pVig = ctx.createLinearGradient(0, py + ph * 0.72, 0, py + ph);

                pVig.addColorStop(0, 'rgba(0,0,0,0)');

                pVig.addColorStop(1, 'rgba(2,18,14,0.45)');

                ctx.fillStyle = pVig;

                ctx.fillRect(px, py, pw, ph);



                // Diagonal neon laser shine over top-right corner of poster (matching original MAR TV template!)

                ctx.globalCompositeOperation = 'screen';

                const laserGrad = ctx.createLinearGradient(px + pw * 0.45, py, px + pw, py + ph * 0.35);

                laserGrad.addColorStop(0, 'rgba(16, 185, 129, 0)');

                laserGrad.addColorStop(0.48, 'rgba(52, 211, 153, 0.42)');

                laserGrad.addColorStop(0.52, 'rgba(167, 243, 208, 0.85)');

                laserGrad.addColorStop(0.56, 'rgba(52, 211, 153, 0.35)');

                laserGrad.addColorStop(1, 'rgba(16, 185, 129, 0)');

                ctx.fillStyle = laserGrad;

                ctx.beginPath();

                ctx.moveTo(px + pw * 0.35, py);

                ctx.lineTo(px + pw, py);

                ctx.lineTo(px + pw, py + ph * 0.42);

                ctx.closePath();

                ctx.fill();

                ctx.restore();



                // Neon green glowing border around poster

                ctx.save();

                drawRoundedRectPath(ctx, px, py, pw, ph, pr);

                ctx.shadowColor = '#10b981';

                ctx.shadowBlur = 16 * S;

                ctx.strokeStyle = '#34d399';

                ctx.lineWidth = 2.2 * S;

                ctx.stroke();

                ctx.restore();

            }



            // 3. Top Genre Line ("PELÍCULA • TERROR Y ACCIÓN") at x=46, y=206

            const topTag = (document.getElementById('sfTopTag').value || '').trim().toUpperCase();

            if (topTag) {

                ctx.save();

                ctx.font = `800 ${15.5 * S}px 'Inter', sans-serif`;

                const parts = topTag.split('•');

                let curX = 46 * S;

                const baseY = 207 * S;

                if (parts.length > 1) {

                    const p1 = parts[0].trim() + ' • ';

                    const p2 = parts.slice(1).join('•').trim();

                    ctx.fillStyle = '#4ade80';

                    ctx.fillText(p1, curX, baseY);

                    curX += ctx.measureText(p1).width;

                    ctx.fillStyle = '#94a3b8';

                    ctx.fillText(p2, curX, baseY);

                } else {

                    ctx.fillStyle = '#4ade80';

                    ctx.fillText(topTag, curX, baseY);

                }

                ctx.restore();

            }



            // 4. Left Hooks (Hook 1 at y=248, Hook 2 at y=296)

            const hook1 = (document.getElementById('sfHook1').value || '').trim();

            const hook2 = (document.getElementById('sfHook2').value || '').trim();

            ctx.save();

            ctx.font = `500 ${17.5 * S}px 'Inter', sans-serif`;

            ctx.fillStyle = '#e2e8f0';

            let hy = 246 * S;

            wrapCanvasLines(ctx, hook1, 185 * S).slice(0, 2).forEach(line => {

                ctx.fillText(line, 46 * S, hy);

                hy += 21 * S;

            });

            hy += 10 * S;

            wrapCanvasLines(ctx, hook2, 185 * S).slice(0, 2).forEach(line => {

                ctx.fillText(line, 46 * S, hy);

                hy += 21 * S;

            });

            ctx.restore();



            // 5. Inside HUD Box (Center X = 171 * S)

            const hudCenterX = 171 * S;

            const hudSub = (document.getElementById('sfHudSub').value || '').trim().toUpperCase();

            const hudMain = (document.getElementById('sfHudMain').value || '').trim().toUpperCase();



            ctx.save();

            ctx.textAlign = 'center';

            // "DISPONIBLE"

            ctx.font = `800 ${26.5 * S}px 'Inter', sans-serif`;

            ctx.fillStyle = '#ffffff';

            ctx.shadowColor = 'rgba(0,0,0,0.6)';

            ctx.shadowBlur = 6 * S;

            const hudTopTxt = (document.getElementById('sfHudTop') ? document.getElementById('sfHudTop').value : 'DISPONIBLE').trim().toUpperCase() || 'DISPONIBLE';

            let htFontSz = hudTopTxt.length > 10 ? 20.5 * S : 26.5 * S;

            ctx.font = `800 ${htFontSz}px 'Inter', sans-serif`;

            ctx.fillText(hudTopTxt, hudCenterX, 396 * S);



            // Subtitle ("PELÍCULA COMPLETA" or "TEMPORADA 1 • CAPÍTULOS 1 AL 10")

            let subFontSz = 10.5 * S;

            ctx.font = `700 ${subFontSz}px 'Inter', sans-serif`;

            while (ctx.measureText(hudSub).width > 205 * S && subFontSz > 7.5 * S) {

                subFontSz -= 0.5 * S;

                ctx.font = `700 ${subFontSz}px 'Inter', sans-serif`;

            }

            ctx.fillStyle = '#e2e8f0';

            ctx.fillText(hudSub, hudCenterX, 415 * S);



            // Main Green Status ("YA DISPONIBLE" or "T1 • CAP. 1-10")

            let mainFontSz = 24.5 * S;

            ctx.font = `800 ${mainFontSz}px 'Inter', sans-serif`;

            while (ctx.measureText(hudMain).width > 206 * S && mainFontSz > 14 * S) {

                mainFontSz -= 0.8 * S;

                ctx.font = `800 ${mainFontSz}px 'Inter', sans-serif`;

            }

            ctx.fillStyle = '#4ade80';

            ctx.shadowColor = 'rgba(74, 222, 128, 0.45)';

            ctx.shadowBlur = 10 * S;

            ctx.fillText(hudMain, hudCenterX, 449 * S);

            ctx.restore();



            // 6. Genre Pill Badge (x=56..242, y=589..624)

            const pillGenre = (document.getElementById('sfPillGenre').value || '').trim().toUpperCase();

            if (pillGenre) {

                ctx.save();

                const pillX = 56 * S, pillY = 589 * S, pillW = 186 * S, pillH = 34 * S;

                drawRoundedRectPath(ctx, pillX, pillY, pillW, pillH, 17 * S);

                ctx.fillStyle = 'rgba(45, 65, 58, 0.78)';

                ctx.fill();

                ctx.strokeStyle = 'rgba(148, 163, 184, 0.35)';

                ctx.lineWidth = 1.2 * S;

                ctx.stroke();



                ctx.textAlign = 'center';

                let pSz = 13 * S;

                ctx.font = `700 ${pSz}px 'Inter', sans-serif`;

                while (ctx.measureText(pillGenre).width > (pillW - 18 * S) && pSz > 8.5 * S) {

                    pSz -= 0.5 * S;

                    ctx.font = `700 ${pSz}px 'Inter', sans-serif`;

                }

                ctx.fillStyle = '#cbd5e1';

                ctx.fillText(pillGenre, pillX + pillW / 2, pillY + 22 * S);

                ctx.restore();

            }



            // 7. Lock Box Text ("DISPONIBLE EN" / "PELÍCULAS" or "SERIES") at x=88, y=662

            ctx.save();

            ctx.font = `800 ${11.5 * S}px 'Inter', sans-serif`;

            ctx.fillStyle = '#ffffff';

            ctx.fillText('DISPONIBLE EN', 88 * S, 663 * S);

            ctx.fillText(type === 'serie' ? 'SERIES MAR TV' : 'PELÍCULAS MAR TV', 88 * S, 679 * S);

            ctx.restore();



            // 8. Mini Footer below lock box (x=46, y=708)

            const miniFooter = (document.getElementById('sfMiniFooter').value || '').trim();

            if (miniFooter) {

                ctx.save();

                ctx.font = `500 ${16 * S}px 'Inter', sans-serif`;

                ctx.fillStyle = '#f1f5f9';

                let mfy = 708 * S;

                wrapCanvasLines(ctx, miniFooter, 185 * S).slice(0, 2).forEach(l => {

                    ctx.fillText(l, 46 * S, mfy);

                    mfy += 19 * S;

                });

                ctx.restore();

            }



            // 9. Bottom Big Title ("RESIDENT EVIL: NOCHE CERO" / "DOCTORA X") at y=832

            const botTitle = (document.getElementById('sfBottomTitle').value || '').trim().toUpperCase();

            if (botTitle) {

                ctx.save();

                ctx.textAlign = 'center';

                let tSz = 52 * S;

                ctx.font = `700 ${tSz}px 'Oswald', 'Anton', sans-serif`;

                while (ctx.measureText(botTitle).width > 515 * S && tSz > 24 * S) {

                    tSz -= 1.5 * S;

                    ctx.font = `700 ${tSz}px 'Oswald', 'Anton', sans-serif`;

                }

                ctx.fillStyle = '#ffffff';

                ctx.shadowColor = 'rgba(0,0,0,0.75)';

                ctx.shadowBlur = 10 * S;

                ctx.fillText(botTitle, (W / 2), 832 * S);

                ctx.restore();

            }



            // 10. Bottom Green Subtitle ("YA DISPONIBLE" / "TEMPORADA 1 • CAPÍTULOS 1 AL 10") at y=868

            const botSub = (document.getElementById('sfBottomSub').value || '').trim().toUpperCase();

            if (botSub) {

                ctx.save();

                ctx.textAlign = 'center';

                let bsSz = 25 * S;

                ctx.font = `800 ${bsSz}px 'Inter', sans-serif`;

                while (ctx.measureText(botSub).width > 520 * S && bsSz > 14 * S) {

                    bsSz -= 1 * S;

                    ctx.font = `800 ${bsSz}px 'Inter', sans-serif`;

                }

                ctx.fillStyle = '#4ade80';

                ctx.shadowColor = 'rgba(74, 222, 128, 0.35)';

                ctx.shadowBlur = 8 * S;

                ctx.fillText(botSub, (W / 2), 867 * S);

                ctx.restore();

            }



            // 11. Bottom Gold Brief Description (y=912..985)

            const botDesc = (document.getElementById('sfBottomDesc').value || '').trim().toUpperCase();

            if (botDesc) {

                ctx.save();

                ctx.textAlign = 'center';

                let bdSz = 22.5 * S;

                ctx.font = `700 ${bdSz}px 'Inter', sans-serif`;

                let lines = wrapCanvasLines(ctx, botDesc, 515 * S);

                while (lines.length > 3 && bdSz > 13.5 * S) {

                    bdSz -= 1 * S;

                    ctx.font = `700 ${bdSz}px 'Inter', sans-serif`;

                    lines = wrapCanvasLines(ctx, botDesc, 515 * S);

                }

                lines = lines.slice(0, 3);

                const lineH = bdSz * 1.24;

                const totalH = lines.length * lineH;

                let startY = (942 * S) - (totalH / 2) + (bdSz * 0.8);

                ctx.fillStyle = '#e5d5b5';

                ctx.shadowColor = 'rgba(0,0,0,0.8)';

                ctx.shadowBlur = 6 * S;

                lines.forEach(l => {

                    ctx.fillText(l, W / 2, startY);

                    startY += lineH;

                });

                ctx.restore();

            }



            ctx.restore();

        }



        async function renderMultiFlyerOnCanvas(ctx, W, H) {

            const S = W / 571.0;

            ctx.save();

            ctx.clearRect(0, 0, W, H);



            // 1. Cybernetic Emerald Dark Background

            const bgGrad = ctx.createLinearGradient(0, 0, 0, H);

            bgGrad.addColorStop(0, '#063025');

            bgGrad.addColorStop(0.25, '#041f18');

            bgGrad.addColorStop(0.75, '#031510');

            bgGrad.addColorStop(1, '#020b09');

            ctx.fillStyle = bgGrad;

            ctx.fillRect(0, 0, W, H);



            // Ambient neon radial glows

            const rad1 = ctx.createRadialGradient(W * 0.85, H * 0.22, 10, W * 0.85, H * 0.22, W * 0.65);

            rad1.addColorStop(0, 'rgba(16, 185, 129, 0.22)');

            rad1.addColorStop(1, 'rgba(16, 185, 129, 0)');

            ctx.fillStyle = rad1;

            ctx.fillRect(0, 0, W, H);



            const rad2 = ctx.createRadialGradient(W * 0.15, H * 0.65, 10, W * 0.15, H * 0.65, W * 0.6);

            rad2.addColorStop(0, 'rgba(6, 182, 212, 0.14)');

            rad2.addColorStop(1, 'rgba(6, 182, 212, 0)');

            ctx.fillStyle = rad2;

            ctx.fillRect(0, 0, W, H);



            // Draw Official MAR TV Top Header (with circular logo)

            if (martvHeaderImg) {

                ctx.drawImage(martvHeaderImg, 0, 0, W, 192 * S);

            }



            // 2. Top Header Banner ("NUEVOS ESTRENOS EN MAR TV" + Green Subtitle)

            const headerTitle = (document.getElementById('mfHeaderTitle').value || 'NUEVOS ESTRENOS EN MAR TV').trim().toUpperCase();

            const headerSub = (document.getElementById('mfHeaderSub').value || 'YA DISPONIBLES EN TU APP').trim().toUpperCase();



            ctx.save();

            ctx.textAlign = 'center';

            let htSz = 29 * S;

            ctx.font = `700 ${htSz}px 'Oswald', sans-serif`;

            while (ctx.measureText(headerTitle).width > 520 * S && htSz > 18 * S) {

                htSz -= 1 * S;

                ctx.font = `700 ${htSz}px 'Oswald', sans-serif`;

            }

            ctx.fillStyle = '#ffffff';

            ctx.shadowColor = 'rgba(16, 185, 129, 0.5)';

            ctx.shadowBlur = 12 * S;

            ctx.fillText(headerTitle, W / 2, 208 * S);



            ctx.font = `800 ${13 * S}px 'Inter', sans-serif`;

            ctx.fillStyle = '#4ade80';

            ctx.fillText(headerSub, W / 2, 228 * S);



            // Glowing divider line under header

            const lineGrad = ctx.createLinearGradient(40 * S, 0, W - 40 * S, 0);

            lineGrad.addColorStop(0, 'rgba(16, 185, 129, 0)');

            lineGrad.addColorStop(0.5, 'rgba(52, 211, 153, 0.85)');

            lineGrad.addColorStop(1, 'rgba(16, 185, 129, 0)');

            ctx.fillStyle = lineGrad;

            ctx.fillRect(40 * S, 237 * S, W - 80 * S, 2 * S);

            ctx.restore();



            // 3. Gather selected items

            const all = getAllLibraryItemsUnified();

            const selectedItems = multiSelectedIds.map(k => all.find(x => x.key === k)).filter(Boolean);

            const layoutStyle = document.getElementById('mfLayoutStyle').value || 'cards';



            const contentTop = 248 * S;

            const contentBottom = 948 * S;

            const availH = contentBottom - contentTop;



            if (selectedItems.length === 0) {

                ctx.save();

                ctx.textAlign = 'center';

                ctx.font = `600 ${18 * S}px 'Inter', sans-serif`;

                ctx.fillStyle = '#94a3b8';

                ctx.fillText('Seleccioná al menos 1 película o serie a la derecha', W / 2, H / 2);

                ctx.restore();

            } else if (layoutStyle === 'cards' && selectedItems.length <= 4) {

                // MODO TARJETAS HORIZONTALES CON PÓSTER + CAPÍTULOS + BREVE DESCRIPCIÓN (1 a 4 items)

                const N = selectedItems.length;

                const gap = (N === 4 ? 10 : 14) * S;

                const cardH = Math.min(220 * S, (availH - gap * (N - 1)) / N);

                const totalCardsH = cardH * N + gap * (N - 1);

                let curY = contentTop + (availH - totalCardsH) / 2;



                for (let i = 0; i < N; i++) {

                    const it = selectedItems[i];

                    const ov = multiCustomOverrides[it.key] || {

                        badge: it.defaultBadge,

                        desc: '',

                        genre: it.type === 'serie' ? 'SERIE' : 'PELÍCULA'

                    };

                    const pImg = await loadProxiedPoster(it.ico);



                    const cx = 24 * S, cw = W - 48 * S, r = 16 * S;



                    // Card Glass Background + Neon Border

                    ctx.save();

                    drawRoundedRectPath(ctx, cx, curY, cw, cardH, r);

                    const cGrad = ctx.createLinearGradient(cx, curY, cx + cw, curY + cardH);

                    cGrad.addColorStop(0, 'rgba(10, 38, 30, 0.92)');

                    cGrad.addColorStop(1, 'rgba(6, 22, 18, 0.95)');

                    ctx.fillStyle = cGrad;

                    ctx.fill();

                    ctx.shadowColor = 'rgba(16, 185, 129, 0.35)';

                    ctx.shadowBlur = 12 * S;

                    ctx.strokeStyle = '#10b981';

                    ctx.lineWidth = 1.6 * S;

                    ctx.stroke();

                    ctx.restore();



                    // Poster on the left of card

                    const pad = 10 * S;

                    const postH = cardH - pad * 2;

                    const postW = postH * 0.68;

                    const postX = cx + pad;

                    const postY = curY + pad;



                    if (pImg) {

                        ctx.save();

                        drawRoundedRectPath(ctx, postX, postY, postW, postH, 10 * S);

                        ctx.clip();

                        drawImageCover(ctx, pImg, postX, postY, postW, postH);

                        ctx.restore();



                        ctx.save();

                        drawRoundedRectPath(ctx, postX, postY, postW, postH, 10 * S);

                        ctx.strokeStyle = '#34d399';

                        ctx.lineWidth = 1.5 * S;

                        ctx.stroke();

                        ctx.restore();

                    }



                    // Right side text inside card

                    const tx = postX + postW + 14 * S;

                    const tw = (cx + cw) - tx - 14 * S;

                    let ty = curY + (N === 4 ? 22 : 26) * S;



                    // 1) Genre tag

                    ctx.save();

                    ctx.font = `800 ${(N === 4 ? 10.5 : 11.5) * S}px 'Inter', sans-serif`;

                    ctx.fillStyle = '#38bdf8';

                    ctx.fillText((ov.genre || '').toUpperCase(), tx, ty);



                    // 2) Title

                    ty += (N === 4 ? 24 : 28) * S;

                    let titleSz = (N === 4 ? 22 : 26) * S;

                    ctx.font = `700 ${titleSz}px 'Oswald', sans-serif`;

                    while (ctx.measureText(it.cleanTitle).width > tw && titleSz > 15 * S) {

                        titleSz -= 1 * S;

                        ctx.font = `700 ${titleSz}px 'Oswald', sans-serif`;

                    }

                    ctx.fillStyle = '#ffffff';

                    ctx.fillText(it.cleanTitle, tx, ty);



                    // 3) Neon HUD Badge for Availability / Chapters

                    ty += (N === 4 ? 10 : 12) * S;

                    const badgeTxt = (ov.badge || it.defaultBadge).toUpperCase();

                    ctx.font = `800 ${(N === 4 ? 11 : 12.5) * S}px 'Inter', sans-serif`;

                    const bPadX = 10 * S;

                    const bW = Math.min(tw, ctx.measureText(badgeTxt).width + bPadX * 2);

                    const bH = (N === 4 ? 22 : 25) * S;



                    drawRoundedRectPath(ctx, tx, ty, bW, bH, 6 * S);

                    ctx.fillStyle = 'rgba(16, 185, 129, 0.18)';

                    ctx.fill();

                    ctx.strokeStyle = '#34d399';

                    ctx.lineWidth = 1.2 * S;

                    ctx.stroke();



                    ctx.fillStyle = '#4ade80';

                    ctx.fillText(badgeTxt, tx + bPadX, ty + bH * 0.72);



                    // 4) Brief Description

                    ty += bH + (N === 4 ? 15 : 18) * S;

                    const descFontSz = (N === 4 ? 11.5 : 13) * S;

                    ctx.font = `500 ${descFontSz}px 'Inter', sans-serif`;

                    ctx.fillStyle = '#e5d5b5';

                    const maxLines = N === 4 ? 2 : 3;

                    const descLines = wrapCanvasLines(ctx, ov.desc || '', tw).slice(0, maxLines);

                    descLines.forEach(dl => {

                        ctx.fillText(dl, tx, ty);

                        ty += descFontSz * 1.32;

                    });

                    ctx.restore();



                    curY += cardH + gap;

                }

            } else {

                // MODO CARTELERA / GRILLA DE PÓSTERS GRANDES (3 a 6 items)

                const items = selectedItems.slice(0, 6);

                const N = items.length;

                const cols = N <= 3 ? N : (N === 4 ? 2 : 3);

                const rows = Math.ceil(N / cols);

                const padX = 24 * S;

                const gapX = 14 * S;

                const gapY = 16 * S;

                const cellW = (W - padX * 2 - gapX * (cols - 1)) / cols;

                const cellH = Math.min(340 * S, (availH - gapY * (rows - 1)) / rows);

                const totalGridH = cellH * rows + gapY * (rows - 1);

                const startY = contentTop + (availH - totalGridH) / 2;



                for (let idx = 0; idx < N; idx++) {

                    const it = items[idx];

                    const ov = multiCustomOverrides[it.key] || {

                        badge: it.shortBadge,

                        desc: ''

                    };

                    const pImg = await loadProxiedPoster(it.ico);

                    const rIdx = Math.floor(idx / cols);

                    const cIdx = idx % cols;



                    // Center last row if incomplete

                    const itemsInRow = (rIdx === rows - 1 && N % cols !== 0) ? (N % cols) : cols;

                    const rowW = itemsInRow * cellW + (itemsInRow - 1) * gapX;

                    const rowStartX = (W - rowW) / 2;



                    const x = rowStartX + cIdx * (cellW + gapX);

                    const y = startY + rIdx * (cellH + gapY);



                    // Card container

                    ctx.save();

                    drawRoundedRectPath(ctx, x, y, cellW, cellH, 14 * S);

                    ctx.fillStyle = 'rgba(8, 28, 22, 0.92)';

                    ctx.fill();

                    ctx.strokeStyle = '#10b981';

                    ctx.lineWidth = 1.6 * S;

                    ctx.stroke();



                    // Poster area (top 72% of cell)

                    const pH = cellH * 0.72;

                    if (pImg) {

                        ctx.save();

                        drawRoundedRectPath(ctx, x + 4 * S, y + 4 * S, cellW - 8 * S, pH, 10 * S);

                        ctx.clip();

                        drawImageCover(ctx, pImg, x + 4 * S, y + 4 * S, cellW - 8 * S, pH);

                        ctx.restore();

                    }



                    // Top floating badge on poster ("YA DISPONIBLE" or "T1 • CAP. 1-10")

                    const bText = (ov.badge || it.shortBadge).toUpperCase();

                    ctx.font = `800 ${10 * S}px 'Inter', sans-serif`;

                    const bw = Math.min(cellW - 16 * S, ctx.measureText(bText).width + 14 * S);

                    const bh = 20 * S;

                    drawRoundedRectPath(ctx, x + (cellW - bw) / 2, y + 10 * S, bw, bh, 6 * S);

                    ctx.fillStyle = 'rgba(4, 47, 46, 0.92)';

                    ctx.fill();

                    ctx.strokeStyle = '#34d399';

                    ctx.lineWidth = 1.2 * S;

                    ctx.stroke();



                    ctx.textAlign = 'center';

                    ctx.fillStyle = '#4ade80';

                    ctx.fillText(bText, x + cellW / 2, y + 23.5 * S);



                    // Title below poster

                    let tSz = 16 * S;

                    ctx.font = `700 ${tSz}px 'Oswald', sans-serif`;

                    while (ctx.measureText(it.cleanTitle).width > (cellW - 14 * S) && tSz > 11 * S) {

                        tSz -= 0.5 * S;

                        ctx.font = `700 ${tSz}px 'Oswald', sans-serif`;

                    }

                    ctx.fillStyle = '#ffffff';

                    ctx.fillText(it.cleanTitle, x + cellW / 2, y + pH + 22 * S);



                    // Mini description (2 lines)

                    ctx.font = `500 ${10 * S}px 'Inter', sans-serif`;

                    ctx.fillStyle = '#e5d5b5';

                    const dLines = wrapCanvasLines(ctx, ov.desc || '', cellW - 16 * S).slice(0, 2);

                    let dy = y + pH + 38 * S;

                    dLines.forEach(l => {

                        ctx.fillText(l, x + cellW / 2, dy);

                        dy += 12.5 * S;

                    });



                    ctx.restore();

                }

            }



            // 4. Bottom Official Footer Banner

            ctx.save();

            const footY = 956 * S;

            ctx.fillStyle = 'rgba(4, 18, 15, 0.95)';

            ctx.fillRect(0, footY, W, H - footY);



            const fLine = ctx.createLinearGradient(0, 0, W, 0);

            fLine.addColorStop(0, 'rgba(16,185,129,0)');

            fLine.addColorStop(0.5, '#34d399');

            fLine.addColorStop(1, 'rgba(16,185,129,0)');

            ctx.fillStyle = fLine;

            ctx.fillRect(0, footY, W, 2.5 * S);



            ctx.textAlign = 'center';

            ctx.font = `800 ${18 * S}px 'Inter', sans-serif`;

            ctx.fillStyle = '#ffffff';

            ctx.fillText('DISPONIBLES AHORA EN TU APP MAR TV', W / 2, 984 * S);



            ctx.font = `700 ${13 * S}px 'Inter', sans-serif`;

            ctx.fillStyle = '#4ade80';

            ctx.fillText('ENTRETENIMIENTO EN CALIDAD HD • ACTUALIZACIÓN DIARIA', W / 2, 1005 * S);

            ctx.restore();



            ctx.restore();

        }



        function downloadFlyerImage() {

            const canvas = document.getElementById('flyerCanvas');

            if (!canvas) return;

            const link = document.createElement('a');

            let fname = 'flyer_martv.jpg';

            if (flyerMode === 'single') {

                const rawT = (document.getElementById('sfBottomTitle').value || 'estreno').toLowerCase().replace(/[^a-z0-9]+/g, '_');

                fname = `martv_${rawT}.jpg`;

            } else {

                fname = `martv_estrenos_${Date.now().toString().slice(-4)}.jpg`;

            }

            link.download = fname;

            link.href = canvas.toDataURL('image/jpeg', 0.94);

            link.click();

        }



        function copyFlyerImageToClipboard() {

            const canvas = document.getElementById('flyerCanvas');

            if (!canvas) return;

            canvas.toBlob(async (blob) => {

                if (!blob) return;

                try {

                    await navigator.clipboard.write([

                        new ClipboardItem({ 'image/png': blob })

                    ]);

                    const toast = document.getElementById('flyerCopyToast');

                    toast.style.display = 'block';

                    setTimeout(() => { toast.style.display = 'none'; }, 3000);

                } catch (e) {

                    alert('Tu navegador no permitió copiar directo al portapapeles. Usá el botón "Descargar Póster HD (.jpg)".');

                }

            }, 'image/png');

        }



        let captchaJobId = null;

        let captchaTimer = null;



        let captchaRunning = false;



        function startCaptchaFrames() {

            stopCaptchaFrames();

            captchaRunning = true;

            const img = document.getElementById('captchaImg');

            const next = (delay) => {

                if (!captchaRunning) return;

                captchaTimer = setTimeout(loadFrame, delay);

            };

            const loadFrame = () => {

                if (!captchaRunning || !captchaJobId) return;

                const loader = new Image();

                let finished = false;

                const done = (ok) => {

                    if (finished) return;

                    finished = true;

                    if (ok) img.src = loader.src;

                    next(ok ? 300 : 900);

                };

                loader.onload = () => done(true);

                loader.onerror = () => done(false);

                setTimeout(() => done(false), 8000);

                loader.src = '/api/captcha/frame/' + captchaJobId + '?t=' + Date.now();

            };

            loadFrame();

        }



        function stopCaptchaFrames() {

            captchaRunning = false;

            if (captchaTimer) { clearTimeout(captchaTimer); captchaTimer = null; }

        }



        function openCaptchaModal() {

            const modal = document.getElementById('captchaModal');

            if (!modal || !captchaJobId) return;

            modal.style.display = 'flex';

            document.getElementById('captchaFab').style.display = 'none';

            startCaptchaFrames();

        }



        function closeCaptchaModal(manual) {

            const modal = document.getElementById('captchaModal');

            const fab = document.getElementById('captchaFab');

            if (!modal) return;

            modal.style.display = 'none';

            if (manual) {

                stopCaptchaFrames();

                if (fab && captchaJobId) fab.style.display = 'block';

            } else {

                stopCaptchaFrames();

                captchaJobId = null;

                if (fab) fab.style.display = 'none';

            }

        }



        async function captchaImgClick(ev) {

            const img = ev.currentTarget;

            const r = img.getBoundingClientRect();

            const x = (ev.clientX - r.left) / r.width;

            const y = (ev.clientY - r.top) / r.height;

            try {

                await fetch('/api/captcha/click', {

                    method: 'POST',

                    headers: {'Content-Type': 'application/json'},

                    body: JSON.stringify({job_id: captchaJobId, x: x, y: y})

                });

            } catch (e) {}

        }



        function updateCaptchaModal(jobs) {

            const modal = document.getElementById('captchaModal');

            if (!modal) return;

            const need = (jobs || []).find(j => j.captcha_needed && !j.cancelled && j.state !== 'done' && j.state !== 'error');

            if (!need) {

                if (captchaJobId) closeCaptchaModal(false);

                return;

            }

            if (captchaJobId !== need.id) {

                captchaJobId = need.id;

                document.getElementById('captchaTitle').textContent = need.display_label || 'Capítulo';

                openCaptchaModal();

            }

        }



        setInterval(refreshState, 2000);

        refreshState();

    </script>

    <button id="captchaFab" onclick="openCaptchaModal()" style="display:none; position:fixed; right:18px; bottom:18px; z-index:9998; background:#f59e0b; color:#111; border:none; border-radius:30px; padding:14px 20px; font-weight:800; font-size:14px; cursor:pointer; box-shadow:0 6px 24px rgba(0,0,0,.5);">🧩 Resolver captcha</button>

    <div id="captchaModal" style="display:none; position:fixed; inset:0; z-index:9999; background:rgba(2,6,23,.88); align-items:center; justify-content:center; flex-direction:column; padding:12px;">

        <div style="color:#fff; font-weight:800; font-size:16px; margin-bottom:4px;">🧩 Captcha: <span id="captchaTitle"></span></div>

        <div style="color:#cbd5e1; font-size:13px; margin-bottom:10px; text-align:center;">Hacé clic en <b>"No soy un robot"</b> sobre la imagen. Si Google muestra fotos, tocá las que pide y dale a Verificar. Se cierra solo cuando termina.</div>

        <img id="captchaImg" alt="Cargando captcha..." onclick="captchaImgClick(event)" style="max-width:96vw; max-height:72vh; border:2px solid #38bdf8; border-radius:10px; cursor:pointer; background:#000; min-width:320px; min-height:180px;">

        <button onclick="closeCaptchaModal(true)" style="margin-top:12px; background:#334155; color:#fff; border:none; border-radius:8px; padding:9px 18px; cursor:pointer; font-weight:700;">Ocultar</button>

    </div>

</body>

</html>

"""

@app.route("/")
def index():
    return render_template_string(HTML_TEMPLATE, dataset_repo=CATALOG.get("dataset_repo", DEFAULT_DATASET_REPO))

if __name__ == "__main__":
    load_catalog_from_hf()
    port = int(os.environ.get("PORT", 5050))
    app.run(host="0.0.0.0", port=port, debug=False)