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
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
import os, subprocess, uuid, random, tempfile, shutil
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import FileResponse, Response
from pydantic import BaseModel
import requests
import numpy as np
import soundfile as sf

app = FastAPI()

RENDERS_DIR = "/tmp/renders"
os.makedirs(RENDERS_DIR, exist_ok=True)

# ---------------------------------------------------------------------------
# Fonts
# ---------------------------------------------------------------------------
FONT_CANDIDATES = {
    "montserrat": ["/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"],
    "poppins":    ["/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"],
    "anton":      ["/usr/share/fonts/truetype/freefont/FreeSansBold.ttf"],
    "impact":     ["/usr/share/fonts/truetype/freefont/FreeSansBold.ttf"],
    "oswald":     ["/usr/share/fonts/truetype/liberation/LiberationSansNarrow-Bold.ttf"],
    "bebas":      ["/usr/share/fonts/truetype/liberation/LiberationSansNarrow-Bold.ttf"],
    "roboto":     ["/usr/share/fonts/truetype/liberation/LiberationSans-Bold.ttf"],
    "dejavu sans":["/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"],
    "serif":      ["/usr/share/fonts/truetype/dejavu/DejaVuSerif-Bold.ttf"],
}
FALLBACK_FONT = "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"

def resolve_font(name):
    key = (name or "").strip().lower()
    for cand in FONT_CANDIDATES.get(key, []):
        if os.path.exists(cand):
            return cand
    return FALLBACK_FONT

# --- Kokoro TTS (lazy-loaded singleton) ---
_kokoro = {"pipe": None}
def get_kokoro(lang_code="a"):
    if _kokoro["pipe"] is None:
        from kokoro import KPipeline
        _kokoro["pipe"] = KPipeline(lang_code=lang_code)
    return _kokoro["pipe"]

class TTSReq(BaseModel):
    text: str
    voice: str | None = "af_bella"
    speed: float | None = 1.0

class RenderReq(BaseModel):
    voice_url: str
    script: str
    hook: str | None = None
    onscreen_cta: str | None = None
    # Style
    font: str | None = "Montserrat"
    caption_style: str | None = "bold_center"
    caption_color: str | None = "#FFFFFF"
    title_color: str | None = "#FFFFFF"
    cta_color: str | None = "#FFD54A"
    accent_color: str | None = "#FFD54A"
    background: str | None = "black"
    subtitle_size: int | None = 64
    title_size: int | None = 88
    cta_size: int | None = 56
    stroke_width: float | None = 5
    shadow: bool | None = True
    box_opacity: float | None = 0.55
    uppercase: bool | None = False
    animation: str | None = "subtle_zoom"
    # Caption reveal: "phrase" (one go) | "word" (one word at a time) | "karaoke" (words build up)
    caption_animation: str | None = "phrase"
    # Placement (fractions of the 1920px-tall canvas)
    title_position: float | None = 0.13
    caption_position: float | None = 0.63
    cta_position: float | None = 0.56
    safe_top: float | None = 0.10
    safe_bottom: float | None = 0.24
    max_seconds: int | None = 60
    # Section branding outro
    brand_link: str | None = None
    brand_text: str | None = None
    brand_duration: int | None = 0
    seed: int | None = None

@app.get("/")
def root():
    return {"ok": True, "service": "shorts-renderer", "version": 4,
            "caption_animations": ["phrase", "word", "karaoke"]}

@app.get("/health")
def health():
    return {"ok": True}

@app.post("/tts")
def tts(req: TTSReq):
    voice = req.voice or "af_bella"
    lang = voice[0] if voice else "a"
    try:
        pipe = get_kokoro(lang_code=lang)
        chunks = []
        for _gs, _ps, audio in pipe(req.text, voice=voice, speed=req.speed or 1.0):
            arr = audio.detach().cpu().numpy() if hasattr(audio, "detach") else np.asarray(audio)
            chunks.append(arr)
        if not chunks:
            raise HTTPException(500, "Kokoro produced no audio")
        wav = np.concatenate(chunks).astype(np.float32)
        job = str(uuid.uuid4())
        wav_path = os.path.join(RENDERS_DIR, f"{job}.wav")
        mp3_path = os.path.join(RENDERS_DIR, f"{job}.mp3")
        sf.write(wav_path, wav, 24000)
        subprocess.run(["ffmpeg","-y","-i",wav_path,"-b:a","128k",mp3_path],
                       check=True, capture_output=True, timeout=120)
        with open(mp3_path,"rb") as f:
            data = f.read()
        try: os.remove(wav_path)
        except OSError: pass
        return Response(content=data, media_type="audio/mpeg")
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(500, f"tts failed: {type(e).__name__}: {str(e)[:400]}")

def probe_duration(path):
    try:
        out = subprocess.check_output([
            "ffprobe","-v","error","-show_entries","format=duration",
            "-of","default=noprint_wrappers=1:nokey=1", path
        ], timeout=60).decode().strip()
        return float(out or "0")
    except Exception:
        return 0.0

# ---- color helpers ----
def hex_to_ff(color, default="0xFFFFFF"):
    if not color: return default
    c = color.strip()
    if c.startswith("#") and len(c) == 7:
        return "0x" + c[1:].upper()
    if c.lower() in ("black","white","red","yellow"):
        return c.lower()
    return default

def hex_to_ass(color, default="&H00FFFFFF"):
    if not color: return default
    c = color.strip().lstrip("#")
    if len(c) != 6: return default
    r, g, b = c[0:2], c[2:4], c[4:6]
    return f"&H00{b}{g}{r}".upper()

def solid_bg(background):
    b = (background or "black").strip().lower()
    if b == "white": return "white"
    if b.startswith("#") and len(b) == 7: return "0x" + b[1:].upper()
    if b in ("black","gray","navy"): return b
    return "black"

def build_caption_entries(script, duration, upper, mode):
    """Return timed caption entries covering the WHOLE narration so nothing is cut.

    modes:
      - "phrase" (default): 3-4 words shown together in one go.
      - "word":            one word at a time.
      - "karaoke":         words build up inside a line, then the line resets.
    Word timings are proportional to word length for tighter audio sync.
    """
    words = script.split()
    if upper: words = [w.upper() for w in words]
    if not words: words = [script.strip() or " "]
    mode = (mode or "phrase").strip().lower()

    weights = [max(2, len(w)) for w in words]
    wsum = float(sum(weights)) or 1.0
    starts, t = [], 0.0
    for wt in weights:
        starts.append(t); t += duration * wt / wsum
    ends = starts[1:] + [duration]

    entries = []  # (start, end, text)
    if mode == "word":
        for i, w in enumerate(words):
            entries.append((starts[i], ends[i], w))
    elif mode == "karaoke":
        LINE = 5
        i = 0
        while i < len(words):
            grp_start = i
            grp_end = min(i + LINE, len(words))
            for gi in range(grp_start, grp_end):
                entries.append((starts[gi], ends[gi], " ".join(words[grp_start:gi + 1])))
            i += LINE
    else:  # phrase / one-go
        SIZE = 4
        i = 0
        while i < len(words):
            grp_end = min(i + SIZE, len(words))
            entries.append((starts[i], ends[grp_end - 1], " ".join(words[i:grp_end])))
            i += SIZE
    # Guarantee a minimum visible window and no gaps/overlaps.
    fixed = []
    for idx, (s, e, txt) in enumerate(entries):
        e = max(e, s + 0.25)
        fixed.append((round(s, 3), round(e, 3), txt))
    return fixed


def esc(t): return t.replace("\\","\\\\").replace(":","\\:").replace("'","\u2019")

