File size: 67,899 Bytes
851e5ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Task API routes using refactored architecture.
"""

from fastapi import APIRouter, Depends, HTTPException, Request
from fastapi.encoders import jsonable_encoder
from fastapi.responses import FileResponse, RedirectResponse, StreamingResponse
from starlette.background import BackgroundTask
from ...media_storage import MediaStorage, STORAGE_ERRORS, is_s3, media_work
from sqlalchemy.ext.asyncio import AsyncSession
from sse_starlette.sse import EventSourceResponse
from pathlib import Path
from contextlib import aclosing
import json
import logging
from typing import Dict, Any, Optional
import inspect
import re
import secrets
import math
import asyncio
import hashlib
import time
from ...utils.async_helpers import run_in_thread
from ... import clip_archive

from ...repositories.generation_allowance_guard import generation_allowance_guard, GenerationAllowanceBusy
from ...repositories.task_run_guard import task_run_guard, TaskRunBusy
from ...repositories.task_repository import TaskRepository
from ...database import get_db
from ...database import AsyncSessionLocal
from ...services.task_service import TaskService
from ...services.video_service import VideoService
from ...media.upload_ingest import foreign_upload
from ...repositories.upload_repository import get_stored_upload
from ...services.billing_service import BillingService, BillingLimitExceeded
from ...auth_headers import resolve_authenticated_user_id
from ...feature_flags import client_platform
from ...workers.job_queue import JobQueue
from ...workers.progress import ProgressTracker
from ...config import get_config
from ...youtube_utils import async_get_youtube_video_info, canonical_youtube_url
from ...youtube_proxy import YouTubeGeoRestrictedError
from ...stream_source import (
    PREFLIGHT_DEADLINE_SECONDS as STREAM_PREFLIGHT_DEADLINE_SECONDS,
    StreamSourceError,
    fetch_stream_info,
)
from ...font_registry import is_font_accessible
from ...clip_duration import normalize_clip_length, validate_clip_length
from ...clip_cleanup import (
    new_task_cleanup_settings,
    normalize_clip_cleanup_settings,
    updated_cleanup_settings,
)
from ...video_utils import VALID_OUTPUT_FORMATS
from ...admin_auth import require_admin_user, user_is_admin
from ...source_submission import SourceAttempt
from ...workflows.contracts import workflow_spec_from_task
from ...workflows.errors import WorkflowRequestError
from ...workflows.options import (
    check_source_duration,
    parse_workflow_request,
    workflow_not_available,
    allowed_workflows,
    workflow_allowed_for,
    workflows_info,
)
import redis.asyncio as redis
from ...clip_editor import export_with_preset, EXPORT_PRESETS

logger = logging.getLogger(__name__)
router = APIRouter(prefix="/tasks", tags=["tasks"])


async def _preflight_youtube_source(url: str, duration_limit: int) -> Dict[str, Any]:
    """Check duration before creating a task or consuming a generation."""
    # wait_for cancels the awaiting task when this elapses. A yt-dlp call already
    # running inside asyncio.to_thread can finish in the background.
    timeout_seconds = get_config().youtube_preflight_timeout_seconds
    try:
        metadata = await asyncio.wait_for(
            async_get_youtube_video_info(url, deadline=time.monotonic() + timeout_seconds),
            timeout=timeout_seconds,
        )
        duration = (metadata or {}).get("duration")
        if isinstance(duration, bool) or not isinstance(duration, (int, float)):
            raise ValueError("Missing video duration")
        if not math.isfinite(duration) or duration <= 0:
            raise ValueError("Invalid video duration")
    except YouTubeGeoRestrictedError as exc:
        raise HTTPException(
            status_code=422,
            detail={
                "code": "YOUTUBE_GEO_RESTRICTED",
                "message": f"{exc} No minutes were used.",
            },
        ) from None
    except TimeoutError:
        logger.warning(
            "YouTube metadata preflight timed out after %s seconds",
            timeout_seconds,
        )
        raise HTTPException(
            status_code=503,
            detail={
                "code": "VIDEO_METADATA_TIMEOUT",
                "message": (
                    "Checking this YouTube video's length timed out. Please try again "
                    "shortly or upload the video file. No minutes were used."
                ),
            },
        ) from None
    except Exception:
        raise HTTPException(
            status_code=503,
            detail={
                "code": "VIDEO_METADATA_UNAVAILABLE",
                "message": (
                    "We couldn't verify this video's length. Please try again shortly "
                    "or upload the video file. No minutes were used."
                ),
            },
        ) from None

    if duration > duration_limit:
        raise HTTPException(
            status_code=422,
            detail={
                "code": "VIDEO_TOO_LONG",
                "message": (
                    f"This video is {duration / 60:.1f} minutes long. Your plan allows "
                    f"YouTube videos up to {duration_limit / 60:g} minutes. "
                    "Choose a shorter video. No minutes were used."
                ),
                "duration_seconds": duration,
                "max_duration_seconds": duration_limit,
            },
        )
    return metadata

async def _preflight_stream_source(url: str, source: str, duration_limit: int) -> Dict[str, Any]:
    try:
        # One overall deadline: yt-dlp (proxy, direct) metadata, then the cheap
        # metadata actor only when both fail. The full-video actor never runs
        # here; the worker owns the rest of the fallback chain.
        metadata = await asyncio.wait_for(
            run_in_thread(fetch_stream_info, url, deadline_seconds=STREAM_PREFLIGHT_DEADLINE_SECONDS),
            timeout=STREAM_PREFLIGHT_DEADLINE_SECONDS + 5,
        )
        duration = (metadata or {}).get("duration")
        if isinstance(duration, bool) or not isinstance(duration, (int, float)) or not math.isfinite(duration) or duration <= 0:
            raise ValueError("Invalid video duration")
    except StreamSourceError as exc:
        raise HTTPException(status_code=422, detail={"code": "VIDEO_UNAVAILABLE", "message": str(exc)}) from None
    except Exception:
        raise HTTPException(status_code=503, detail={"code": "VIDEO_METADATA_UNAVAILABLE", "message": "We couldn't fetch this video, try again later. No minutes were used."}) from None
    if duration > duration_limit:
        raise HTTPException(status_code=422, detail={"code": "VIDEO_TOO_LONG", "message": f"This {source.title()} video is {duration / 60:.1f} minutes long. Your plan allows videos up to {duration_limit / 60:g} minutes. Choose a shorter VOD or clip. No minutes were used.", "duration_seconds": duration, "max_duration_seconds": duration_limit})
    return metadata


def _stream_resolution_metadata(metadata: Dict[str, Any] | None) -> Dict[str, Any]:
    """Persist a preflight actor result so the worker does not pay for it again."""
    if not metadata or not metadata.get("media_url") or not str(metadata.get("provider", "")).startswith("apify_"):
        return {}
    return {
        "stream_resolution": {
            key: metadata.get(key)
            for key in ("provider", "id", "title", "duration", "media_url")
        }
        | {"resolved_at": time.time()}
    }


async def _preflight_upload_source(url: str, user_id: str, duration_limit: int, db=None) -> float:
    """Read an uploaded video's length so its minutes are charged up front."""
    reference = None
    if db is not None and isinstance(url, str) and url.startswith("upload://") and not url.startswith("upload://s3/"):
        row = await get_stored_upload(db, url)
        reference = row.storage_reference if row is not None else None
    try:
        if reference:
            duration = await run_in_thread(VideoService.probe_upload_duration, url, user_id, reference)
        else:
            duration = await run_in_thread(VideoService.probe_upload_duration, url, user_id)
        if not math.isfinite(duration) or duration <= 0:
            raise ValueError("Invalid video duration")
    except Exception:
        raise HTTPException(
            status_code=422,
            detail={
                "code": "VIDEO_METADATA_UNAVAILABLE",
                "message": (
                    "We couldn't read this video's length. Check that the file is a "
                    "playable video and upload it again. No minutes were used."
                ),
            },
        ) from None

    if duration > duration_limit:
        raise HTTPException(
            status_code=422,
            detail={
                "code": "VIDEO_TOO_LONG",
                "message": (
                    f"This video is {duration / 60:.1f} minutes long. Uploads can be "
                    f"up to {duration_limit / 60:g} minutes. No minutes were used."
                ),
                "duration_seconds": duration,
                "max_duration_seconds": duration_limit,
            },
        )
    return duration