@app.post("/render")
def render(req: RenderReq):
    job = str(uuid.uuid4())
    voice_path = os.path.join(RENDERS_DIR, f"{job}.mp3")
    main_path = os.path.join(RENDERS_DIR, f"{job}_main.mp4")
    out_path = os.path.join(RENDERS_DIR, f"{job}.mp4")
    srt_path = os.path.join(RENDERS_DIR, f"{job}.srt")

    try:
        r = requests.get(req.voice_url, timeout=60)
    except Exception as e:
        raise HTTPException(400, f"voice fetch error: {str(e)[:200]}")
    if r.status_code != 200 or len(r.content) < 500:
        raise HTTPException(400, f"voice fetch failed {r.status_code} ({len(r.content)} bytes)")
    with open(voice_path,"wb") as f: f.write(r.content)

    audio_dur = probe_duration(voice_path)
    if audio_dur <= 0:
        raise HTTPException(400, "voice_url did not return decodable audio")
    # Cover the FULL narration (never truncate captions); only a generous hard cap.
    hard_cap = float(req.max_seconds or 60)
    hard_cap = max(hard_cap, 60.0)
    duration = max(3.0, min(hard_cap, audio_dur))

    upper = bool(req.uppercase)
    entries = build_caption_entries(req.script, duration, upper, req.caption_animation)

    font = resolve_font(req.font)
    title_c = hex_to_ff(req.title_color, "0xFFFFFF")
    cta_c = hex_to_ff(req.cta_color, "0xFFD54A")
    cap_c = hex_to_ff(req.caption_color, "0xFFFFFF")
    box_op = max(0.0, min(1.0, float(req.box_opacity if req.box_opacity is not None else 0.55)))
    stroke = int(max(0, min(12, float(req.stroke_width or 4))))

    title_size = int(req.title_size or 88)
    sub_size = int(req.subtitle_size or 64)
    cta_size = int(req.cta_size or 56)
    y_cap = int(max(0.0, min(1.0, float(req.caption_position or 0.63))) * 1920)
    y_title = int(max(0.0, min(1.0, float(req.title_position or 0.13))) * 1920)
    y_cta = int(max(0.0, min(1.0, float(req.cta_position or 0.56))) * 1920)

    hook = (req.hook or "").strip()
    cta = (req.onscreen_cta or "").strip()
    if upper:
        hook, cta = hook.upper(), cta.upper()

    drawtexts = []
    if hook:
        # Fixed headline for the whole clip while captions flow underneath.
        drawtexts.append(
            f"drawtext=fontfile={font}:text='{esc(hook)}':fontcolor={title_c}:fontsize={title_size}:"
            f"borderw={stroke}:bordercolor=black:x=(w-text_w)/2:y={y_title}:"
            f"box=1:boxcolor=black@{box_op}:boxborderw=24:line_spacing=10"
        )
    if cta:
        drawtexts.append(
            f"drawtext=fontfile={font}:text='{esc(cta)}':fontcolor={cta_c}:fontsize={cta_size}:"
            f"borderw={stroke}:bordercolor=black:x=(w-text_w)/2:y={y_cta}:"
            f"box=1:boxcolor=black@{box_op}:boxborderw=18"
        )
    # Flowing captions as time-gated drawtext (reliable: no libass/subtitles dependency).
    for (s, e, txt) in entries:
        drawtexts.append(
            f"drawtext=fontfile={font}:text='{esc(txt)}':fontcolor={cap_c}:fontsize={sub_size}:"
            f"borderw={max(1,stroke)}:bordercolor=black:x=(w-text_w)/2:y={y_cap}:"
            f"box=1:boxcolor=black@{box_op}:boxborderw=18:enable='between(t,{s},{e})'"
        )
    vf = ",".join(drawtexts) if drawtexts else "null"


    bg = solid_bg(req.background)
    anim = (req.animation or "").lower()
    zoom = "zoompan=z='min(zoom+0.0008,1.15)':d=1:s=1080x1920" if "zoom" in anim else "scale=1080:1920"
    bg_filter = f"color=c={bg}:s=1080x1920:d={duration},{zoom}"

    cmd = [
        "ffmpeg","-y","-f","lavfi","-i", bg_filter,"-i", voice_path,
        "-vf", vf,"-c:v","libx264","-preset","veryfast","-pix_fmt","yuv420p",
        "-c:a","aac","-b:a","128k","-shortest","-t", f"{duration}","-r","30", main_path,
    ]
    try:
        subprocess.run(cmd, check=True, capture_output=True, timeout=300)
    except subprocess.CalledProcessError as e:
        raise HTTPException(500, f"ffmpeg failed: {e.stderr.decode()[-500:]}")

    # ---- Optional section-branding outro (black screen + link) ----
    brand_secs = int(req.brand_duration or 0)
    if brand_secs > 0 and (req.brand_text or req.brand_link):
        outro_path = os.path.join(RENDERS_DIR, f"{job}_outro.mp4")
        line1 = esc((req.brand_text or "").strip().upper() if upper else (req.brand_text or "").strip())
        line2 = esc((req.brand_link or "").strip())
        dts = []
        if line1:
            dts.append(f"drawtext=fontfile={font}:text='{line1}':fontcolor=white:fontsize=64:"
                       f"borderw=3:bordercolor=black:x=(w-text_w)/2:y=(h/2)-90")
        if line2:
            dts.append(f"drawtext=fontfile={font}:text='{line2}':fontcolor={hex_to_ff(req.accent_color,'0xFFD54A')}:"
                       f"fontsize=52:borderw=3:bordercolor=black:x=(w-text_w)/2:y=(h/2)+20")
        ovf = ",".join(["fade=t=in:st=0:d=0.4"] + dts) if dts else "fade=t=in:st=0:d=0.4"
        ocmd = [
            "ffmpeg","-y",
            "-f","lavfi","-i", f"color=c=black:s=1080x1920:d={brand_secs}:r=30",
            "-f","lavfi","-i", f"anullsrc=channel_layout=stereo:sample_rate=44100",
            "-vf", ovf,"-c:v","libx264","-preset","veryfast","-pix_fmt","yuv420p",
            "-c:a","aac","-b:a","128k","-t", f"{brand_secs}", outro_path,
        ]
        try:
            subprocess.run(ocmd, check=True, capture_output=True, timeout=120)
            concat_txt = os.path.join(RENDERS_DIR, f"{job}_list.txt")
            with open(concat_txt,"w") as f:
                f.write(f"file '{main_path}'\nfile '{outro_path}'\n")
            subprocess.run(
                ["ffmpeg","-y","-f","concat","-safe","0","-i",concat_txt,
                 "-c:v","libx264","-preset","veryfast","-pix_fmt","yuv420p",
                 "-c:a","aac","-b:a","128k", out_path],
                check=True, capture_output=True, timeout=180,
            )
        except subprocess.CalledProcessError:
            os.replace(main_path, out_path)
    else:
        os.replace(main_path, out_path)

    return FileResponse(out_path, media_type="video/mp4", filename=f"{job}.mp4")

@app.get("/file/{name}")
def get_file(name: str):
    p = os.path.join(RENDERS_DIR, name)
    if not os.path.exists(p): raise HTTPException(404)
    return FileResponse(p, media_type="video/mp4")


# ==========================================================================
# Template-video engine (merged from template-generator). Adds /templates and
# /render-template without touching the existing /render, /tts, /health routes.
# ==========================================================================
from pathlib import Path
from typing import Optional
import re
import time as _time
import json as _json
import io
from PIL import Image, ImageDraw, ImageFont

ROOT = Path(__file__).resolve().parent
FONT_DIR = ROOT / "fonts"
W, H = 1080, 1920
FPS = 20

KOKORO_VOICES = [
    "af_heart", "af_bella", "af_nicole", "af_sarah", "af_sky", "af_alloy",
    "af_aoede", "af_jessica", "af_kore", "af_nova", "af_river",
    "am_adam", "am_michael", "am_echo", "am_eric", "am_fenrir",
    "am_liam", "am_onyx", "am_puck", "am_santa",
    "bf_emma", "bf_isabella", "bf_alice", "bf_lily",
    "bm_george", "bm_lewis", "bm_daniel", "bm_fable",
]
DEFAULT_VOICE = "af_heart"

TEMPLATES = [
    "atmospheric_text_hook",
    "tweet_thread",
    "notes_app",
    "fullscreen_title_hook",
]

YELLOW = (255, 212, 0)
NAVY = (10, 14, 30)
NAVY2 = (18, 24, 48)
CREAM = (247, 240, 222)

# (single FastAPI instance defined above; do not re-create it here)

# ---------------------------------------------------------------------------
# Auth (optional bearer for private-Space friendliness; open if no key set)
# ---------------------------------------------------------------------------
SPACE_KEY = os.environ.get("SPACE_AUTH_KEY", "").strip()


def _check_auth(req: Request) -> bool:
    if not SPACE_KEY:
        return True
    auth = req.headers.get("authorization", "")
    return auth.replace("Bearer ", "").strip() == SPACE_KEY


# ---------------------------------------------------------------------------
# Fonts
# ---------------------------------------------------------------------------
def _font(name: str, size: int) -> ImageFont.FreeTypeFont:
    path = FONT_DIR / name
    try:
        if path.exists():
            return ImageFont.truetype(str(path), size)
    except Exception:
        pass
    for fallback in ["/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf"]:
        if Path(fallback).exists():
            return ImageFont.truetype(fallback, size)
    return ImageFont.load_default()


def anton(size):
    return _font("Anton.ttf", size)


def bebas(size):
    return _font("BebasNeue.ttf", size)


def archivo(size):
    return _font("ArchivoBlack.ttf", size)


def inter(size):
    f = FONT_DIR / "Inter-Bold.ttf"
    return _font("Inter-Bold.ttf" if f.exists() else "ArchivoBlack.ttf", size)


# ---------------------------------------------------------------------------
# Kokoro TTS
# ---------------------------------------------------------------------------
def synth(text: str, voice: str) -> tuple[np.ndarray, int]:
    """Synthesize one segment of text -> (float32 mono samples, sample_rate).
    Reuses the shared Kokoro pipeline singleton (get_kokoro) from the base app."""
    text = (text or "").strip()
    if not text:
        return np.zeros(int(24000 * 0.3), dtype=np.float32), 24000
    v = voice if voice in KOKORO_VOICES else DEFAULT_VOICE
    try:
        pipe = get_kokoro(lang_code=v[0] if v else "a")
        chunks = []
        for _, _, audio in pipe(text, voice=v):
            arr = audio.detach().cpu().numpy() if hasattr(audio, "detach") else np.asarray(audio)
            chunks.append(arr.astype(np.float32))
        if not chunks:
            raise RuntimeError("empty kokoro output")
        return np.concatenate(chunks), 24000
    except Exception as e:
        print("Kokoro TTS (template) failed, using silence fallback:", e, flush=True)
        approx = max(0.6, len(text.split()) / 2.5)
        return np.zeros(int(24000 * approx), dtype=np.float32), 24000


def synth_segments(lines: list[str], voice: str, gap_s: float = 0.18) -> tuple[np.ndarray, int, list[float]]:
    """Synthesize each line separately so segment durations are exact.
    Returns (full_audio, sr, per_segment_duration_including_gap)."""
    sr = 24000
    audio_parts = []
    durations = []
    gap = np.zeros(int(sr * gap_s), dtype=np.float32)
    for i, line in enumerate(lines):
        a, sr = synth(line, voice)
        dur = len(a) / sr
        audio_parts.append(a)
        if i < len(lines) - 1:
            audio_parts.append(gap)
            dur += gap_s
        durations.append(dur)
    full = np.concatenate(audio_parts) if audio_parts else np.zeros(1, dtype=np.float32)
    return full, sr, durations


# ---------------------------------------------------------------------------
# Text helpers
# ---------------------------------------------------------------------------
def split_sentences(text: str, max_items: int) -> list[str]:
    text = (text or "").strip()
    if not text:
        return []
    parts = [p.strip() for p in re.split(r"(?<=[.!?])\s+|\n+", text) if p.strip()]
    if not parts:
        parts = [text]
    return parts[:max_items]


def wrap_text(text: str, font: ImageFont.FreeTypeFont, max_width: int, draw: ImageDraw.ImageDraw) -> list[str]:
    words = text.split()
    lines, cur = [], ""
    for w in words:
        test = (cur + " " + w).strip()
        if draw.textlength(test, font=font) <= max_width or not cur:
            cur = test
        else:
            lines.append(cur)
            cur = w
    if cur:
        lines.append(cur)
    return lines


def draw_text_block(draw, xy_center, lines, font, fill, max_width, line_spacing=1.08,
                     stroke_width=0, stroke_fill=None, align="center"):
    cx, cy = xy_center
    sizes = [draw.textbbox((0, 0), ln, font=font, stroke_width=stroke_width) for ln in lines]
    heights = [b[3] - b[1] for b in sizes]
    total_h = sum(heights) * line_spacing
    y = cy - total_h / 2
    for ln, h in zip(lines, heights):
        w = draw.textlength(ln, font=font)
        x = cx - w / 2
        draw.text((x, y), ln, font=font, fill=fill, stroke_width=stroke_width, stroke_fill=stroke_fill)
        y += h * line_spacing
    return y


def gradient_bg(top, bottom):
    img = Image.new("RGB", (W, H), top)
    px = img.load()
    for y in range(H):
        t = y / H
        r = int(top[0] + (bottom[0] - top[0]) * t)
        g = int(top[1] + (bottom[1] - top[1]) * t)
        b = int(top[2] + (bottom[2] - top[2]) * t)
        for x in range(0, W, 4):
            px[x, y] = (r, g, b)
    # cheap horizontal fill (speed): stretch every 4th column
    arr = np.array(img)
    for i in range(1, 4):
        arr[:, i::4] = arr[:, 0::4][:, : arr[:, i::4].shape[1]]
    return Image.fromarray(arr)


def load_background_image(url: Optional[str]) -> Optional[Image.Image]:
    if not url:
        return None
    try:
        r = requests.get(url, timeout=20)
        r.raise_for_status()
        img = Image.open(io.BytesIO(r.content)).convert("RGB")
        # cover-fit into 1080x1920
        scale = max(W / img.width, H / img.height)
        nw, nh = int(img.width * scale), int(img.height * scale)
        img = img.resize((nw, nh))
        left = (nw - W) // 2
        top = (nh - H) // 2
        return img.crop((left, top, left + W, top + H))
    except Exception as e:
        print("bg image load failed:", e, flush=True)
        return None


def dim(img: Image.Image, amount=0.45) -> Image.Image:
    overlay = Image.new("RGB", img.size, (0, 0, 0))
    return Image.blend(img, overlay, amount)


# ---------------------------------------------------------------------------
# Template 1: atmospheric_text_hook
# ---------------------------------------------------------------------------
def render_atmospheric(headline: str, hook_lines: list[str], bg_img, active: int) -> Image.Image:
    base = dim(bg_img, 0.5) if bg_img is not None else gradient_bg((30, 30, 34), (5, 5, 8))
    img = base.copy()
    draw = ImageDraw.Draw(img)
    # dark gradient overlay top/bottom for legibility
    grad = Image.new("L", (1, H), 0)
    for y in range(H):
        v = 0
        if y < H * 0.28:
            v = int(160 * (1 - y / (H * 0.28)))
        elif y > H * 0.78:
            v = int(200 * ((y - H * 0.78) / (H * 0.22)))
        grad.putpixel((0, y), v)
    grad = grad.resize((W, H))
    black = Image.new("RGB", (W, H), (0, 0, 0))
    img = Image.composite(black, img, grad)
    draw = ImageDraw.Draw(img)

    f_head = archivo(78)
    head_lines = wrap_text(headline.upper(), f_head, W - 140, draw)
    draw_text_block(draw, (W / 2, 190), head_lines, f_head, "white", W - 140,
                     stroke_width=6, stroke_fill="black")

    f_hook = anton(96)
    y = 780
    for i, line in enumerate(hook_lines):
        if i > active:
            continue
        wrapped = wrap_text(line.upper(), f_hook, W - 100, draw)
        color = YELLOW if i % 2 == 0 else "white"
        yb = draw_text_block(draw, (W / 2, y + 70), wrapped, f_hook, color, W - 100,
                              stroke_width=8, stroke_fill="black")
        y = yb + 30

    if active >= len(hook_lines) - 1:
        f_cta = archivo(58)
        draw_text_block(draw, (W / 2, H - 190), ["SAVE THIS POST!"], f_cta, YELLOW, W - 120,
                         stroke_width=6, stroke_fill="black")
    return img


# ---------------------------------------------------------------------------
# Template 2: tweet_thread
# ---------------------------------------------------------------------------
def draw_tweet_card(canvas: Image.Image, top_y: int, handle: str, text: str, timestamp: str, idx: int):
    card_w = 900
    x0 = (W - card_w) // 2
    draw = ImageDraw.Draw(canvas)
    f_user = inter(34)
    f_handle = inter(26)
    f_body = inter(36)
    f_time = inter(22)

    tmp = Image.new("RGB", (10, 10))
    tdraw = ImageDraw.Draw(tmp)
    body_lines = wrap_text(text, f_body, card_w - 90, tdraw)
    card_h = 170 + len(body_lines) * 48 + 40

    card = Image.new("RGBA", (card_w, card_h), (255, 255, 255, 255))
    cd = ImageDraw.Draw(card)
    cd.rounded_rectangle([0, 0, card_w - 1, card_h - 1], radius=28, outline=(210, 210, 215), width=2)
    cd.text((28, 20), "‹", font=inter(30), fill=(60, 100, 220))
    cd.text((28, 66), "Tweet", font=inter(30), fill=(20, 20, 24))
    # avatar
    cd.ellipse([28, 118, 88, 178], fill=(120, 150, 230))
    cd.text((100, 118), "Username:", font=f_user, fill=(20, 20, 24))
    cd.text((100, 156), "@ContentMaster", font=f_handle, fill=(120, 130, 145))
    ty = 210
    for ln in body_lines:
        cd.text((28, ty), ln, font=f_body, fill=(15, 15, 20))
        ty += 48
    cd.text((28, ty + 14), timestamp, font=f_time, fill=(150, 155, 165))

    canvas.paste(card, (x0, top_y), card)
    return card_h


def render_tweet_thread(tweets: list[str], active: int) -> Image.Image:
    img = gradient_bg(NAVY, (4, 6, 14))
    y = 260
    shown = tweets[: active + 1]
    # cascade: show last 3 stacked, offset each by +40px x/y
    start = max(0, len(shown) - 4)
    for i, t in enumerate(shown[start:]):
        idx = start + i
        offset = i * 46
        top = y + offset
        h = draw_tweet_card(img, top, "@ContentMaster", t, f"3:15 PM · Jan 9, 2021 · {120 + idx*40}K Views", idx)
    draw = ImageDraw.Draw(img)
    draw_text_block(draw, (W / 2, 130), ["MY VIRAL THREAD"], archivo(56), "white", W - 140,
                     stroke_width=4, stroke_fill="black")
    return img


# ---------------------------------------------------------------------------
# Template 3: notes_app
# ---------------------------------------------------------------------------
def render_notes_app(lines: list[str], active: int) -> Image.Image:
    img = gradient_bg((14, 16, 22), (4, 4, 6))
    draw = ImageDraw.Draw(img)

    phone_w, phone_h = 760, 1560
    px0, py0 = (W - phone_w) // 2, (H - phone_h) // 2
    draw.rounded_rectangle([px0 - 18, py0 - 18, px0 + phone_w + 18, py0 + phone_h + 18],
                            radius=90, fill=(30, 30, 32))
    draw.rounded_rectangle([px0, py0, px0 + phone_w, py0 + phone_h], radius=72, fill=CREAM)

    # status bar
    f_status = inter(24)
    draw.text((px0 + 40, py0 + 30), "9:31", font=f_status, fill=(30, 30, 30))
    draw.text((px0 + phone_w - 150, py0 + 30), "🔋 📶", font=f_status, fill=(30, 30, 30))
    draw.text((px0 + 40, py0 + 90), "‹ Notes", font=inter(30), fill=(230, 160, 40))

    f_body = archivo(46)
    y = py0 + 190
    for i, ln in enumerate(lines):
        if i > active:
            continue
        wrapped = wrap_text(ln.upper(), f_body, phone_w - 100, draw)
        for wln in wrapped:
            draw.text((px0 + 50, y), wln, font=f_body, fill=(15, 15, 15))
            y += 60
        y += 26
    return img