def _normalize_font_size(value: Any, default: int = 24) -> Optional[int]:
    if value is None or (isinstance(value, str) and not value.strip()):
        return None
    try:
        parsed = int(value)
    except (TypeError, ValueError):
        parsed = default
    return max(12, min(72, parsed))


def _normalize_font_color(value: Any, default: str = "#FFFFFF") -> Optional[str]:
    if value is None or (isinstance(value, str) and not value.strip()):
        return None
    if isinstance(value, str) and re.match(r"^#[0-9A-Fa-f]{6}$", value):
        return value.upper()
    return default


def _normalize_font_family(value: Any) -> Optional[str]:
    if isinstance(value, str) and value.strip():
        return value.strip()
    return None


async def _read_json_object(request: Request) -> Dict[str, Any]:
    try:
        payload = await request.json()
    except (ValueError, UnicodeDecodeError):
        raise HTTPException(status_code=400, detail="Invalid JSON body")
    if not isinstance(payload, dict):
        raise HTTPException(status_code=400, detail="Request body must be an object")
    return payload


def _finite_number(value: Any, name: str) -> float:
    try:
        number = float(value)
    except (TypeError, ValueError, OverflowError):
        raise ValueError(f"{name} must be a finite number")
    if isinstance(value, bool) or not math.isfinite(number):
        raise ValueError(f"{name} must be a finite number")
    return number


async def _get_user_id_from_headers(request: Request, db: AsyncSession) -> str:
    """Resolve the authenticated user ID from an API key or signed frontend headers."""
    config = get_config()
    return await resolve_authenticated_user_id(request, db, config)


async def _load_task_source_metadata(task_id: str, db: AsyncSession | None = None) -> Dict[str, Any]:
    if db is not None:
        metadata = await TaskRepository.load_source_metadata(db, task_id)
        if metadata:
            return metadata
    runtime_config = get_config()
    redis_client = redis.Redis(
        host=runtime_config.redis_host,
        port=runtime_config.redis_port,
        password=runtime_config.redis_password,
        decode_responses=True,
    )
    try:
        payload = await redis_client.get(f"task_source:{task_id}")
    except Exception as exc:
        logger.warning("Unable to load task source metadata for %s: %s", task_id, exc)
        return {}
    finally:
        await redis_client.aclose()

    if not payload:
        return {}

    try:
        return json.loads(payload)
    except json.JSONDecodeError:
        return {}


async def _save_task_source_metadata(
    task_id: str, payload: Dict[str, Any], db: AsyncSession | None = None
) -> None:
    if db is not None:
        await TaskRepository.save_source_metadata(db, task_id, payload)
    runtime_config = get_config()
    redis_client = redis.Redis(
        host=runtime_config.redis_host,
        port=runtime_config.redis_port,
        password=runtime_config.redis_password,
        decode_responses=True,
    )
    try:
        await redis_client.set(
            f"task_source:{task_id}",
            json.dumps(payload),
            ex=60 * 60 * 24 * 7,
        )
    except Exception as exc:
        logger.warning("Unable to save task source metadata for %s: %s", task_id, exc)
    finally:
        await redis_client.aclose()


def _merge_task_source_metadata(
    existing: Dict[str, Any] | None,
    *,
    source_url: Any = None,
    source_type: Any = None,
    output_format: Any = None,
    add_subtitles: Any = None,
    cleanup_settings: Dict[str, Any] | None = None,
) -> Dict[str, Any]:
    merged = dict(existing or {})

    if isinstance(source_url, str) and source_url:
        merged["url"] = source_url
    if isinstance(source_type, str) and source_type:
        merged["source_type"] = source_type
    if output_format in VALID_OUTPUT_FORMATS:
        merged["output_format"] = output_format
    if isinstance(add_subtitles, bool):
        merged["add_subtitles"] = add_subtitles
    if cleanup_settings:
        merged.update(cleanup_settings)

    return merged


# Matches the admin dashboard's live queue: queued, processing, and the
# pre-queue pending default. Finished tasks stay visible only to their owner.
ADMIN_READABLE_TASK_STATUSES = {"queued", "processing", "pending"}


async def _load_task_for_user(
    request: Request, task_service: TaskService, db: AsyncSession, task_id: str
):
    user_id = await _get_user_id_from_headers(request, db)
    task = await task_service.task_repo.get_task_by_id(db, task_id)
    if not task:
        raise HTTPException(status_code=404, detail="Task not found")
    return user_id, task


async def _require_task_owner(
    request: Request, task_service: TaskService, db: AsyncSession, task_id: str
):
    """Ensure authenticated user owns the task."""
    user_id, task = await _load_task_for_user(request, task_service, db, task_id)

    if task.get("user_id") != user_id:
        raise HTTPException(status_code=403, detail="Not authorized for this task")

    return task


async def _authorize_task_reader(
    request: Request, task_service: TaskService, db: AsyncSession, task_id: str
):
    """Owner, or an admin reading a task that is still active. Returns (user_id, task)."""
    user_id, task = await _load_task_for_user(request, task_service, db, task_id)

    if task.get("user_id") == user_id:
        return user_id, task
    if task.get("status") in ADMIN_READABLE_TASK_STATUSES and await user_is_admin(
        db, user_id
    ):
        return user_id, task

    raise HTTPException(status_code=403, detail="Not authorized for this task")


async def _require_task_reader(
    request: Request, task_service: TaskService, db: AsyncSession, task_id: str
):
    """Owner, or an admin reading a task that is still active."""
    _user_id, task = await _authorize_task_reader(request, task_service, db, task_id)
    return task