# ---------------------------------------------------------------------------
# Template 4: fullscreen_title_hook
# ---------------------------------------------------------------------------
def render_fullscreen_title(lines: list[str], active: int) -> Image.Image:
    img = gradient_bg((16, 20, 46), (4, 5, 14))
    draw = ImageDraw.Draw(img)
    n = len(lines)
    y = H * 0.30
    for i, ln in enumerate(lines):
        if i > active:
            continue
        size = 150 if i == 0 else 84
        f = anton(size)
        color = YELLOW if i == n - 1 else "white"
        wrapped = wrap_text(ln.upper(), f, W - 100, draw)
        yb = draw_text_block(draw, (W / 2, y + size * 0.6), wrapped, f, color, W - 100,
                              stroke_width=7 if i == 0 else 5, stroke_fill="black")
        y = yb + 30
    return img


# ---------------------------------------------------------------------------
# Render orchestration
# ---------------------------------------------------------------------------
def build_content(template: str, headline: Optional[str], script: str, lines_override: Optional[list[str]]):
    if lines_override:
        lines = [l.strip() for l in lines_override if l.strip()]
    else:
        if template == "tweet_thread":
            lines = split_sentences(script, 5)
        elif template == "notes_app":
            lines = split_sentences(script, 5)
        elif template == "fullscreen_title_hook":
            lines = split_sentences(script, 4)
        else:
            lines = split_sentences(script, 4)
    if not lines:
        lines = [headline or "Watch this"]
    return lines


def render_frames(template: str, headline: str, lines: list[str], bg_img) -> list[Image.Image]:
    frames = []
    n = len(lines)
    for i in range(n):
        if template == "atmospheric_text_hook":
            frames.append(render_atmospheric(headline, lines, bg_img, i))
        elif template == "tweet_thread":
            frames.append(render_tweet_thread(lines, i))
        elif template == "notes_app":
            frames.append(render_notes_app(lines, i))
        else:
            frames.append(render_fullscreen_title(lines, i))
    return frames


def assemble_video(frames: list[Image.Image], durations: list[float], audio: np.ndarray, sr: int) -> bytes:
    with tempfile.TemporaryDirectory() as tmp:
        tmp = Path(tmp)
        list_path = tmp / "list.txt"
        with open(list_path, "w") as f:
            for i, (frame, dur) in enumerate(zip(frames, durations)):
                p = tmp / f"f{i:03d}.png"
                frame.convert("RGB").save(p, "PNG")
                f.write(f"file '{p.name}'\nduration {max(dur, 0.35):.3f}\n")
            # ffmpeg concat needs the last file repeated w/o duration
            last = tmp / f"f{len(frames)-1:03d}.png"
            f.write(f"file '{last.name}'\n")

        audio_path = tmp / "audio.wav"
        sf.write(str(audio_path), audio, sr)

        video_noaudio = tmp / "video_noaudio.mp4"
        cmd1 = [
            "ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", str(list_path),
            "-vf", f"fps={FPS},scale={W}:{H}", "-pix_fmt", "yuv420p", str(video_noaudio),
        ]
        subprocess.run(cmd1, cwd=tmp, check=True, capture_output=True)

        out_path = tmp / "out.mp4"
        cmd2 = [
            "ffmpeg", "-y", "-i", str(video_noaudio), "-i", str(audio_path),
            "-c:v", "libx264", "-preset", "veryfast", "-crf", "23",
            "-c:a", "aac", "-b:a", "160k", "-shortest", str(out_path),
        ]
        subprocess.run(cmd2, check=True, capture_output=True)
        return out_path.read_bytes()


def do_render(payload: dict) -> bytes:
    template = payload.get("template", "atmospheric_text_hook")
    if template not in TEMPLATES:
        template = "atmospheric_text_hook"
    voice = payload.get("voice", DEFAULT_VOICE)
    script = (payload.get("script") or payload.get("voice_script") or "").strip()
    headline = (payload.get("headline") or "").strip() or (script.split(".")[0][:60] if script else "Watch This")
    lines_override = payload.get("lines")
    bg_url = payload.get("background_image_url") or payload.get("background_image")

    lines = build_content(template, headline, script, lines_override)
    bg_img = load_background_image(bg_url) if template == "atmospheric_text_hook" else None
    if template == "atmospheric_text_hook" and bg_img is None:
        bg_img = gradient_bg((40, 32, 26), (10, 8, 8))

    # narrate: headline (for atmospheric/fullscreen) + each line as its own segment
    narrate_lines = lines if script else lines
    audio, sr, seg_durs = synth_segments(narrate_lines, voice)

    frames = render_frames(template, headline, lines, bg_img)
    mp4_bytes = assemble_video(frames, seg_durs, audio, sr)
    return mp4_bytes




# ---------------------------------------------------------------------------
# Template video routes (additive; does not affect /render, /tts, /health)
# ---------------------------------------------------------------------------
class TemplateRenderReq(BaseModel):
    template: str | None = "atmospheric_text_hook"
    script: str | None = None
    voice_script: str | None = None
    voice: str | None = DEFAULT_VOICE
    headline: str | None = None
    lines: list[str] | None = None
    background_image: str | None = None
    background_image_url: str | None = None


@app.get("/templates")
def list_templates():
    return {
        "templates": [
            {"id": "atmospheric_text_hook", "label": "Atmospheric text hook",
             "description": "Moody photo background with bold yellow/white hook lines and a Save-this-post CTA."},
            {"id": "tweet_thread", "label": "Tweet thread",
             "description": "Cascading fake-tweet cards revealing a thread, one tweet per beat."},
            {"id": "notes_app", "label": "Notes app",
             "description": "iPhone Notes screenshot look, lines appearing like a typed note."},
            {"id": "fullscreen_title_hook", "label": "Fullscreen title hook",
             "description": "Huge stacked title cards, escalating size, classic scroll-stopper."},
        ],
        "voices": KOKORO_VOICES,
    }


@app.post("/render-template")
def render_template(req: TemplateRenderReq):
    payload = {
        "template": req.template or "atmospheric_text_hook",
        "script": req.script or req.voice_script or "",
        "voice": req.voice or DEFAULT_VOICE,
        "headline": req.headline,
        "lines": req.lines,
        "background_image_url": req.background_image_url or req.background_image,
    }
    try:
        mp4 = do_render(payload)
        return Response(content=mp4, media_type="video/mp4")
    except Exception as e:
        import traceback
        traceback.print_exc()
        raise HTTPException(500, f"template render failed: {type(e).__name__}: {str(e)[:400]}")


# ===========================================================================
# v5: animated templates, music bed, custom uploaded media
# ===========================================================================
import io as _io
import math as _math
from pathlib import Path as _Path

import anim_templates as anim


def _download(url: str, suffix: str) -> str:
    r = requests.get(url, timeout=120)
    r.raise_for_status()
    p = os.path.join(tempfile.mkdtemp(), f"dl{suffix}")
    with open(p, "wb") as f:
        f.write(r.content)
    return p


def _media_frames(url: str, total: float, fps: int) -> list:
    """Decode an uploaded image or video into `total*fps` cover-fitted frames."""
    if not url:
        return []
    low = url.split("?")[0].lower()
    is_video = any(low.endswith(x) for x in (".mp4", ".mov", ".webm", ".m4v", ".avi"))
    n = max(int(total * fps), 1)
    if not is_video:
        try:
            r = requests.get(url, timeout=60)
            r.raise_for_status()
            img = anim.cover(Image.open(_io.BytesIO(r.content)).convert("RGB"))
            return [anim.ken_burns(img, k / n) for k in range(n)]
        except Exception as e:
            print("media image failed:", e, flush=True)
            return []
    try:
        src = _download(url, ".mp4")
        outdir = tempfile.mkdtemp()
        subprocess.run(
            ["ffmpeg", "-y", "-stream_loop", "-1", "-t", f"{total:.2f}", "-i", src,
             "-vf", f"fps={fps},scale={anim.SW}:{anim.SH}:force_original_aspect_ratio=increase,"
                    f"crop={anim.SW}:{anim.SH}",
             "-an", os.path.join(outdir, "m%05d.png")],
            check=True, capture_output=True,
        )
        files = sorted(_Path(outdir).glob("m*.png"))[:n]
        frames = [Image.open(f).convert("RGB") for f in files]
        while frames and len(frames) < n:
            frames.append(frames[-1])
        return frames
    except Exception as e:
        print("media video failed:", e, flush=True)
        return []


def _assemble_animated(frames, fps, audio, sr, music_url=None, music_volume=0.18,
                       media_audio_url=None, media_audio_volume=0.0,
                       brand_link=None, brand_text=None, brand_duration=0.0) -> bytes:
    with tempfile.TemporaryDirectory() as tmp:
        tmp = _Path(tmp)
        for i, fr in enumerate(frames):
            fr.convert("RGB").save(tmp / f"f{i:05d}.png", "PNG", compress_level=1)
        audio_path = tmp / "voice.wav"
        sf.write(str(audio_path), audio, sr)

        silent = tmp / "silent.mp4"
        subprocess.run(
            ["ffmpeg", "-y", "-framerate", str(fps), "-i", str(tmp / "f%05d.png"),
             "-vf", "scale=1080:1920:flags=lanczos", "-pix_fmt", "yuv420p",
             "-c:v", "libx264", "-preset", "veryfast", "-crf", "22", str(silent)],
            check=True, capture_output=True,
        )

        inputs = ["-i", str(silent), "-i", str(audio_path)]
        parts, mix_labels = [], ["[1:a]"]
        idx = 2
        if music_url:
            try:
                mp = _download(music_url, ".mp3")
                inputs += ["-i", mp]
                parts.append(f"[{idx}:a]volume={max(0.0, min(music_volume, 1.0)):.3f},"
                             f"afade=t=in:st=0:d=1.2,aloop=loop=-1:size=2e9[mus]")
                mix_labels.append("[mus]")
                idx += 1
            except Exception as e:
                print("music failed:", e, flush=True)
        if media_audio_url and media_audio_volume > 0:
            try:
                ap = _download(media_audio_url, ".mp4")
                inputs += ["-i", ap]
                parts.append(f"[{idx}:a]volume={min(media_audio_volume, 1.0):.3f}[mda]")
                mix_labels.append("[mda]")
                idx += 1
            except Exception as e:
                print("media audio failed:", e, flush=True)

        out = tmp / "out.mp4"
        cmd = ["ffmpeg", "-y"] + inputs
        if len(mix_labels) > 1:
            fc = ";".join(parts + [
                "".join(mix_labels) + f"amix=inputs={len(mix_labels)}:duration=first:"
                                      f"dropout_transition=0,alimiter=limit=0.95[aout]"
            ])
            cmd += ["-filter_complex", fc, "-map", "0:v", "-map", "[aout]"]
        else:
            cmd += ["-map", "0:v", "-map", "1:a"]
        cmd += ["-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-shortest", str(out)]
        subprocess.run(cmd, check=True, capture_output=True)

        if brand_duration and brand_duration > 0:
            outro = tmp / "outro.mp4"
            txt = (brand_text or brand_link or "").replace(":", "\\:").replace("'", "\u2019")
            link = (brand_link or "").replace(":", "\\:").replace("'", "\u2019")
            font = FALLBACK_FONT
            vf = (f"drawtext=fontfile={font}:text='{txt}':fontcolor=white:fontsize=64:"
                  f"x=(w-text_w)/2:y=(h-text_h)/2-70,"
                  f"drawtext=fontfile={font}:text='{link}':fontcolor=0xFFD400:fontsize=48:"
                  f"x=(w-text_w)/2:y=(h-text_h)/2+60")
            subprocess.run(
                ["ffmpeg", "-y", "-f", "lavfi", "-i", f"color=c=black:s=1080x1920:d={brand_duration}",
                 "-f", "lavfi", "-i", f"anullsrc=r=44100:cl=stereo:d={brand_duration}",
                 "-vf", vf, "-pix_fmt", "yuv420p", "-c:v", "libx264", "-preset", "veryfast",
                 "-c:a", "aac", "-shortest", str(outro)], check=True, capture_output=True)
            joined = tmp / "joined.mp4"
            lst = tmp / "cat.txt"
            lst.write_text(f"file '{out}'\nfile '{outro}'\n")
            subprocess.run(["ffmpeg", "-y", "-f", "concat", "-safe", "0", "-i", str(lst),
                            "-c:v", "libx264", "-preset", "veryfast", "-crf", "22",
                            "-c:a", "aac", str(joined)], check=True, capture_output=True)
            return joined.read_bytes()
        return out.read_bytes()


class AnimatedReq(BaseModel):
    template: str = "depth_parallax"
    script: str | None = None
    voice_script: str | None = None
    headline: str | None = None
    lines: list[str] | None = None
    voice: str | None = DEFAULT_VOICE
    max_lines: int | None = 6
    background_image_url: str | None = None
    media_url: str | None = None          # uploaded clip or image (custom templates)
    media_audio: bool | None = False
    media_audio_volume: float | None = 0.35
    music_url: str | None = None
    music_volume: float | None = 0.18
    brand_link: str | None = None
    brand_text: str | None = None
    brand_duration: float | None = 0.0
    fps: int | None = 24


@app.get("/animated-templates")
def animated_templates():
    return {"templates": anim.META, "voices": KOKORO_VOICES}


@app.post("/render-animated")
def render_animated(req: AnimatedReq):
    try:
        script = (req.script or req.voice_script or "").strip()
        lines = [l.strip() for l in (req.lines or []) if l.strip()]
        if not lines:
            lines = split_sentences(script, max(2, min(req.max_lines or 6, 8)))
        if not lines:
            lines = [req.headline or "Watch this"]
        headline = (req.headline or "").strip() or lines[0][:60]

        audio, sr, seg_durs = synth_segments(lines, req.voice or DEFAULT_VOICE)
        total = max(sum(seg_durs), 3.0)
        fps = max(12, min(req.fps or 24, 30))

        bg = None
        if req.background_image_url:
            try:
                r = requests.get(req.background_image_url, timeout=40)
                r.raise_for_status()
                bg = anim.cover(Image.open(_io.BytesIO(r.content)).convert("RGB"))
            except Exception as e:
                print("bg failed:", e, flush=True)

        media_frames = _media_frames(req.media_url, total, fps) if req.media_url else []
        template = req.template if req.template in anim.ANIMATED else (
            "custom_media" if media_frames else "depth_parallax")

        frames = anim.render_animation(template, headline, lines, seg_durs, total,
                                       bg=bg, media_frames=media_frames, fps=fps)
        mp4 = _assemble_animated(
            frames, fps, audio, sr,
            music_url=req.music_url,
            music_volume=req.music_volume if req.music_volume is not None else 0.18,
            media_audio_url=req.media_url if req.media_audio else None,
            media_audio_volume=(req.media_audio_volume or 0.35) if req.media_audio else 0.0,
            brand_link=req.brand_link, brand_text=req.brand_text,
            brand_duration=req.brand_duration or 0.0,
        )
        return Response(content=mp4, media_type="video/mp4")
    except Exception as e:
        import traceback
        traceback.print_exc()
        raise HTTPException(500, f"animated render failed: {type(e).__name__}: {str(e)[:400]}")

# ===========================================================================
# Automation 2 — source-clip pipeline
#   /clip/probe   : resolve a source URL -> duration, title, timed subtitles
#   /clip/render  : cut one segment, reframe to 9:16, burn captions,
#                   optionally mute the source and lay a Kokoro voice over it.
# Downloads are cached per video id in /tmp so a 100-clip batch downloads once.
# ===========================================================================
import glob as _glob
import hashlib as _hashlib

CLIP_CACHE = "/tmp/clipcache"
os.makedirs(CLIP_CACHE, exist_ok=True)


COOKIE_FILE = "/tmp/yt_cookies.txt"


def _cookie_file():
    raw = os.environ.get("YTDLP_COOKIES", "").strip()
    if not raw:
        return None
    if not os.path.exists(COOKIE_FILE):
        with open(COOKIE_FILE, "w", encoding="utf-8") as f:
            f.write(raw.replace("\\n", "\n"))
    return COOKIE_FILE


def _ydl_opts(extra: dict) -> dict:
    base = {
        "quiet": True,
        "no_warnings": True,
        "noplaylist": True,
        "cachedir": "/tmp/ytdlcache",
        "retries": 1,
        "fragment_retries": 2,
        "extractor_retries": 1,
        "socket_timeout": 12,
        "geo_bypass": True,
        "http_headers": {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
                          "(KHTML, like Gecko) Chrome/124.0 Safari/537.36",
            "Accept-Language": "en-US,en;q=0.9",
        },
    }
    ck = _cookie_file()
    if ck:
        base["cookiefile"] = ck
    proxy = os.environ.get("YTDLP_PROXY", "").strip()
    if proxy:
        base["proxy"] = proxy
    base.update(extra)
    return base


# --- multi-strategy YouTube access ------------------------------------------
# Datacenter IPs get throttled/blocked by the default web client, so we walk a
# ladder of player clients and remember the first one that works.
YT_STRATEGIES = [
    ("android_vr", {"youtube": {"player_client": ["android_vr"]}}),
    ("tv", {"youtube": {"player_client": ["tv"]}}),
    ("ios", {"youtube": {"player_client": ["ios"]}}),
    ("mweb", {"youtube": {"player_client": ["mweb"]}}),
    ("web_safari", {"youtube": {"player_client": ["web_safari"]}}),
    ("web_embedded", {"youtube": {"player_client": ["web_embedded"]}}),
    ("android", {"youtube": {"player_client": ["android"]}}),
    ("default", None),
]
STRATEGY_MEMO = "/tmp/yt_strategy.txt"