PUBLIC_TASK_FIELDS = {
    "source_title",
    "source_type",
    "status",
    "clips_count",
    "workflow",
    "created_at",
    "updated_at",
}
PUBLIC_CLIP_FIELDS = {
    "id",
    "filename",
    "start_time",
    "end_time",
    "duration",
    "text",
    "relevance_score",
    "reasoning",
    "clip_order",
    "created_at",
    "virality_score",
    "hook_score",
    "engagement_score",
    "value_score",
    "shareability_score",
    "hook_type",
    "hook_title",
    "part_number",
    "workflow_role",
}


def _pick(value: Any, keys: tuple[str, ...]) -> Dict[str, Any]:
    if not isinstance(value, dict):
        return {}
    return {key: value[key] for key in keys if key in value}


def _picked_list(value: Any, keys: tuple[str, ...]) -> list[Dict[str, Any]]:
    if not isinstance(value, list):
        return []
    return [_pick(item, keys) for item in value if isinstance(item, dict)]


def _public_workflow_plan(plan: Any) -> Optional[Dict[str, Any]]:
    """The share-safe subset of ``tasks.workflow_plan``: titles and labels, no
    unit ids, ranges, summaries, captions or errors."""
    if not isinstance(plan, dict):
        return None
    public = _pick(plan, ("version", "workflow", "title"))
    if "notes" in plan:
        public["notes"] = _picked_list(plan["notes"], ("code", "params"))
    if "parts" in plan:
        public["parts"] = _picked_list(plan["parts"], ("part_number", "title"))
    if "points" in plan:
        public["points"] = _picked_list(plan["points"], ("label",))
    if "beats" in plan:
        public["beats"] = _picked_list(plan["beats"], ("role",))
    if "topic" in plan:
        public["topic"] = _pick(plan["topic"], ("query", "canonical", "coverage", "found"))
    return public


def _public_workflow_meta(meta: Any) -> Dict[str, Any]:
    """The share-safe subset of ``generated_clips.workflow_meta``."""
    public = _pick(meta, ("title", "ends_on", "part_count"))
    if isinstance(meta, dict) and "points" in meta:
        public["points"] = _picked_list(meta["points"], ("label", "kind", "range_index", "output_start"))
    if isinstance(meta, dict) and "beats" in meta:
        public["beats"] = _picked_list(meta["beats"], ("role", "range_index", "output_start"))
    return public


def _build_public_task(task: Dict[str, Any], share_token: str) -> Dict[str, Any]:
    """Return only fields intended for anyone holding the share URL."""
    public_task = {key: task.get(key) for key in PUBLIC_TASK_FIELDS}
    public_task["workflow_plan"] = _public_workflow_plan(task.get("workflow_plan"))
    public_task["clips"] = []
    for clip in task.get("clips", []):
        public_clip = {key: clip.get(key) for key in PUBLIC_CLIP_FIELDS}
        public_clip["workflow_meta"] = _public_workflow_meta(clip.get("workflow_meta"))
        public_clip["video_url"] = (
            f"/tasks/shared/{share_token}/clips/{clip['id']}/file"
        )
        public_task["clips"].append(public_clip)
    return public_task


@router.get("/")
async def list_tasks(
    request: Request, db: AsyncSession = Depends(get_db), limit: int = 50
):
    """
    Get all tasks for the authenticated user.
    """
    user_id = await _get_user_id_from_headers(request, db)

    try:
        task_service = TaskService(db)
        tasks = await task_service.get_user_tasks(user_id, limit)

        return {"tasks": tasks, "total": len(tasks)}

    except Exception as e:
        logger.error(f"Error retrieving user tasks: {e}")
        raise HTTPException(status_code=500, detail=f"Error retrieving tasks: {str(e)}")


def _request_idempotency_key(request: Request) -> str:
    headers = getattr(request, "headers", None)
    getter = getattr(headers, "get", None)
    if getter is None:
        return ""
    raw = getter("idempotency-key")
    if raw is None or not str(raw).strip():
        return ""
    key = str(raw).strip()
    if not re.fullmatch(r"[A-Za-z0-9._:-]{8,200}", key):
        raise HTTPException(status_code=400, detail="Invalid idempotency key")
    return key


def _upload_request_key(request: Request, url: str, options: Dict[str, Any]) -> str | None:
    """Stable id for one upload plus the options that change the job.

    A missing header still matches an identical retry. YouTube and other
    links are not deduped here.
    """
    header = _request_idempotency_key(request)
    if not isinstance(url, str) or not url.startswith("upload://"):
        return None
    payload = json.dumps(options, sort_keys=True, separators=(",", ":"))
    return hashlib.sha256(f"{header}\n{payload}".encode()).hexdigest()


def _queued_upload_task(task_id: str, job_id: str | None) -> Dict[str, Any]:
    return {
        "task_id": task_id,
        "job_id": job_id or task_id,
        "message": "Task already queued",
    }


@router.post("/")
async def create_task(request: Request, db: AsyncSession = Depends(get_db)):
    """
    Create a new task and enqueue it for processing.
    Returns task_id immediately.
    """
    attempt = SourceAttempt(request, db)
    try:
        response = await _create_task(request, db, attempt)
    except HTTPException as exc:
        await attempt.rejected(exc.status_code, exc.detail)
        raise
    await attempt.accepted()
    return response