def _is_youtube(url: str) -> bool:
    return bool(re.search(r"(youtube\.com|youtu\.be)", url or "", re.I))


def _normalize_url(url: str) -> str:
    u = (url or "").strip()
    if "dropbox.com" in u:
        u = u.split("?")[0] + "?dl=1"
    if "drive.google.com" in u:
        m = re.search(r"/d/([A-Za-z0-9_-]+)", u) or re.search(r"[?&]id=([A-Za-z0-9_-]+)", u)
        if m:
            u = f"https://drive.google.com/uc?export=download&id={m.group(1)}"
    return u


def _ordered_strategies():
    order = list(YT_STRATEGIES)
    try:
        with open(STRATEGY_MEMO) as f:
            win = f.read().strip()
        order.sort(key=lambda s: 0 if s[0] == win else 1)
    except Exception:
        pass
    return order


def _remember(name: str):
    try:
        with open(STRATEGY_MEMO, "w") as f:
            f.write(name)
    except Exception:
        pass



def _ffprobe_json(target: str) -> dict:
    try:
        out = subprocess.check_output(
            ["ffprobe", "-v", "quiet", "-print_format", "json", "-show_format", "-show_streams", target],
            timeout=120,
        )
        return _json.loads(out.decode("utf-8", "ignore"))
    except Exception as e:
        raise HTTPException(400, f"ffprobe could not open this source: {type(e).__name__}: {str(e)[:200]}")


def _direct_probe(url: str) -> dict:
    """Duration/title for a plain media URL (upload, signed URL, CDN mp4)."""
    try:
        meta = _ffprobe_json(url)
    except Exception:
        local = _direct_download(url, os.path.join(CLIP_CACHE, _src_key(url)))
        meta = _ffprobe_json(local)
    dur = 0.0
    try:
        dur = float((meta.get("format") or {}).get("duration") or 0)
    except Exception:
        dur = 0.0
    if dur <= 0:
        for s in meta.get("streams", []):
            try:
                dur = max(dur, float(s.get("duration") or 0))
            except Exception:
                pass
    name = (meta.get("format") or {}).get("tags", {}).get("title")
    if not name:
        name = os.path.basename((url.split("?")[0] or "source")) or "Source video"
    return {"id": None, "title": name[:120], "duration": dur}


def _direct_download(url: str, dest_noext: str) -> str:
    """Stream a plain media URL to disk (no yt-dlp)."""
    dest = dest_noext + ".mp4"
    with requests.get(url, stream=True, timeout=120, headers={"User-Agent": "Mozilla/5.0"}) as r:
        r.raise_for_status()
        with open(dest, "wb") as f:
            for chunk in r.iter_content(1024 * 512):
                if chunk:
                    f.write(chunk)
    if os.path.getsize(dest) < 1024:
        raise HTTPException(400, "source download produced an empty file")
    return dest


def _run_with_timeout(fn, seconds: int):
    import concurrent.futures as _cf
    with _cf.ThreadPoolExecutor(max_workers=1) as ex:
        return ex.submit(fn).result(timeout=seconds)


def _ydl_try(url: str, extra: dict, download: bool):
    """Run yt-dlp across every strategy; return (info, strategy) or raise."""
    from yt_dlp import YoutubeDL
    url = _normalize_url(url)
    if not _is_youtube(url):
        opts = _ydl_opts(dict(extra))
        try:
            def _go():
                with YoutubeDL(opts) as ydl:
                    return ydl.extract_info(url, download=download)
            return _run_with_timeout(_go, 600 if download else 90), "direct"
        except Exception as e:
            raise HTTPException(400, f"direct source failed: {type(e).__name__}: {str(e)[:200]}")
    errors = []
    deadline = _time.time() + (600 if download else 75)
    per_try = 300 if download else 20
    for name, args in _ordered_strategies():
        left = deadline - _time.time()
        if left <= 5:
            errors.append("deadline reached before trying " + name)
            break
        opts = _ydl_opts(dict(extra))
        if args:
            opts["extractor_args"] = args
        try:
            def _go(o=opts):
                with YoutubeDL(o) as ydl:
                    return ydl.extract_info(url, download=download)
            info = _run_with_timeout(_go, min(per_try, max(8, int(left))))
            if info:
                _remember(name)
                return info, name
        except Exception as e:
            errors.append(f"{name}: {type(e).__name__}: {str(e)[:160]}")
            continue
    joined = " | ".join(errors[-4:])
    blocked = any(k in joined.lower() for k in
                  ("sign in to confirm", "bot", "403", "forbidden", "unavailable", "timeout"))
    hint = (" YouTube is blocking this server's IP. Upload the video file instead,"
            " or add YouTube cookies (YTDLP_COOKIES) to this Space.") if blocked else ""
    raise HTTPException(400, "all download methods failed -> " + joined + hint)


def _src_key(url: str) -> str:
    return _hashlib.sha1(url.encode("utf-8")).hexdigest()[:16]


def _parse_vtt(text: str) -> list:
    """Very small WebVTT parser -> [{start,end,text}] with de-duplicated lines."""
    cues, buf = [], None
    def ts(v):
        v = v.strip().replace(",", ".")
        parts = v.split(":")
        try:
            if len(parts) == 3:
                return int(parts[0]) * 3600 + int(parts[1]) * 60 + float(parts[2])
            if len(parts) == 2:
                return int(parts[0]) * 60 + float(parts[1])
        except Exception:
            return None
        return None
    for raw in text.splitlines():
        line = raw.strip()
        if "-->" in line:
            a, _, b = line.partition("-->")
            s, e = ts(a), ts(b.split(" ")[0] if " " in b.strip() else b)
            if s is None or e is None:
                buf = None
                continue
            buf = {"start": s, "end": e, "text": ""}
            cues.append(buf)
        elif line and buf is not None and not line.startswith(("WEBVTT", "Kind:", "Language:", "NOTE")):
            clean = re.sub(r"<[^>]+>", "", line).strip()
            if clean:
                buf["text"] = (buf["text"] + " " + clean).strip()
    out, seen = [], ""
    for c in cues:
        t = c["text"].strip()
        if not t or t == seen:
            continue
        seen = t
        out.append({"start": round(c["start"], 3), "end": round(c["end"], 3), "text": t[:220]})
    return out


def _fetch_subtitles(info: dict) -> list:
    tracks = {}
    tracks.update(info.get("subtitles") or {})
    for k, v in (info.get("automatic_captions") or {}).items():
        tracks.setdefault(k, v)
    pick = None
    for lang in ("en", "en-US", "en-GB", "en-orig"):
        if lang in tracks:
            pick = tracks[lang]
            break
    if not pick and tracks:
        pick = list(tracks.values())[0]
    if not pick:
        return []
    url = None
    for fmt in pick:
        if fmt.get("ext") in ("vtt", "srt"):
            url = fmt.get("url")
            break
    if not url:
        url = pick[0].get("url")
    if not url:
        return []
    try:
        r = requests.get(url, timeout=45)
        r.raise_for_status()
        return _parse_vtt(r.text)
    except Exception as e:
        print("subtitle fetch failed:", e, flush=True)
        return []


class ProbeReq(BaseModel):
    url: str


@app.post("/clip/probe")
def clip_probe(req: ProbeReq, request: Request):
    _check_auth(request)
    try:
        import yt_dlp  # noqa: F401
    except Exception as e:
        raise HTTPException(500, f"yt-dlp unavailable: {e}")
    url = _normalize_url(req.url)
    if not _is_youtube(url):
        d = _direct_probe(url)
        if not d["duration"]:
            raise HTTPException(400, "could not read the duration of this source")
        return {"video_id": None, "title": d["title"], "duration": d["duration"],
                "subtitles": [], "has_subtitles": False, "strategy": "ffprobe"}
    info, strategy = _ydl_try(
        url, {"skip_download": True, "writesubtitles": True, "writeautomaticsub": True}, False
    )
    subs = _fetch_subtitles(info)
    return {
        "video_id": info.get("id"),
        "title": info.get("title") or "Source video",
        "duration": float(info.get("duration") or 0),
        "subtitles": subs,
        "has_subtitles": bool(subs),
        "strategy": strategy,
    }


@app.post("/clip/diag")
def clip_diag(req: ProbeReq, request: Request):
    """Try every download method against a URL and report which ones work."""
    _check_auth(request)
    from yt_dlp import YoutubeDL
    url = _normalize_url(req.url)
    out = []
    for name, args in YT_STRATEGIES:
        opts = _ydl_opts({"skip_download": True})
        if args:
            opts["extractor_args"] = args
        try:
            with YoutubeDL(opts) as ydl:
                info = ydl.extract_info(url, download=False)
            out.append({"strategy": name, "ok": True, "title": info.get("title"),
                        "duration": info.get("duration")})
        except Exception as e:
            out.append({"strategy": name, "ok": False, "error": f"{type(e).__name__}: {str(e)[:200]}"})
    working = [o["strategy"] for o in out if o["ok"]]
    if working:
        _remember(working[0])
    return {"url": url, "working": working, "results": out}