async def _create_task(request: Request, db: AsyncSession, attempt: SourceAttempt):
    data = await _read_json_object(request)

    raw_source = data.get("source")
    if isinstance(raw_source, dict):
        attempt.note_url(raw_source.get("url"))
    if not isinstance(raw_source, dict) or not isinstance(raw_source.get("url"), str) or not raw_source["url"].strip():
        raise HTTPException(status_code=400, detail="Source URL is required")
    user_id = await _get_user_id_from_headers(request, db)
    attempt.note_user(user_id)
    attempt.note_workflow(data.get("workflow"))

    # Get font options
    font_options = data.get("font_options", {})
    if not isinstance(font_options, dict):
        raise HTTPException(status_code=400, detail="font_options must be an object")
    font_family = _normalize_font_family(font_options.get("font_family"))
    font_size = _normalize_font_size(font_options.get("font_size"))
    font_color = _normalize_font_color(font_options.get("font_color"))
    caption_template = data.get("caption_template", "default")
    include_broll = data.get("include_broll") is True
    runtime_config = get_config()
    processing_mode = data.get(
        "processing_mode", runtime_config.default_processing_mode
    )
    if processing_mode not in {"fast", "balanced", "quality"}:
        processing_mode = runtime_config.default_processing_mode
    output_format = data.get("output_format", "vertical")
    if output_format not in VALID_OUTPUT_FORMATS:
        output_format = "vertical"
    add_subtitles = data.get("add_subtitles", True)
    if not isinstance(add_subtitles, bool):
        add_subtitles = True
    try:
        clip_length = validate_clip_length(data.get("clip_length", "auto"))
    except ValueError as exc:
        raise HTTPException(status_code=422, detail=str(exc)) from None
    try:
        workflow_spec = parse_workflow_request(data, clip_length)
    except WorkflowRequestError as exc:
        raise HTTPException(status_code=exc.status, detail=exc.to_detail()) from None
    if not workflow_spec.legacy and not await workflow_allowed_for(
        db, user_id, workflow_spec.workflow, platform=client_platform(request)
    ):
        error = workflow_not_available()
        raise HTTPException(status_code=error.status, detail=error.to_detail())
    workflow_options = workflow_spec.options.to_json()
    cleanup_settings = new_task_cleanup_settings(data)
    if not raw_source or not raw_source.get("url"):
        raise HTTPException(status_code=400, detail="Source URL is required")

    upload_options = {
        "url": raw_source["url"],
        "font_family": font_family,
        "font_size": font_size,
        "font_color": font_color,
        "caption_template": caption_template,
        "include_broll": include_broll,
        "processing_mode": processing_mode,
        "output_format": output_format,
        "add_subtitles": add_subtitles,
        "clip_length": clip_length,
        "cleanup_settings": cleanup_settings,
    }
    if not workflow_spec.legacy:
        # Plain highlights keep their existing key. The key is a hash, so topic
        # and instructions never leave the process.
        upload_options["workflow"] = workflow_spec.workflow
        upload_options["workflow_options"] = workflow_options
    upload_request_key = _upload_request_key(request, raw_source["url"], upload_options)
    if upload_request_key and db is not None:
        existing = await TaskRepository.find_recent_upload_task(db, user_id, upload_request_key)
        if existing is not None:
            return _queued_upload_task(existing.id, existing.job_id)

    try:
        billing_service = BillingService(db)
        billing = await billing_service.assert_can_create_task(user_id)

        task_service = TaskService(db)

        try:
            source_type = task_service.video_service.determine_source_type(raw_source["url"])
        except ValueError as exc:
            # Only rejected http(s) stream URLs are a 422 validation error.
            # Local paths and other non-URL sources keep the historic 404.
            if not str(raw_source["url"]).strip().lower().startswith(("http://", "https://")):
                raise
            raise HTTPException(status_code=422, detail=str(exc)) from None
        if source_type == "youtube":
            # Shorts, live, share and embed links all become watch?v=ID, so the
            # stored source, downloads and caches see one form per video.
            raw_source["url"] = canonical_youtube_url(raw_source["url"]) or raw_source["url"]
        source_title = raw_source.get("title")
        stream_metadata: Dict[str, Any] | None = None
        if source_type == "youtube":
            metadata = await _preflight_youtube_source(
                raw_source["url"], billing["max_youtube_duration_seconds"]
            )
            source_title = source_title or metadata.get("title") or "YouTube Video"
            duration_seconds = float(metadata["duration"])
        elif source_type in {"twitch", "kick"}:
            stream_metadata = await _preflight_stream_source(raw_source["url"], source_type, billing["max_youtube_duration_seconds"])
            source_title = source_title or stream_metadata.get("title") or f"{source_type.title()} Video"
            duration_seconds = float(stream_metadata["duration"])
        else:
            if await foreign_upload(db, raw_source["url"], user_id):
                raise HTTPException(status_code=404, detail="Video file not found")
            duration_seconds = await _preflight_upload_source(
                raw_source["url"], user_id, billing["max_upload_duration_seconds"], db
            )

        try:
            check_source_duration(workflow_spec, duration_seconds)
        except WorkflowRequestError as exc:
            raise HTTPException(status_code=exc.status, detail=exc.to_detail()) from None

        async with generation_allowance_guard(
            db, user_id, enabled=runtime_config.monetization_enabled
        ):
            await billing_service.assert_can_create_task(user_id, duration_seconds)
            # Create task
            task_id = await task_service.create_task_with_source(
                user_id=user_id,
                url=raw_source["url"],
                title=source_title,
                font_family=font_family,
                font_size=font_size,
                font_color=font_color,
                caption_template=caption_template,
                include_broll=include_broll,
                processing_mode=processing_mode,
                source_duration_seconds=math.ceil(duration_seconds),
                upload_request_key=upload_request_key,
                workflow=workflow_spec.workflow,
                workflow_options=workflow_options,
            )
            if getattr(task_service, "reused_upload_task", False):
                return _queued_upload_task(
                    task_id, getattr(task_service, "reused_upload_job_id", None)
                )

            try:
                # Persist retry options before submitting the job; Redis remains a legacy cache.
                processing_job_id = f"{task_id}:{secrets.token_hex(16)}"
                await _save_task_source_metadata(
                    task_id,
                    _merge_task_source_metadata(
                        {
                            "processing_job_id": processing_job_id,
                            "clip_length": clip_length,
                            **_stream_resolution_metadata(stream_metadata),
                        },
                        source_url=raw_source["url"],
                        source_type=source_type,
                        output_format=output_format,
                        add_subtitles=add_subtitles,
                        cleanup_settings=cleanup_settings,
                    ),
                    db=db,
                )

                # Enqueue job for worker
                queue_adapter = getattr(request.app.state, "queue_adapter", JobQueue)
                job_id = await queue_adapter.enqueue_processing_job(
                    "process_video_task",
                    processing_mode,
                    task_id,
                    raw_source["url"],
                    source_type,
                    user_id,
                    font_family,
                    font_size,
                    font_color,
                    caption_template,
                    processing_mode,
                    output_format,
                    add_subtitles,
                    cleanup_settings,
                    clip_length,
                    _job_id=processing_job_id,
                )

            except Exception:
                await task_service.task_repo.update_task_status(
                    db, task_id, "error", progress=0,
                    progress_message="Unable to queue processing. Please retry this generation.",
                    expected_statuses=["queued"],
                )
                raise

            logger.info(f"Task {task_id} created and job {job_id} enqueued")

            return {
                "task_id": task_id,
                "job_id": job_id,
                "message": "Task created and queued for processing",
            }

    except GenerationAllowanceBusy as e:
        raise HTTPException(status_code=409, detail=str(e), headers={"Retry-After": "1"})
    except HTTPException:
        raise
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except BillingLimitExceeded as e:
        raise HTTPException(
            status_code=402,
            detail={
                "code": "SUBSCRIPTION_REQUIRED",
                "message": e.summary.get("reason") or "Choose a paid plan to process videos.",
                "billing": jsonable_encoder(e.summary),
            },
        )
    except Exception as e:
        logger.error(f"Error creating task: {e}")
        raise HTTPException(status_code=500, detail=f"Error creating task: {str(e)}")


@router.get("/billing/summary")
async def get_billing_summary(request: Request, db: AsyncSession = Depends(get_db)):
    """Get monetization status and current usage for authenticated user."""
    user_id = await _get_user_id_from_headers(request, db)

    try:
        billing_service = BillingService(db)
        summary = await billing_service.get_usage_summary(user_id)
        return summary
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))
    except Exception as e:
        logger.error(f"Error retrieving billing summary: {e}")
        raise HTTPException(
            status_code=500,
            detail=f"Error retrieving billing summary: {str(e)}",
        )


@router.get("/workflows")
async def get_workflows(request: Request, db: AsyncSession = Depends(get_db)):
    """What the authenticated user can make on this platform, with each workflow's limits."""
    user_id = await _get_user_id_from_headers(request, db)
    return workflows_info(await allowed_workflows(db, user_id, platform=client_platform(request)))


@router.get("/shared/{share_token}")
async def get_shared_task(share_token: str, db: AsyncSession = Depends(get_db)):
    """Get the read-only generation result associated with an opaque share token."""
    task_service = TaskService(db)
    task_id = await task_service.task_repo.get_shared_task_id(db, share_token)
    if not task_id:
        raise HTTPException(status_code=404, detail="Shared result not found")

    task = await task_service.get_task_with_clips(task_id)
    if not task or task.get("status") != "completed":
        raise HTTPException(status_code=404, detail="Shared result not found")

    return _build_public_task(task, share_token)


@router.get("/shared/{share_token}/clips/{clip_id}/file")
async def get_shared_clip_file(
    share_token: str,
    clip_id: str,
    download: bool = False,
    db: AsyncSession = Depends(get_db, scope="function"),
):
    """Serve one shared clip only when the bearer share token is enabled."""
    task_service = TaskService(db)
    task_id = await task_service.task_repo.get_shared_task_id(db, share_token)
    if not task_id:
        raise HTTPException(status_code=404, detail="Shared result not found")

    clip = await task_service.clip_repo.get_clip_by_id(db, clip_id)
    if not clip or clip.get("task_id") != task_id:
        raise HTTPException(status_code=404, detail="Clip not found")

    if is_s3(clip["file_path"]):
        await db.close()
        url = await run_in_thread(MediaStorage().signed_url, clip["file_path"], clip["filename"], attachment=download)
        return RedirectResponse(url, status_code=307, headers={"Cache-Control": "private, no-store"})
    clip_path = Path(clip["file_path"])
    if not clip_path.exists():
        raise HTTPException(status_code=404, detail="Clip file not found")

    return FileResponse(
        path=str(clip_path),
        media_type="video/mp4",
        filename=clip["filename"],
        content_disposition_type="attachment" if download else "inline",
        headers={"Cache-Control": "private, no-store"},
    )