def _ensure_source(url: str) -> str:
    key = _src_key(url)
    hits = sorted(_glob.glob(os.path.join(CLIP_CACHE, key + ".*")))
    for h in hits:
        if os.path.getsize(h) > 0:
            return h
    try:
        from yt_dlp import YoutubeDL
    except Exception as e:
        raise HTTPException(500, f"yt-dlp unavailable: {e}")
    if not _is_youtube(_normalize_url(url)):
        return _direct_download(_normalize_url(url), os.path.join(CLIP_CACHE, key))
    out = os.path.join(CLIP_CACHE, key + ".%(ext)s")
    _ydl_try(url, {
        "outtmpl": out,
        "format": "bestvideo[height<=720][ext=mp4]+bestaudio[ext=m4a]/best[height<=720]/best",
        "merge_output_format": "mp4",
        "concurrent_fragment_downloads": 4,
    }, True)
    hits = sorted(_glob.glob(os.path.join(CLIP_CACHE, key + ".*")))
    if not hits:
        raise HTTPException(500, "download produced no file")
    # keep the cache small — newest 3 sources only
    files = sorted(_glob.glob(os.path.join(CLIP_CACHE, "*")), key=os.path.getmtime, reverse=True)
    for old in files[6:]:
        try: os.remove(old)
        except OSError: pass
    return hits[0]


def _ass_escape(t: str) -> str:
    return t.replace("\\", "\\\\").replace("{", "(").replace("}", ")").replace("\n", " ")