@router.get("/{task_id}")
async def get_task(
    task_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Get task details."""
    try:
        task_service = TaskService(db)
        await _require_task_reader(request, task_service, db, task_id)
        task = await task_service.get_task_with_clips(task_id)

        if not task:
            raise HTTPException(status_code=404, detail="Task not found")

        return task

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error retrieving task: {e}")
        raise HTTPException(status_code=500, detail=f"Error retrieving task: {str(e)}")


@router.get("/{task_id}/clips")
async def get_task_clips(
    task_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Get all clips for a task."""
    try:
        task_service = TaskService(db)
        await _require_task_reader(request, task_service, db, task_id)
        task = await task_service.get_task_with_clips(task_id)

        if not task:
            raise HTTPException(status_code=404, detail="Task not found")

        return {
            "task_id": task_id,
            "clips": task.get("clips", []),
            "total_clips": len(task.get("clips", [])),
        }

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error retrieving clips: {e}")
        raise HTTPException(status_code=500, detail=f"Error retrieving clips: {str(e)}")


@router.post("/{task_id}/share")
async def share_task(
    task_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Create or re-enable a stable, read-only share URL for a completed task."""
    task_service = TaskService(db)
    task = await _require_task_owner(request, task_service, db, task_id)
    if task.get("status") != "completed":
        raise HTTPException(
            status_code=409, detail="Only completed generations can be shared"
        )

    share_token = await task_service.task_repo.enable_sharing(
        db, task_id, secrets.token_urlsafe(32)
    )
    if not share_token:
        raise HTTPException(status_code=404, detail="Task not found")

    return {
        "share_token": share_token,
        "share_path": f"/share/{share_token}",
    }


@router.delete("/{task_id}/share")
async def unshare_task(
    task_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Disable the public URL while preserving the private generation result."""
    task_service = TaskService(db)
    await _require_task_owner(request, task_service, db, task_id)
    await task_service.task_repo.disable_sharing(db, task_id)
    return {"message": "Share link disabled"}


@router.get("/{task_id}/progress")
async def get_task_progress_sse(task_id: str, request: Request):
    """
    SSE endpoint for real-time progress updates.
    Streams progress updates as Server-Sent Events.
    """

    async with AsyncSessionLocal() as local_db:
        task_service = TaskService(local_db)
        task = await _require_task_reader(request, task_service, local_db, task_id)

    async def event_generator():
        """Generate SSE events for task progress."""
        # Send initial task status
        yield {
            "event": "status",
            "data": json.dumps(
                {
                    "task_id": task_id,
                    "status": task.get("status"),
                    "progress": task.get("progress", 0),
                    "message": task.get("progress_message", ""),
                }
            ),
        }

        # If task is already completed or error, close connection
        if task.get("status") in ["completed", "error", "cancelled"]:
            yield {"event": "close", "data": json.dumps({"status": task.get("status")})}
            return

        # Connect to Redis for real-time updates
        runtime_config = get_config()
        redis_client = redis.Redis(
            host=runtime_config.redis_host,
            port=runtime_config.redis_port,
            password=runtime_config.redis_password,
            decode_responses=True,
        )

        try:
            # Subscribe to progress updates
            async with aclosing(ProgressTracker.subscribe_to_progress(redis_client, task_id)) as updates:
                async for progress_data in updates:
                    event_type = progress_data.get("event_type", "progress")
                    yield {"event": event_type, "data": json.dumps(progress_data)}

                    # Close connection if task is done
                    if progress_data.get("status") in ["completed", "error", "cancelled"]:
                        yield {
                            "event": "close",
                            "data": json.dumps({"status": progress_data.get("status")}),
                        }
                        break
        finally:
            await redis_client.aclose()

    return EventSourceResponse(event_generator())


@router.patch("/{task_id}")
async def update_task(
    task_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Update task details (title)."""
    try:
        data = await _read_json_object(request)
        title = data.get("title")

        if not isinstance(title, str) or not title.strip():
            raise HTTPException(status_code=400, detail="Title is required")

        task_service = TaskService(db)

        task = await _require_task_owner(request, task_service, db, task_id)

        # Update source title
        await task_service.source_repo.update_source_title(db, task["source_id"], title)

        return {"message": "Task updated successfully", "task_id": task_id}

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error updating task: {e}")
        raise HTTPException(status_code=500, detail=f"Error updating task: {str(e)}")


@router.delete("/{task_id}")
async def delete_task(
    task_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Delete a task and all its associated clips."""
    try:
        user_id = await _get_user_id_from_headers(request, db)
        task_service = TaskService(db)

        # Get task to verify ownership
        task = await task_service.task_repo.get_task_by_id(db, task_id)
        if not task:
            raise HTTPException(status_code=404, detail="Task not found")

        if task["user_id"] != user_id:
            raise HTTPException(
                status_code=403, detail="Not authorized to delete this task"
            )

        # Delete clips and task
        await task_service.delete_task(task_id)

        return {"message": "Task deleted successfully"}

    except HTTPException:
        raise
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Error deleting task: {e}")
        raise HTTPException(status_code=500, detail=f"Error deleting task: {str(e)}")


@router.delete("/{task_id}/clips/{clip_id}")
async def delete_clip(
    task_id: str, clip_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Delete a specific clip."""
    try:
        user_id = await _get_user_id_from_headers(request, db)
        task_service = TaskService(db)

        # Verify task ownership
        task = await task_service.task_repo.get_task_by_id(db, task_id)
        if not task:
            raise HTTPException(status_code=404, detail="Task not found")

        if task["user_id"] != user_id:
            raise HTTPException(
                status_code=403, detail="Not authorized to delete this clip"
            )

        clip = await task_service.clip_repo.get_clip_by_id(db, clip_id)
        if not clip or clip["task_id"] != task_id:
            raise HTTPException(status_code=404, detail="Clip not found")

        await task_service.delete_clip(task_id, clip_id)

        return {"message": "Clip deleted successfully"}

    except HTTPException:
        raise
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        logger.error(f"Error deleting clip: {e}")
        raise HTTPException(status_code=500, detail=f"Error deleting clip: {str(e)}")


@router.get("/{task_id}/clips/{clip_id}/file")
async def get_clip_file(
    task_id: str,
    clip_id: str,
    request: Request,
    download: bool = False,
    db: AsyncSession = Depends(get_db, scope="function"),
):
    """Serve a clip file after verifying task ownership."""
    try:
        task_service = TaskService(db)
        await _require_task_reader(request, task_service, db, task_id)
        clip = await task_service.clip_repo.get_clip_by_id(db, clip_id)
        if not clip or clip.get("task_id") != task_id:
            raise HTTPException(status_code=404, detail="Clip not found")

        if is_s3(clip["file_path"]):
            await db.close()
            url = await run_in_thread(MediaStorage().signed_url, clip["file_path"], clip["filename"], attachment=download)
            return RedirectResponse(url, status_code=307, headers={"Cache-Control": "private, no-store"})
        clip_path = Path(clip["file_path"])
        if not clip_path.exists():
            raise HTTPException(status_code=404, detail="Clip file not found")

        # Release the DB connection before streaming: FastAPI keeps a
        # `Depends(get_db)` session open for the full response lifetime, and a
        # FileResponse can take many seconds (large file, slow client, range
        # scrubbing). Holding it leaves the read-only transaction above as
        # "idle in transaction" in Postgres for the whole transfer, which
        # exhausts the connection pool under concurrent playback.
        await db.close()

        return FileResponse(
            path=str(clip_path),
            media_type="video/mp4",
            filename=clip["filename"],
            content_disposition_type="attachment" if download else "inline",
            headers={"Cache-Control": "private, no-store"},
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error serving clip file: {e}")
        raise HTTPException(status_code=500, detail=f"Error serving clip file: {str(e)}")


async def _prepare_clip_archive(request: Request, db: AsyncSession, task_id: str):
    """Authorize like a single-clip download and list the clip files that exist."""
    task_service = TaskService(db)
    user_id, task = await _authorize_task_reader(request, task_service, db, task_id)
    clips = await task_service.clip_repo.get_clips_by_task(db, task_id)
    # Release the DB connection before storage lookups and the long stream;
    # see get_clip_file.
    await db.close()
    try:
        entries = await run_in_thread(
            clip_archive.resolve_entries, clips, MediaStorage(), task.get("workflow")
        )
    except STORAGE_ERRORS:
        logger.exception("Could not list clip files for task %s", task_id)
        raise HTTPException(
            status_code=503,
            detail="Clip storage is unavailable right now. Please try again shortly.",
        ) from None
    if not entries:
        raise HTTPException(
            status_code=404,
            detail="This generation has no clip files to download.",
        )
    return user_id, task, entries


@router.get("/{task_id}/clips/zip/preflight")
async def preflight_clip_archive(
    task_id: str,
    request: Request,
    db: AsyncSession = Depends(get_db, scope="function"),
):
    """Check a ZIP download would start, so a browser can surface errors first."""
    user_id, task, entries = await _prepare_clip_archive(request, db, task_id)
    if await clip_archive.archive_in_progress(user_id):
        raise HTTPException(
            status_code=429,
            detail="A ZIP download of your clips is already in progress. Wait for it to finish, then try again.",
        )
    return {
        "filename": clip_archive.archive_filename(task.get("source_title")),
        "clip_count": len(entries),
        "total_bytes": sum(entry.size for entry in entries),
    }


@router.get("/{task_id}/clips/zip")
async def download_clip_archive(
    task_id: str,
    request: Request,
    db: AsyncSession = Depends(get_db, scope="function"),
):
    """Stream every existing clip of the task as one ZIP, built on the fly."""
    user_id, task, entries = await _prepare_clip_archive(request, db, task_id)
    try:
        slot = await clip_archive.ArchiveSlot(user_id).acquire()
    except clip_archive.ClipArchiveBusy as exc:
        raise HTTPException(status_code=429, detail=str(exc)) from None
    filename = clip_archive.archive_filename(task.get("source_title"))
    return StreamingResponse(
        clip_archive.stream_with_slot(entries, MediaStorage(), slot),
        media_type="application/zip",
        headers={
            "Content-Disposition": clip_archive.content_disposition(filename),
            "Cache-Control": "private, no-store",
            # Let nginx pass chunks through instead of buffering the archive.
            "X-Accel-Buffering": "no",
        },
    )


@router.patch("/{task_id}/clips/{clip_id}")
async def trim_clip(
    task_id: str, clip_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Trim clip boundaries and regenerate clip file."""
    try:
        payload = await _read_json_object(request)
        start_offset = _finite_number(payload.get("start_offset", 0), "start_offset")
        end_offset = _finite_number(payload.get("end_offset", 0), "end_offset")

        if start_offset < 0 or end_offset < 0:
            raise HTTPException(status_code=400, detail="Offsets must be non-negative")

        task_service = TaskService(db)
        await _require_task_owner(request, task_service, db, task_id)
        updated_clip = await task_service.trim_clip(
            task_id, clip_id, start_offset, end_offset
        )
        return {"clip": updated_clip}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error trimming clip: {e}")
        raise HTTPException(status_code=500, detail=f"Error trimming clip: {str(e)}")


@router.post("/{task_id}/clips/{clip_id}/split")
async def split_clip(
    task_id: str, clip_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Split a clip into two clips."""
    try:
        payload = await _read_json_object(request)
        split_time = _finite_number(payload.get("split_time", 0), "split_time")
        if split_time <= 0:
            raise HTTPException(
                status_code=400, detail="split_time must be greater than zero"
            )

        task_service = TaskService(db)
        await _require_task_owner(request, task_service, db, task_id)
        result = await task_service.split_clip(task_id, clip_id, split_time)
        return result
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error splitting clip: {e}")
        raise HTTPException(status_code=500, detail=f"Error splitting clip: {str(e)}")


@router.post("/{task_id}/clips/merge")
async def merge_clips(
    task_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Merge multiple clips into one clip."""
    try:
        payload = await _read_json_object(request)
        clip_ids = payload.get("clip_ids") or []
        if not isinstance(clip_ids, list) or any(not isinstance(cid, str) or not cid for cid in clip_ids):
            raise HTTPException(status_code=400, detail="clip_ids must be an array")

        task_service = TaskService(db)
        await _require_task_owner(request, task_service, db, task_id)
        result = await task_service.merge_clips(task_id, clip_ids)
        return result
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error merging clips: {e}")
        raise HTTPException(status_code=500, detail=f"Error merging clips: {str(e)}")


@router.patch("/{task_id}/clips/{clip_id}/captions")
async def update_clip_captions(
    task_id: str, clip_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Update clip caption text, timing style and highlighted words."""
    try:
        payload = await _read_json_object(request)
        caption_text = str(payload.get("caption_text", "")).strip()
        position = str(payload.get("position", "bottom"))
        highlight_words = payload.get("highlight_words") or []
        if not isinstance(highlight_words, list):
            raise HTTPException(
                status_code=400, detail="highlight_words must be an array"
            )

        font_size = payload.get("font_size")
        if font_size is not None:
            font_size = _finite_number(font_size, "font_size")
            if not math.isfinite(font_size) or not 12 <= font_size <= 72:
                raise ValueError("Font size must be between 12 and 72")
            font_size = int(font_size)
        position_y = payload.get("position_y")
        if position_y is not None:
            position_y = _finite_number(position_y, "position_y")
            if not math.isfinite(position_y) or not 0.1 <= position_y <= 0.85:
                raise ValueError("Caption position must be between 0.1 and 0.85")
        if position not in {"top", "middle", "bottom"}:
            raise ValueError("Invalid caption position")

        task_service = TaskService(db)
        await _require_task_owner(request, task_service, db, task_id)
        updated_clip = await task_service.update_clip_captions(
            task_id,
            clip_id,
            caption_text,
            position,
            [str(word) for word in highlight_words],
            font_size=font_size,
            position_y=position_y,
        )
        return {"clip": updated_clip}
    except YouTubeGeoRestrictedError as exc:
        raise HTTPException(
            status_code=422,
            detail={"code": "YOUTUBE_GEO_RESTRICTED", "message": str(exc)},
        ) from None
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error updating captions: {e}")
        raise HTTPException(
            status_code=500, detail=f"Error updating captions: {str(e)}"
        )


@router.post("/{task_id}/clips/{clip_id}/regenerate")
async def regenerate_clip(
    task_id: str, clip_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Regenerate a single clip after editing timing values."""
    try:
        payload = await _read_json_object(request)
        start_offset = _finite_number(payload.get("start_offset", 0), "start_offset")
        end_offset = _finite_number(payload.get("end_offset", 0), "end_offset")

        task_service = TaskService(db)
        await _require_task_owner(request, task_service, db, task_id)
        updated_clip = await task_service.trim_clip(
            task_id, clip_id, start_offset, end_offset
        )
        return {"clip": updated_clip, "message": "Clip regenerated successfully"}
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error regenerating clip: {e}")
        raise HTTPException(
            status_code=500, detail=f"Error regenerating clip: {str(e)}"
        )


@router.post("/{task_id}/settings")
async def apply_task_settings(
    task_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Update task-level styling settings and optionally apply to all existing clips."""
    try:
        payload = await _read_json_object(request)
        font_family = _normalize_font_family(payload.get("font_family"))
        font_size = _normalize_font_size(payload.get("font_size"))
        font_color = _normalize_font_color(payload.get("font_color"))
        caption_template = payload.get("caption_template", "default")
        apply_to_existing = bool(payload.get("apply_to_existing", False))

        task_service = TaskService(db)
        await _require_task_owner(request, task_service, db, task_id)
        task_record = await task_service.task_repo.get_task_by_id(db, task_id)
        if not task_record:
            raise HTTPException(status_code=404, detail="Task not found")
        # Like cleanup below: an omitted flag keeps the task's B-roll setting,
        # so a styling-only update doesn't strip B-roll from every clip.
        include_broll = (
            payload["include_broll"] is True
            if "include_broll" in payload
            else bool(task_record.get("include_broll"))
        )

        # Cleanup fields the request omits keep the task's stored values, so a
        # styling-only update can't silently switch pause/filler cleanup off.
        metadata = await _load_task_source_metadata(task_id, db=db)
        cleanup_settings = updated_cleanup_settings(payload, metadata)
        if font_family is not None and not is_font_accessible(
            font_family, task_record["user_id"]
        ):
            raise HTTPException(
                status_code=400, detail="Selected font is not available"
            )
        task = await task_service.update_task_settings(
            task_id,
            font_family,
            font_size,
            font_color,
            caption_template,
            include_broll,
            apply_to_existing,
            cleanup_settings,
        )
        # Settings edits must not write the job ID captured before a lengthy
        # regeneration: a concurrent resume may have reserved a newer attempt.
        metadata.pop("processing_job_id", None)
        await _save_task_source_metadata(
            task_id,
            _merge_task_source_metadata(
                metadata,
                source_url=metadata.get("url") or task_record.get("source_url"),
                source_type=metadata.get("source_type") or task_record.get("source_type"),
                output_format=metadata.get("output_format") or task.get("output_format"),
                add_subtitles=(
                    metadata["add_subtitles"]
                    if isinstance(metadata.get("add_subtitles"), bool)
                    else task.get("add_subtitles")
                ),
                cleanup_settings=cleanup_settings,
            ),
            db=db,
        )
        return {"task": task, "message": "Task settings updated"}
    except YouTubeGeoRestrictedError as exc:
        raise HTTPException(
            status_code=422,
            detail={"code": "YOUTUBE_GEO_RESTRICTED", "message": str(exc)},
        ) from None
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error updating task settings: {e}")
        raise HTTPException(
            status_code=500, detail=f"Error updating task settings: {str(e)}"
        )


@router.get("/{task_id}/clips/{clip_id}/export")
@media_work
async def export_clip(
    task_id: str,
    clip_id: str,
    request: Request,
    preset: str = "tiktok",
    db: AsyncSession = Depends(get_db, scope="function"),
):
    """Export clip with a social platform preset."""
    try:
        preset_name = preset.lower().strip()
        if preset_name not in EXPORT_PRESETS:
            raise HTTPException(
                status_code=400,
                detail=f"Invalid preset. Use one of: {', '.join(EXPORT_PRESETS.keys())}",
            )

        task_service = TaskService(db)
        await _require_task_reader(request, task_service, db, task_id)
        clip = await task_service.clip_repo.get_clip_by_id(db, clip_id)
        if not clip or clip.get("task_id") != task_id:
            raise HTTPException(status_code=404, detail="Clip not found")

        from pathlib import Path

        # Release the DB connection before the (potentially multi-minute) ffmpeg
        # re-encode and file streaming below — see get_clip_file for why holding
        # it here turns into "idle in transaction" connection-pool exhaustion.
        await db.close()

        runtime_config = get_config()
        output_path = await run_in_thread(
            export_with_preset,
            await run_in_thread(MediaStorage().local_path, clip["file_path"]),
            Path(runtime_config.temp_dir) / "exports",
            preset_name,
        )

        download_name = f"{Path(clip['filename']).stem}_{preset_name}.mp4"
        return FileResponse(
            path=str(output_path), media_type="video/mp4", filename=download_name,
            background=BackgroundTask(output_path.unlink, missing_ok=True),
        )
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error exporting clip: {e}")
        raise HTTPException(status_code=500, detail=f"Error exporting clip: {str(e)}")


@router.post("/{task_id}/cancel")
async def cancel_task(
    task_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Cancel an active queued or processing task."""
    try:
        task_service = TaskService(db)
        task = await _require_task_owner(request, task_service, db, task_id)

        if task.get("status") in ["completed", "error", "cancelled"]:
            return {"message": f"Task already in terminal state: {task.get('status')}"}

        runtime_config = get_config()
        redis_client = redis.Redis(
            host=runtime_config.redis_host,
            port=runtime_config.redis_port,
            password=runtime_config.redis_password,
            decode_responses=True,
        )
        try:
            await redis_client.setex(f"task_cancel:{task_id}", 3600, "1")
        finally:
            await redis_client.aclose()

        await task_service.task_repo.update_task_status(
            db,
            task_id,
            "cancelled",
            progress=0,
            progress_message="Cancelled by user",
            expected_statuses=["queued", "processing"],
        )

        return {"message": "Task cancellation requested"}
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error cancelling task: {e}")
        raise HTTPException(status_code=500, detail=f"Error cancelling task: {str(e)}")


@router.get("/metrics/performance")
async def get_performance_metrics(
    request: Request, db: AsyncSession = Depends(get_db)
):
    """Get aggregate processing performance metrics by mode."""
    try:
        await require_admin_user(request, db, get_config())
        task_service = TaskService(db)
        return await task_service.get_performance_metrics()
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error loading performance metrics: {e}")
        raise HTTPException(status_code=500, detail=f"Error loading metrics: {str(e)}")


@router.post("/{task_id}/resume")
async def resume_task(
    task_id: str, request: Request, db: AsyncSession = Depends(get_db)
):
    """Retry a cancelled or errored task while preserving completed clips."""
    try:
        task_service = TaskService(db)
        task = await _require_task_owner(request, task_service, db, task_id)

        async with task_run_guard(db, task_id):
            task = await task_service.task_repo.get_task_by_id(db, task_id)
            if task.get("status") == "queued":
                return {"message": "Task already queued"}
            if task.get("status") not in ["cancelled", "error"]:
                raise HTTPException(
                    status_code=400,
                    detail="Only cancelled/error/queued tasks can be retried",
                )
            # The rollout gate holds for resumes too: switching it off (or
            # leaving the allowlist) stops a workflow task from running again.
            spec = workflow_spec_from_task(task, "auto")  # the length never decides the gate
            if not spec.legacy and not await workflow_allowed_for(
                db, task["user_id"], spec.workflow, platform=client_platform(request)
            ):
                error = workflow_not_available()
                raise HTTPException(status_code=error.status, detail=error.to_detail())

            source_url = task.get("source_url")
            source_type = task.get("source_type")
            output_format = "vertical"
            add_subtitles = True

            metadata = await _load_task_source_metadata(task_id, db=db)
            if not source_url:
                source_url = metadata.get("url")
            if not source_type:
                source_type = metadata.get("source_type")
            of = metadata.get("output_format", output_format)
            if of in VALID_OUTPUT_FORMATS:
                output_format = of
            asub = metadata.get("add_subtitles", add_subtitles)
            if isinstance(asub, bool):
                add_subtitles = asub
            cleanup_settings = normalize_clip_cleanup_settings(
                metadata.get("cut_long_pauses"),
                metadata.get("pause_threshold_ms"),
                metadata.get("remove_filler_words"),
                metadata.get("filtered_words"),
            )

            if not source_url or not source_type:
                raise HTTPException(status_code=400, detail="Task source URL is missing")

            async with generation_allowance_guard(
                db, task["user_id"], enabled=get_config().monetization_enabled
            ):
                await BillingService(db).assert_can_resume_task(task["user_id"], task_id)

                try:
                    runtime_config = get_config()
                    redis_client = redis.Redis(
                        host=runtime_config.redis_host,
                        port=runtime_config.redis_port,
                        password=runtime_config.redis_password,
                        decode_responses=True,
                    )
                    try:
                        await redis_client.delete(f"task_cancel:{task_id}")
                    finally:
                        await redis_client.aclose()

                    await task_service.task_repo.update_task_status(
                        db,
                        task_id,
                        "queued",
                        progress=0,
                        progress_message="Re-queued by user",
                    )

                    processing_mode = (
                        task.get("processing_mode") or runtime_config.default_processing_mode
                    )

                    processing_job_id = f"{task_id}:{secrets.token_hex(16)}"
                    metadata["processing_job_id"] = processing_job_id
                    await _save_task_source_metadata(task_id, metadata, db=db)
                    job_id = await JobQueue.enqueue_processing_job(
                        "process_video_task",
                        processing_mode,
                        task_id,
                        source_url,
                        source_type,
                        task["user_id"],
                        task.get("font_family"),
                        task.get("font_size"),
                        task.get("font_color"),
                        task.get("caption_template") or "default",
                        processing_mode,
                        output_format,
                        add_subtitles,
                        cleanup_settings,
                        normalize_clip_length(metadata.get("clip_length")),
                        _job_id=processing_job_id,
                    )
                except Exception:
                    await task_service.task_repo.update_task_status(
                        db, task_id, task["status"],
                        progress_message="Could not queue generation. Please try again.",
                        expected_statuses=["queued", task["status"]],
                    )
                    raise

                return {"message": "Generation retry queued", "job_id": job_id}
    except GenerationAllowanceBusy as e:
        raise HTTPException(status_code=409, detail=str(e), headers={"Retry-After": "1"})
    except BillingLimitExceeded as e:
        raise HTTPException(
            status_code=402,
            detail={
                "code": "SUBSCRIPTION_REQUIRED",
                "message": e.summary.get("reason") or "Plan usage limit reached",
                "billing": jsonable_encoder(e.summary),
            },
        )
    except TaskRunBusy as e:
        raise HTTPException(status_code=409, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Error retrying generation: {e}")
        raise HTTPException(status_code=500, detail=f"Error retrying generation: {str(e)}")


@router.get("/dead-letter/list")
async def list_dead_letter_tasks(request: Request, db: AsyncSession = Depends(get_db)):
    """List tasks that exhausted retries and landed in dead-letter store."""
    runtime_config = get_config()
    await require_admin_user(request, db, runtime_config)
    redis_client = redis.Redis(
        host=runtime_config.redis_host,
        port=runtime_config.redis_port,
        password=runtime_config.redis_password,
        decode_responses=True,
    )
    try:
        ids_result = redis_client.smembers("tasks:dead_letter")
        ids = await ids_result if inspect.isawaitable(ids_result) else ids_result
        items = []
        safe_ids = list(ids or [])
        for task_id in sorted(safe_ids):
            payload = await redis_client.get(f"dead_letter:{task_id}")
            if payload:
                try:
                    items.append(json.loads(payload))
                except json.JSONDecodeError:
                    items.append({"task_id": task_id, "raw": payload})

        return {"total": len(items), "tasks": items}
    finally:
        await redis_client.aclose()