def _ass_time(t: float) -> str:
    t = max(0.0, t)
    h = int(t // 3600); m = int((t % 3600) // 60); s = t % 60
    return f"{h:d}:{m:02d}:{s:05.2f}"


ASS_FONTS = {"Anton": "Anton", "BebasNeue": "Bebas Neue", "ArchivoBlack": "Archivo Black",
             "Inter": "Liberation Sans", "Montserrat": "Liberation Sans"}


def _build_ass(cues: list, preset: str, font: str, color: str, accent: str, path: str,
               font_size: int = 0, position: float = -1.0, uppercase: bool = True):
    fontname = ASS_FONTS.get(font, "Liberation Sans")
    primary = hex_to_ass(color, "&H00FFFFFF")
    outline_col = "&H00000000"
    size = {"clean_caps": 78, "karaoke_pop": 84, "split_frame": 66,
            "blur_fill": 74, "bottom_bar": 62}.get(preset, 74)
    align, marginv = (2, 430) if preset != "split_frame" else (2, 240)
    if preset == "bottom_bar":
        marginv = 250
    if font_size and font_size > 0:
        size = max(28, min(140, int(font_size)))
    if position is not None and position >= 0:
        # position: 0 = bottom of frame, 1 = top of frame
        marginv = int(max(60, min(1700, position * 1920)))
    header = f"""[Script Info]
ScriptType: v4.00+
PlayResX: 1080
PlayResY: 1920
WrapStyle: 2
ScaledBorderAndShadow: yes

[V4+ Styles]
Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding
Style: Cap,{fontname},{size},{primary},{hex_to_ass(accent, '&H004AD5FF')},{outline_col},&H80000000,-1,0,0,0,100,100,0,0,1,6,2,{align},70,70,{marginv},1

[Events]
Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text
"""
    lines = []
    for c in cues:
        text = _ass_escape(str(c.get("text", "")).strip())
        if not text:
            continue
        if uppercase:
            text = text.upper()
        if preset == "karaoke_pop":
            text = "{\\fad(60,60)\\fscx104\\fscy104}" + text
        else:
            text = "{\\fad(50,50)}" + text
        lines.append(
            f"Dialogue: 0,{_ass_time(float(c['start']))},{_ass_time(float(c['end']))},Cap,,0,0,0,,{text}"
        )
    with open(path, "w", encoding="utf-8") as f:
        f.write(header + "\n".join(lines) + "\n")


def _frame_filter(preset: str, accent: str) -> str:
    """Reframe a 16:9 source into a 1080x1920 canvas per template preset."""
    if preset == "blur_fill":
        return ("[0:v]split=2[bg][fg];"
                "[bg]scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,"
                "gblur=sigma=32,eq=brightness=-0.08[bgb];"
                "[fg]scale=1080:-2[fgs];"
                "[bgb][fgs]overlay=(W-w)/2:(H-h)/2[v]")
    if preset == "split_frame":
        return ("[0:v]scale=1080:-2[fgs];"
                "color=c=0x0B0B0F:s=1080x1920:d=1[bg];"
                "[bg][fgs]overlay=0:220:shortest=1[v]")
    if preset == "bottom_bar":
        return ("[0:v]scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920[vc];"
                f"color=c={accent.replace('#','0x')}:s=1080x14:d=1[bar];"
                "[vc][bar]overlay=0:1780:shortest=1[v]")
    # clean_caps / karaoke_pop -> straight center crop
    return "[0:v]scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920[v]"


def _fx_chain(req) -> str:
    """Cool-edit chain applied to the reframed 1080x1920 video."""
    k = max(0.2, min(2.0, float(getattr(req, "fx_intensity", 1.0) or 1.0)))
    parts = []
    if getattr(req, "fx_zoom", False):
        z = 0.10 * k
        parts.append(
            "crop=w='iw/(1+%.3f*mod(t,6)/6)':h='ih/(1+%.3f*mod(t,6)/6)':"
            "x='(iw-ow)/2':y='(ih-oh)/2',scale=1080:1920" % (z, z)
        )
    if getattr(req, "fx_shake", False):
        a = 6 * k
        parts.append(
            "crop=w=iw-24:h=ih-24:x='12+%.2f*sin(2*PI*t*7)':y='12+%.2f*cos(2*PI*t*5)',"
            "scale=1080:1920" % (a, a)
        )
    if getattr(req, "fx_grade", True):
        parts.append("eq=contrast=%.3f:saturation=%.3f:gamma=0.98" % (1 + 0.10 * k, 1 + 0.18 * k))
    if getattr(req, "fx_glitch", False):
        sh = int(round(6 * k))
        parts.append("rgbashift=rh=%d:bh=-%d:enable='lt(mod(t,2.6),0.09)'" % (sh, sh))
        parts.append("hue=s=0:enable='lt(mod(t,5.2),0.05)'")
    if getattr(req, "fx_flash", False):
        parts.append("eq=brightness=%.2f:enable='lt(mod(t,4),0.07)'" % (0.30 * k))
    if getattr(req, "fx_grain", False):
        parts.append("noise=alls=%d:allf=t+u" % max(2, int(round(8 * k))))
    if getattr(req, "fx_vignette", False):
        parts.append("vignette=PI/5")
    return ",".join(parts)

class ClipReq(BaseModel):
    url: str
    start: float = 0
    duration: float = 15
    preset: str = "clean_caps"
    font: str = "Anton"
    caption_color: str = "#FFFFFF"
    accent: str = "#FFD54A"
    captions: Optional[list] = None      # [{start,end,text}] in SOURCE time
    mute_source: bool = False
    voice_text: Optional[str] = None     # Kokoro narration laid over the clip
    voice: str = "af_bella"
    music_volume: float = 0.25
    font_size: int = 0
    caption_position: float = -1.0   # 0 = bottom, 1 = top
    uppercase: bool = True
    fx_zoom: bool = False
    fx_shake: bool = False
    fx_glitch: bool = False
    fx_grain: bool = False
    fx_flash: bool = False
    fx_vignette: bool = False
    fx_grade: bool = True
    fx_intensity: float = 1.0


@app.post("/clip/render")
def clip_render(req: ClipReq, request: Request):
    _check_auth(request)
    src = _ensure_source(req.url)
    job = str(uuid.uuid4())
    work = tempfile.mkdtemp(prefix="clip_")
    out = os.path.join(RENDERS_DIR, f"{job}.mp4")
    try:
        dur = max(3.0, min(90.0, float(req.duration or 15)))
        start = max(0.0, float(req.start or 0))

        # ---- captions, shifted into clip-relative time ----
        vf = _frame_filter(req.preset, req.accent)
        fx = _fx_chain(req)
        vlab = "[v]"
        if fx:
            vf += f";[v]{fx}[vfx]"
            vlab = "[vfx]"
        cues = []
        for c in (req.captions or []):
            try:
                s = float(c.get("start", 0)) - start
                e = float(c.get("end", 0)) - start
            except Exception:
                continue
            if e <= 0.05 or s >= dur:
                continue
            cues.append({"start": max(0.0, s), "end": min(dur, e), "text": c.get("text", "")})
        if cues:
            ass = os.path.join(work, "caps.ass")
            _build_ass(cues, req.preset, req.font, req.caption_color, req.accent, ass,
                       req.font_size, req.caption_position, req.uppercase)
            vf += f";{vlab}ass={ass}[vout]"
        else:
            vf += f";{vlab}null[vout]"

        cmd = ["ffmpeg", "-y", "-ss", f"{start:.2f}", "-t", f"{dur:.2f}", "-i", src]

        voice_path = None
        if req.voice_text and req.voice_text.strip():
            wav, sr = synth(req.voice_text.strip(), req.voice or "af_bella")
            voice_path = os.path.join(work, "vo.wav")
            sf.write(voice_path, wav, sr)
            cmd += ["-i", voice_path]

        filters = [vf]
        if voice_path and req.mute_source:
            amap = "[1:a]aresample=48000,apad[aout]"
            filters.append(amap)
        elif voice_path:
            filters.append(
                f"[0:a]volume={max(0.0, min(1.0, req.music_volume))},aresample=48000[bed];"
                "[1:a]aresample=48000[vo];[bed][vo]amix=inputs=2:duration=first:dropout_transition=0[aout]"
            )
        elif req.mute_source:
            filters.append("anullsrc=channel_layout=stereo:sample_rate=48000[aout]")
        else:
            filters.append("[0:a]aresample=48000[aout]")

        cmd += ["-filter_complex", ";".join(filters), "-map", "[vout]", "-map", "[aout]"]
        cmd += ["-t", f"{dur:.2f}", "-r", "30", "-c:v", "libx264", "-preset", "veryfast",
                "-crf", "23", "-pix_fmt", "yuv420p", "-c:a", "aac", "-b:a", "128k",
                "-movflags", "+faststart", out]
        proc = subprocess.run(cmd, capture_output=True, timeout=900)
        if proc.returncode != 0 or not os.path.exists(out):
            raise HTTPException(500, f"ffmpeg failed: {proc.stderr.decode()[-500:]}")
        with open(out, "rb") as f:
            data = f.read()
        return Response(content=data, media_type="video/mp4")
    finally:
        shutil.rmtree(work, ignore_errors=True)
        try: os.remove(out)
        except OSError: pass


class PeaksReq(BaseModel):
    url: str
    window: float = 15
    count: int = 10


@app.post("/clip/peaks")
def clip_peaks(req: PeaksReq, request: Request):
    """Free 'best moment' detection: loudness energy peaks across the source."""
    _check_auth(request)
    src = _ensure_source(req.url)
    win = max(5.0, min(60.0, float(req.window or 15)))
    probe = subprocess.run(
        ["ffprobe", "-v", "error", "-show_entries", "format=duration",
         "-of", "default=nw=1:nk=1", src], capture_output=True, timeout=120)
    try:
        duration = float(probe.stdout.decode().strip())
    except Exception:
        duration = 0.0
    proc = subprocess.run(
        ["ffmpeg", "-i", src, "-af", "astats=metadata=1:reset=1,ametadata=print:key=lavfi.astats.Overall.RMS_level:file=-",
         "-f", "null", "-"], capture_output=True, timeout=900)
    text = proc.stdout.decode(errors="ignore") + proc.stderr.decode(errors="ignore")
    samples = []
    t = None
    for line in text.splitlines():
        line = line.strip()
        if line.startswith("frame:"):
            m = re.search(r"pts_time:([0-9.]+)", line)
            t = float(m.group(1)) if m else None
        elif "RMS_level=" in line and t is not None:
            try:
                samples.append((t, float(line.split("=")[-1])))
            except Exception:
                pass
    scored = []
    if samples:
        step = max(1.0, win / 3)
        pos = 0.0
        end = duration or (samples[-1][0])
        while pos + win <= end:
            vals = [v for (ts, v) in samples if pos <= ts < pos + win and v > -90]
            if vals:
                scored.append({"start": round(pos, 2), "score": round(sum(vals) / len(vals), 2)})
            pos += step
    scored.sort(key=lambda x: x["score"], reverse=True)
    picks = []
    for c in scored:
        if all(abs(c["start"] - p["start"]) >= win for p in picks):
            picks.append(c)
        if len(picks) >= int(req.count or 10):
            break
    picks.sort(key=lambda x: x["start"])
    return {"duration": duration, "window": win, "peaks": picks}


class FetchReq(BaseModel):
    url: str
    mode: str = "video"      # video | audio
    height: int = 1080


DL_CACHE = os.path.join(CLIP_CACHE, "dl")
os.makedirs(DL_CACHE, exist_ok=True)


@app.post("/clip/info")
def clip_info(req: ProbeReq, request: Request):
    """Lightweight metadata for the downloader tool (title, thumb, qualities)."""
    _check_auth(request)
    info, strategy = _ydl_try(req.url, {"skip_download": True}, False)
    heights = sorted({int(f.get("height") or 0) for f in (info.get("formats") or [])
                      if f.get("height")}, reverse=True)
    return {
        "title": info.get("title") or "Video",
        "uploader": info.get("uploader") or info.get("channel") or "",
        "duration": float(info.get("duration") or 0),
        "thumbnail": info.get("thumbnail"),
        "heights": [h for h in heights if h <= 2160][:8],
        "strategy": strategy,
    }


@app.post("/clip/fetch")
def clip_fetch(req: FetchReq, request: Request):
    """Full-file download (Crayo-style YouTube downloader): mp4 or mp3."""
    _check_auth(request)
    key = _src_key(f"{req.url}|{req.mode}|{req.height}")
    out = os.path.join(DL_CACHE, key + ".%(ext)s")
    if req.mode == "audio":
        extra = {"outtmpl": out, "format": "bestaudio/best",
                 "postprocessors": [{"key": "FFmpegExtractAudio",
                                     "preferredcodec": "mp3", "preferredquality": "192"}]}
    else:
        h = max(240, min(2160, int(req.height or 1080)))
        extra = {"outtmpl": out, "merge_output_format": "mp4",
                 "concurrent_fragment_downloads": 4,
                 "format": (f"bestvideo[height<={h}][ext=mp4]+bestaudio[ext=m4a]/"
                            f"bestvideo[height<={h}]+bestaudio/best[height<={h}]/best")}
    info, _strategy = _ydl_try(req.url, extra, True)
    hits = [p for p in _glob.glob(os.path.join(DL_CACHE, key + ".*")) if not p.endswith(".part")]
    hits.sort(key=os.path.getmtime, reverse=True)
    if not hits:
        raise HTTPException(500, "download produced no file")
    path = hits[0]
    for old in sorted(_glob.glob(os.path.join(DL_CACHE, "*")), key=os.path.getmtime, reverse=True)[4:]:
        try: os.remove(old)
        except OSError: pass
    title = re.sub(r"[^A-Za-z0-9 ._-]", "", info.get("title") or "video")[:120]
    media = "audio/mpeg" if req.mode == "audio" else "video/mp4"
    return FileResponse(path, media_type=media, headers={"X-Title": title})


@app.get("/clip/health")
def clip_health():
    try:
        import yt_dlp
        v = yt_dlp.version.__version__
    except Exception as e:
        v = f"missing: {e}"
    return {"ok": True, "yt_dlp": v}


# ===========================================================================
# FX Studio — advanced "cool edits" generator (kinetic captions, speed ramps,
# whip transitions, flash/shake/glitch, grain, music bed + Kokoro narration).
# Additive: every existing renderer endpoint above is untouched, so this Space
# keeps serving as the backup renderer for the main automation.
# ===========================================================================
try:
    import fx_engine as _fx
except Exception as _e:  # pragma: no cover
    _fx = None
    print("fx_engine unavailable:", _e, flush=True)


class FxShot(BaseModel):
    image_url: str | None = None
    text: str | None = ""
    say: str | None = None
    seconds: float | None = None


class FxReq(BaseModel):
    shots: list[FxShot]
    voice: str | None = None
    narrate: bool = True
    music_url: str | None = None
    music_volume: float | None = 0.22
    fps: int | None = 24
    accent: str | None = "#12E1B6"
    font_size: int | None = 62
    uppercase: bool | None = True
    caption_position: float | None = 0.72
    shake: bool | None = True
    glitch: bool | None = True
    flash: bool | None = True
    grain: bool | None = True


@app.get("/fx/health")
def fx_health():
    return {"ok": _fx is not None, "engine": "fx-v1"}


@app.post("/fx/render")
def fx_render(req: FxReq):
    if _fx is None:
        raise HTTPException(500, "fx engine not loaded")
    try:
        shots = [s for s in req.shots if s][:12]
        if not shots:
            raise HTTPException(400, "no shots")
        fps = max(12, min(req.fps or 24, 30))
        voice = req.voice or DEFAULT_VOICE

        say_lines = [(s.say or s.text or "").strip() for s in shots]
        if req.narrate and any(say_lines):
            audio, sr, durations = synth_segments([l or "." for l in say_lines], voice)
            durations = [max(1.1, min(d, 6.0)) for d in durations]
        else:
            durations = [float(s.seconds or 2.2) for s in shots]
            sr = 24000
            audio = np.zeros(int(sr * sum(durations)), dtype=np.float32)

        style = {
            "accent": req.accent or "#12E1B6",
            "font_size": req.font_size or 62,
            "uppercase": req.uppercase if req.uppercase is not None else True,
            "caption_position": req.caption_position if req.caption_position is not None else 0.72,
            "shake": req.shake, "glitch": req.glitch,
            "flash": req.flash, "grain": req.grain,
        }
        frames = _fx.build_frames(
            [{"image_url": s.image_url, "text": s.text or ""} for s in shots],
            durations, fps, style, lambda size: anton(size),
        )
        mp4 = _assemble_animated(
            frames, fps, audio, sr,
            music_url=req.music_url,
            music_volume=req.music_volume if req.music_volume is not None else 0.22,
        )
        return Response(content=mp4, media_type="video/mp4")
    except HTTPException:
        raise
    except Exception as e:
        import traceback
        traceback.print_exc()
        raise HTTPException(500, f"fx render failed: {type(e).__name__}: {str(e)[:400]}")