File size: 42,151 Bytes
7b5f7c4
ed37502
 
 
 
7b5f7c4
ed37502
 
 
 
 
 
e808ae1
ed37502
 
 
 
 
 
 
 
 
 
a4583f2
7b5f7c4
a4583f2
7b5f7c4
 
 
 
 
 
a4583f2
 
 
 
 
ed37502
 
 
 
 
e808ae1
 
 
 
ed37502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e808ae1
ed37502
 
e808ae1
ed37502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e808ae1
ed37502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b5f7c4
 
 
 
 
 
 
 
 
a4583f2
7b5f7c4
a4583f2
7b5f7c4
 
 
1ebf6af
 
a4583f2
 
1ebf6af
a4583f2
 
 
 
 
 
 
 
7b5f7c4
1ebf6af
7b5f7c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4583f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1970317
b02f80a
 
 
 
 
 
19c97d8
b02f80a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36371b1
b02f80a
 
 
 
 
 
 
 
 
 
36371b1
b02f80a
 
 
 
 
 
a97bced
 
 
 
 
 
 
 
 
 
 
 
b02f80a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36371b1
b02f80a
 
 
 
 
 
27e64d0
 
 
 
 
 
 
b02f80a
27e64d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5a8b9c0
 
27e64d0
 
 
 
 
 
 
 
 
 
 
b02f80a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a4583f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc4811e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e808ae1
 
fc4811e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7b5f7c4
 
 
 
 
 
 
 
 
 
 
 
1ebf6af
 
 
7b5f7c4
 
1ebf6af
7b5f7c4
1ebf6af
7b5f7c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e808ae1
 
 
 
 
1ebf6af
 
 
7b5f7c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ebf6af
7b5f7c4
 
 
 
 
 
 
 
 
fc4811e
7b5f7c4
 
fc4811e
 
 
 
 
 
 
 
 
7b5f7c4
 
 
 
 
 
 
 
 
 
fc4811e
7b5f7c4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed37502
 
 
 
 
e808ae1
 
ed37502
 
 
 
e808ae1
ed37502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e808ae1
ed37502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e808ae1
 
 
 
 
 
ed37502
 
 
e808ae1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ed37502
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Video generation routes — WAN 2.2 img2video on RunPod pod or WaveSpeed cloud."""

from __future__ import annotations

import asyncio
import base64
import logging
import os
import time
import uuid
from pathlib import Path

import runpod
from fastapi import APIRouter, File, Form, HTTPException, UploadFile
from pydantic import BaseModel

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/api/video", tags=["video"])

# Video jobs tracking
_video_jobs: dict[str, dict] = {}

# Cloud providers (initialized from main.py)
_wavespeed_provider = None
_higgsfield_provider = None

def init_wavespeed(provider):
    """Initialize WaveSpeed provider for cloud video generation."""
    global _wavespeed_provider
    _wavespeed_provider = provider

def init_higgsfield(provider):
    """Initialize Higgsfield provider for Kling 3.0, Sora 2, etc."""
    global _higgsfield_provider
    _higgsfield_provider = provider

# Pod state is shared from routes_pod
def _get_pod_state():
    from content_engine.api.routes_pod import _pod_state
    return _pod_state

def _get_comfyui_url():
    from content_engine.api.routes_pod import _get_comfyui_url as _gcurl
    return _gcurl()


class VideoGenerateRequest(BaseModel):
    prompt: str
    negative_prompt: str = ""
    num_frames: int = 81  # ~3 seconds at 24fps
    fps: int = 24
    seed: int = -1


@router.post("/generate")
async def generate_video(
    image: UploadFile = File(...),
    prompt: str = Form(...),
    negative_prompt: str = Form(""),
    num_frames: int = Form(81),
    fps: int = Form(24),
    seed: int = Form(-1),
):
    """Generate a video from an image using WAN 2.2 I2V on the RunPod pod."""
    import httpx
    import random
    import base64

    pod_state = _get_pod_state()

    if pod_state["status"] != "running":
        raise HTTPException(400, "Pod not running - start it first in Status page")

    job_id = str(uuid.uuid4())[:8]
    seed = seed if seed >= 0 else random.randint(0, 2**32 - 1)

    # Read the image
    image_bytes = await image.read()
    image_b64 = base64.b64encode(image_bytes).decode("utf-8")

    # Build ComfyUI workflow for WAN 2.2 I2V
    workflow = _build_wan_i2v_workflow(
        image_b64=image_b64,
        prompt=prompt,
        negative_prompt=negative_prompt,
        num_frames=num_frames,
        fps=fps,
        seed=seed,
    )

    try:
        comfyui_url = _get_comfyui_url()
        async with httpx.AsyncClient(timeout=30) as client:
            # First upload the image to ComfyUI
            upload_url = f"{comfyui_url}/upload/image"
            files = {"image": (f"input_{job_id}.png", image_bytes, "image/png")}
            upload_resp = await client.post(upload_url, files=files)

            if upload_resp.status_code != 200:
                raise HTTPException(500, "Failed to upload image to pod")

            upload_data = upload_resp.json()
            uploaded_filename = upload_data.get("name", f"input_{job_id}.png")

            # Update workflow with uploaded filename
            workflow = _build_wan_i2v_workflow(
                uploaded_filename=uploaded_filename,
                prompt=prompt,
                negative_prompt=negative_prompt,
                num_frames=num_frames,
                fps=fps,
                seed=seed,
            )

            # Submit workflow
            url = f"{comfyui_url}/prompt"
            resp = await client.post(url, json={"prompt": workflow})
            resp.raise_for_status()

            data = resp.json()
            prompt_id = data["prompt_id"]

            _video_jobs[job_id] = {
                "prompt_id": prompt_id,
                "status": "running",
                "seed": seed,
                "started_at": time.time(),
                "num_frames": num_frames,
                "fps": fps,
            }

            logger.info("Video generation started: %s -> %s", job_id, prompt_id)

            # Start background task to poll for completion
            asyncio.create_task(_poll_video_job(job_id, prompt_id))

            return {
                "job_id": job_id,
                "status": "running",
                "seed": seed,
                "estimated_time": f"~{num_frames * 2} seconds",
            }

    except httpx.HTTPError as e:
        logger.error("Video generation failed: %s", e)
        raise HTTPException(500, f"Generation failed: {e}")


@router.post("/generate/cloud")
async def generate_video_cloud(
    image: UploadFile = File(...),
    prompt: str = Form("smooth motion, high quality video"),
    negative_prompt: str = Form(""),
    model: str = Form("wan-2.6-i2v"),
    num_frames: int = Form(81),
    fps: int = Form(24),
    seed: int = Form(-1),
    backend: str = Form("wavespeed"),  # wavespeed or higgsfield
):
    """Generate a video using cloud API (WaveSpeed or Higgsfield)."""
    import random
    import httpx

    logger.info("Video cloud generation request: model=%s, backend=%s, frames=%d", model, backend, num_frames)

    # Route to Higgsfield for Kling 3.0 models
    if backend == "higgsfield" or model.startswith("kling-3"):
        logger.info("Routing to Higgsfield for model: %s", model)
        return await generate_video_higgsfield(
            image=image,
            prompt=prompt,
            model=model,
            duration=max(3, num_frames // 24),  # Convert frames to seconds
            seed=seed,
        )

    if not _wavespeed_provider:
        logger.error("WaveSpeed provider not configured!")
        raise HTTPException(500, "WaveSpeed API not configured")

    job_id = str(uuid.uuid4())[:8]
    seed = seed if seed >= 0 else random.randint(0, 2**32 - 1)

    # Read the image
    image_bytes = await image.read()
    image_b64 = base64.b64encode(image_bytes).decode("utf-8")

    # Create job entry
    _video_jobs[job_id] = {
        "status": "running",
        "seed": seed,
        "started_at": time.time(),
        "num_frames": num_frames,
        "fps": fps,
        "model": model,
        "backend": "cloud",
    }

    logger.info("Cloud video generation started: %s (model=%s)", job_id, model)

    # Start background task for cloud video generation
    asyncio.create_task(_generate_cloud_video(job_id, image_bytes, prompt, negative_prompt, model, seed))

    return {
        "job_id": job_id,
        "status": "running",
        "seed": seed,
        "model": model,
        "estimated_time": "~30-120 seconds",
    }


@router.post("/generate/higgsfield")
async def generate_video_higgsfield(
    image: UploadFile = File(...),
    prompt: str = Form("smooth cinematic motion"),
    model: str = Form("kling-3.0"),
    duration: int = Form(5),
    resolution: str = Form("720p"),
    enable_audio: bool = Form(False),
    seed: int = Form(-1),
):
    """Generate a video using Higgsfield (Kling 3.0, Sora 2, Veo 3.1)."""
    import random

    if not _higgsfield_provider:
        raise HTTPException(500, "Higgsfield API not configured - set HIGGSFIELD_API_KEY")

    job_id = str(uuid.uuid4())[:8]
    seed = seed if seed >= 0 else random.randint(0, 2**32 - 1)

    # Read the image
    image_bytes = await image.read()

    # Create job entry
    _video_jobs[job_id] = {
        "status": "running",
        "seed": seed,
        "started_at": time.time(),
        "duration": duration,
        "model": model,
        "backend": "higgsfield",
        "message": "Starting Higgsfield video generation...",
    }

    logger.info("Higgsfield video generation started: %s (model=%s)", job_id, model)

    # Start background task
    asyncio.create_task(_generate_higgsfield_video(
        job_id, image_bytes, prompt, model, duration, resolution, enable_audio, seed
    ))

    return {
        "job_id": job_id,
        "status": "running",
        "seed": seed,
        "model": model,
        "backend": "higgsfield",
        "estimated_time": f"~{duration * 10}-{duration * 20} seconds",
    }


@router.post("/generate/kling-motion")
async def generate_kling_motion(
    image: UploadFile = File(...),
    driving_video: UploadFile = File(...),
    prompt: str = Form("smooth motion, high quality video"),
    duration: int = Form(5),
    seed: int = Form(-1),
    character_orientation: str = Form("image"),
):
    """Generate video using Kling Motion Control (character image + driving video)."""
    import random

    if not _wavespeed_provider:
        raise HTTPException(500, "WaveSpeed API not configured")

    job_id = str(uuid.uuid4())[:8]
    seed = seed if seed >= 0 else random.randint(0, 2**32 - 1)

    image_bytes = await image.read()
    video_bytes = await driving_video.read()

    _video_jobs[job_id] = {
        "status": "running",
        "seed": seed,
        "started_at": time.time(),
        "model": "kling-motion",
        "backend": "cloud",
        "message": "Uploading files...",
    }

    asyncio.create_task(_generate_kling_motion_video(job_id, image_bytes, video_bytes, prompt, duration, character_orientation))

    return {"job_id": job_id, "status": "running", "estimated_time": "~60-120 seconds"}


async def _generate_kling_motion_video(
    job_id: str,
    image_bytes: bytes,
    video_bytes: bytes,
    prompt: str,
    duration: int,
    character_orientation: str = "image",
):
    """Background task: upload image + driving video, call Kling Motion Control API."""
    import httpx
    import aiohttp

    try:
        # Resize image if too large (Kling Motion limit)
        from PIL import Image
        import io
        img = Image.open(io.BytesIO(image_bytes))
        max_size = 1280
        if img.width > max_size or img.height > max_size:
            img.thumbnail((max_size, max_size), Image.LANCZOS)
            buf = io.BytesIO()
            img.save(buf, format="JPEG", quality=90)
            image_bytes = buf.getvalue()
            logger.info("Resized character image to %dx%d", img.width, img.height)

        _video_jobs[job_id]["message"] = "Uploading character image..."
        image_url = await _wavespeed_provider._upload_temp_image(image_bytes)
        logger.info("Kling motion: character image uploaded: %s", image_url[:80])

        _video_jobs[job_id]["message"] = "Uploading driving video..."
        video_url = await _upload_temp_video(video_bytes)
        logger.info("Kling motion: driving video uploaded: %s", video_url[:80])

        api_key = _wavespeed_provider._api_key
        endpoint = "https://api.wavespeed.ai/api/v3/kwaivgi/kling-v2.6-pro/motion-control"

        payload = {
            "image": image_url,
            "video": video_url,
            "prompt": prompt,
            "duration": duration,
            "character_orientation": character_orientation,
            "enable_sync_mode": False,
        }

        _video_jobs[job_id]["message"] = "Calling Kling Motion Control API..."
        logger.info("Calling Kling Motion Control: %s", endpoint)

        # Reuse the provider's existing httpx client (avoids SSL reconnect issues)
        http = _wavespeed_provider._http_client
        resp = await http.post(
            endpoint,
            json=payload,
            headers={"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"},
        )

        if resp.status_code != 200:
            error_text = resp.text[:500]
            logger.error("Kling Motion API error: %s", error_text)
            _video_jobs[job_id]["status"] = "failed"
            _video_jobs[job_id]["error"] = f"API error: {error_text[:200]}"
            return

        result = resp.json()
        data = result.get("data", result)
        logger.info("Kling Motion API response: %s", str(result)[:300])

        # Poll if async
        outputs = data.get("outputs", [])
        urls_data = data.get("urls", {})
        if not outputs and urls_data.get("get"):
            _video_jobs[job_id]["message"] = "Waiting for Kling Motion to complete..."
            video_url_out = await _poll_wavespeed_video(urls_data["get"], api_key, job_id, max_attempts=300, interval=5.0)
        elif outputs:
            video_url_out = outputs[0] if isinstance(outputs[0], str) else outputs[0].get("url")
        else:
            _video_jobs[job_id]["status"] = "failed"
            _video_jobs[job_id]["error"] = "No output URL in response"
            return

        if not video_url_out:
            return  # poll already set status

        # Download and save
        _video_jobs[job_id]["message"] = "Downloading video..."
        from content_engine.config import settings
        output_dir = settings.paths.output_dir / "videos"
        output_dir.mkdir(parents=True, exist_ok=True)
        filename = f"kling_motion_{job_id}.mp4"
        output_path = output_dir / filename

        r = await http.get(video_url_out)
        output_path.write_bytes(r.content)

        _video_jobs[job_id]["status"] = "completed"
        _video_jobs[job_id]["filename"] = filename
        _video_jobs[job_id]["message"] = "Done"
        logger.info("Kling Motion video saved: %s", filename)

    except Exception as e:
        logger.exception("Kling Motion generation failed: %s", e)
        _video_jobs[job_id]["status"] = "failed"
        _video_jobs[job_id]["error"] = str(e)


async def _upload_temp_video(video_bytes: bytes) -> str:
    """Upload a video file to litterbox.catbox.moe and return the URL."""
    import aiohttp

    async with aiohttp.ClientSession() as session:
        data = aiohttp.FormData()
        data.add_field("reqtype", "fileupload")
        data.add_field("time", "1h")
        data.add_field("fileToUpload", video_bytes, filename="driving.mp4", content_type="video/mp4")
        async with session.post("https://litterbox.catbox.moe/resources/internals/api.php", data=data) as resp:
            if resp.status == 200:
                url = (await resp.text()).strip()
                if url.startswith("http"):
                    return url
    raise RuntimeError("Failed to upload driving video to litterbox.catbox.moe")


async def _generate_higgsfield_video(
    job_id: str,
    image_bytes: bytes,
    prompt: str,
    model: str,
    duration: int,
    resolution: str,
    enable_audio: bool,
    seed: int,
):
    """Background task to generate video via Higgsfield API."""
    try:
        _video_jobs[job_id]["message"] = "Uploading image to Higgsfield..."

        # Upload image to temp URL
        image_url = await _higgsfield_provider._upload_temp_image(image_bytes) if hasattr(_higgsfield_provider, '_upload_temp_image') else None

        if not image_url:
            # Fall back to base64 data URL
            import base64
            image_b64 = base64.b64encode(image_bytes).decode("utf-8")
            image_url = f"data:image/png;base64,{image_b64}"

        _video_jobs[job_id]["message"] = f"Generating video with {model}..."

        # Generate video
        result = await _higgsfield_provider.generate_video(
            prompt=prompt,
            model=model,
            duration=duration,
            resolution=resolution,
            enable_audio=enable_audio,
            image_url=image_url,
        )

        video_url = result.get("video_url")
        if not video_url:
            _video_jobs[job_id]["status"] = "failed"
            _video_jobs[job_id]["error"] = "No video URL in response"
            return

        # Download the video
        _video_jobs[job_id]["message"] = "Downloading generated video..."
        import httpx
        async with httpx.AsyncClient(timeout=120) as client:
            video_resp = await client.get(video_url)

            if video_resp.status_code != 200:
                _video_jobs[job_id]["status"] = "failed"
                _video_jobs[job_id]["error"] = "Failed to download video"
                return

            # Save to local output directory
            from content_engine.config import settings
            output_dir = settings.paths.output_dir / "videos"
            output_dir.mkdir(parents=True, exist_ok=True)

            ext = ".mp4"
            if video_url.endswith(".webm"):
                ext = ".webm"

            local_path = output_dir / f"video_{job_id}{ext}"
            local_path.write_bytes(video_resp.content)

            _video_jobs[job_id]["status"] = "completed"
            _video_jobs[job_id]["output_path"] = str(local_path)
            _video_jobs[job_id]["completed_at"] = time.time()
            _video_jobs[job_id]["filename"] = local_path.name
            _video_jobs[job_id]["message"] = "Video generated successfully!"

            logger.info("Higgsfield video saved: %s", local_path)

    except Exception as e:
        logger.error("Higgsfield video generation failed: %s", e)
        _video_jobs[job_id]["status"] = "failed"
        _video_jobs[job_id]["error"] = str(e)


async def _poll_wavespeed_video(poll_url: str, api_key: str, job_id: str, max_attempts: int = 120, interval: float = 3.0) -> str | None:
    """Poll the WaveSpeed async video job URL until outputs are ready.

    Returns the first output URL when available, or None on failure.
    """
    import httpx

    async with httpx.AsyncClient(timeout=60) as client:
        for attempt in range(max_attempts):
            try:
                resp = await client.get(
                    poll_url,
                    headers={"Authorization": f"Bearer {api_key}"},
                )
                resp.raise_for_status()
                result = resp.json()

                data = result.get("data", result)
                status = data.get("status", "")

                if status == "failed":
                    error_msg = data.get("error", "Unknown error")
                    logger.error("WaveSpeed video job failed: %s", error_msg)
                    _video_jobs[job_id]["status"] = "failed"
                    _video_jobs[job_id]["error"] = error_msg
                    return None

                outputs = data.get("outputs", [])
                if outputs:
                    logger.info("WaveSpeed video job completed after %d polls", attempt + 1)
                    return outputs[0]

                # Also check for 'output' field
                if "output" in data:
                    out = data["output"]
                    if isinstance(out, list) and out:
                        return out[0]
                    elif isinstance(out, str):
                        return out

                # Update job status with progress
                _video_jobs[job_id]["message"] = f"Generating video... (poll {attempt + 1}/{max_attempts})"

                logger.debug("WaveSpeed video job pending (attempt %d/%d)", attempt + 1, max_attempts)
                await asyncio.sleep(interval)

            except Exception as e:
                logger.warning("Video poll request failed: %s", e)
                await asyncio.sleep(interval)

    logger.error("WaveSpeed video job timed out after %d attempts", max_attempts)
    return None


async def _generate_cloud_video(
    job_id: str,
    image_bytes: bytes,
    prompt: str,
    negative_prompt: str,
    model: str,
    seed: int,
):
    """Background task to generate video via WaveSpeed cloud API."""
    import httpx
    import aiohttp

    logger.info("Starting cloud video generation: job=%s, model=%s, image_size=%d bytes", job_id, model, len(image_bytes))
    _video_jobs[job_id]["message"] = "Uploading image..."

    try:
        # Upload image to temporary hosting (WaveSpeed needs URL)
        logger.info("Uploading image to temp host...")
        image_url = await _wavespeed_provider._upload_temp_image(image_bytes)
        logger.info("Image uploaded: %s", image_url[:80] if image_url else "FAILED")

        # Resolve model to WaveSpeed model ID
        from content_engine.services.cloud_providers.wavespeed_provider import VIDEO_MODEL_MAP
        wavespeed_model = VIDEO_MODEL_MAP.get(model, VIDEO_MODEL_MAP.get("default", "alibaba/wan-2.6-i2v-720p"))

        # Call WaveSpeed video API
        api_key = _wavespeed_provider._api_key
        endpoint = f"https://api.wavespeed.ai/api/v3/{wavespeed_model}"

        payload = {
            "image": image_url,
            "prompt": prompt,
            "enable_sync_mode": True,
        }
        if negative_prompt:
            payload["negative_prompt"] = negative_prompt

        # Grok Imagine Video uses duration (6 or 10s) instead of frame counts
        if model == "grok-imagine-i2v":
            num_frames = _video_jobs[job_id].get("num_frames", 81)
            payload["duration"] = 10 if num_frames > 150 else 6

        _video_jobs[job_id]["message"] = f"Calling WaveSpeed API ({wavespeed_model})..."
        logger.info("Calling WaveSpeed video API: %s", endpoint)

        async with httpx.AsyncClient(timeout=300) as client:
            resp = await client.post(
                endpoint,
                json=payload,
                headers={
                    "Authorization": f"Bearer {api_key}",
                    "Content-Type": "application/json",
                },
            )

            if resp.status_code != 200:
                error_text = resp.text[:500]
                logger.error("WaveSpeed video API error: %s", error_text)
                _video_jobs[job_id]["status"] = "failed"
                _video_jobs[job_id]["error"] = f"API error: {error_text[:200]}"
                return

            result = resp.json()
            logger.info("WaveSpeed video API response: %s", str(result)[:500])
            data = result.get("data", result)

            # Check for failed status
            if data.get("status") == "failed":
                error_msg = data.get("error", "Unknown error")
                _video_jobs[job_id]["status"] = "failed"
                _video_jobs[job_id]["error"] = error_msg
                return

            # Extract video URL - handle async response (outputs empty, urls.get present)
            video_url = None
            outputs = data.get("outputs", [])
            urls_data = data.get("urls", {})

            # Check for async response first
            if not outputs and urls_data and urls_data.get("get"):
                poll_url = urls_data["get"]
                logger.info("WaveSpeed video returned async job, polling: %s", poll_url[:80])
                _video_jobs[job_id]["message"] = "Polling for video result..."
                video_url = await _poll_wavespeed_video(poll_url, api_key, job_id)
            elif outputs:
                video_url = outputs[0]
            elif "output" in data:
                out = data["output"]
                if isinstance(out, list) and out:
                    video_url = out[0]
                elif isinstance(out, str):
                    video_url = out

            if not video_url:
                _video_jobs[job_id]["status"] = "failed"
                _video_jobs[job_id]["error"] = f"No video URL in response: {data}"
                return

            # Download the video
            logger.info("Downloading cloud video: %s", video_url[:80])
            video_resp = await client.get(video_url)

            if video_resp.status_code != 200:
                _video_jobs[job_id]["status"] = "failed"
                _video_jobs[job_id]["error"] = "Failed to download video"
                return

            # Save to local output directory
            from content_engine.config import settings
            output_dir = settings.paths.output_dir / "videos"
            output_dir.mkdir(parents=True, exist_ok=True)

            # Determine extension from URL or default to mp4
            ext = ".mp4"
            if video_url.endswith(".webm"):
                ext = ".webm"
            elif video_url.endswith(".webp"):
                ext = ".webp"

            local_path = output_dir / f"video_{job_id}{ext}"
            local_path.write_bytes(video_resp.content)

            _video_jobs[job_id]["status"] = "completed"
            _video_jobs[job_id]["output_path"] = str(local_path)
            _video_jobs[job_id]["completed_at"] = time.time()
            _video_jobs[job_id]["filename"] = local_path.name

            logger.info("Cloud video saved: %s", local_path)

    except Exception as e:
        logger.error("Cloud video generation failed: %s", e)
        _video_jobs[job_id]["status"] = "failed"
        _video_jobs[job_id]["error"] = str(e)


async def _poll_video_job(job_id: str, prompt_id: str):
    """Poll ComfyUI for video job completion."""
    import httpx

    start = time.time()
    timeout = 1800  # 30 minutes for video (WAN 2.2 needs time to load 14B model first run)
    comfyui_url = _get_comfyui_url()

    async with httpx.AsyncClient(timeout=60) as client:
        while time.time() - start < timeout:
            try:
                url = f"{comfyui_url}/history/{prompt_id}"
                resp = await client.get(url)

                if resp.status_code == 200:
                    data = resp.json()
                    if prompt_id in data:
                        outputs = data[prompt_id].get("outputs", {})

                        # Find video output (SaveAnimatedWEBP or VHS_VideoCombine)
                        for node_id, node_output in outputs.items():
                            # Check for gifs/videos
                            if "gifs" in node_output:
                                video_info = node_output["gifs"][0]
                                await _download_video(client, job_id, video_info, pod_state)
                                return
                            # Check for images (animated)
                            if "images" in node_output:
                                img_info = node_output["images"][0]
                                if img_info.get("type") == "output":
                                    await _download_video(client, job_id, img_info, pod_state)
                                    return

            except Exception as e:
                logger.debug("Polling video job: %s", e)

            await asyncio.sleep(3)

    _video_jobs[job_id]["status"] = "failed"
    _video_jobs[job_id]["error"] = "Timeout waiting for video generation"
    logger.error("Video generation timed out: %s", job_id)


async def _download_video(client, job_id: str, video_info: dict, pod_state: dict):
    """Download the generated video from ComfyUI."""
    filename = video_info.get("filename")
    subfolder = video_info.get("subfolder", "")
    file_type = video_info.get("type", "output")

    # Download video
    view_url = f"{_get_comfyui_url()}/view"
    params = {"filename": filename, "type": file_type}
    if subfolder:
        params["subfolder"] = subfolder

    video_resp = await client.get(view_url, params=params)

    if video_resp.status_code == 200:
        # Save to local output directory
        from content_engine.config import settings
        output_dir = settings.paths.output_dir / "videos"
        output_dir.mkdir(parents=True, exist_ok=True)

        # Determine extension
        ext = Path(filename).suffix or ".webp"
        local_path = output_dir / f"video_{job_id}{ext}"
        local_path.write_bytes(video_resp.content)

        _video_jobs[job_id]["status"] = "completed"
        _video_jobs[job_id]["output_path"] = str(local_path)
        _video_jobs[job_id]["completed_at"] = time.time()
        _video_jobs[job_id]["filename"] = local_path.name

        logger.info("Video saved: %s", local_path)
    else:
        _video_jobs[job_id]["status"] = "failed"
        _video_jobs[job_id]["error"] = "Failed to download video"


@router.get("/jobs")
async def list_video_jobs():
    """List all video generation jobs."""
    return list(_video_jobs.values())


@router.get("/jobs/{job_id}")
async def get_video_job(job_id: str):
    """Get status of a video generation job."""
    job = _video_jobs.get(job_id)
    if not job:
        raise HTTPException(404, "Job not found")
    return job


@router.get("/{filename}")
async def get_video_file(filename: str):
    """Serve a generated video file."""
    from fastapi.responses import FileResponse
    from content_engine.config import settings

    video_path = settings.paths.output_dir / "videos" / filename
    if not video_path.exists():
        raise HTTPException(404, "Video not found")

    if filename.endswith(".webm"):
        media_type = "video/webm"
    elif filename.endswith(".mp4"):
        media_type = "video/mp4"
    else:
        media_type = "image/webp"
    return FileResponse(video_path, media_type=media_type)


@router.post("/animate")
async def generate_video_animate(
    image: UploadFile = File(...),
    driving_video: UploadFile = File(...),
    prompt: str = Form("a person dancing, smooth motion, high quality"),
    negative_prompt: str = Form(""),
    width: int = Form(832),
    height: int = Form(480),
    num_frames: int = Form(81),
    fps: int = Form(16),
    seed: int = Form(-1),
    steps: int = Form(20),
    cfg: float = Form(6.0),
    bg_mode: str = Form("keep"),  # keep | driving_video | auto
):
    """Generate a dance animation via WAN 2.2 Animate on RunPod ComfyUI pod.

    Requires on the pod:
      - models/diffusion_models/Wan2_2-Animate-14B_fp8_e4m3fn_scaled_KJ.safetensors
      - models/vae/wan_2.1_vae.safetensors
      - models/clip_vision/clip_vision_h.safetensors
      - models/text_encoders/umt5-xxl-enc-bf16.safetensors
      - Custom nodes: ComfyUI-WanVideoWrapper, ComfyUI-VideoHelperSuite, comfyui_controlnet_aux
    """
    import httpx
    import random

    pod_state = _get_pod_state()
    if pod_state["status"] != "running":
        raise HTTPException(400, "Pod not running — start it first in Status page")

    job_id = str(uuid.uuid4())[:8]
    seed = seed if seed >= 0 else random.randint(0, 2**32 - 1)

    image_bytes = await image.read()
    video_bytes = await driving_video.read()

    try:
        base_url = _get_comfyui_url()
        async with httpx.AsyncClient(timeout=60) as client:

            # Upload character reference image
            img_resp = await client.post(
                f"{base_url}/upload/image",
                files={"image": (f"ref_{job_id}.png", image_bytes, "image/png")},
            )
            if img_resp.status_code != 200:
                raise HTTPException(500, f"Failed to upload character image: {img_resp.text[:200]}")
            img_filename = img_resp.json().get("name", f"ref_{job_id}.png")
            logger.info("Uploaded character image: %s", img_filename)

            # Upload driving video
            vid_ext = "mp4"
            if driving_video.filename and "." in driving_video.filename:
                vid_ext = driving_video.filename.rsplit(".", 1)[-1].lower()
            vid_resp = await client.post(
                f"{base_url}/upload/image",
                files={"image": (f"drive_{job_id}.{vid_ext}", video_bytes, "video/mp4")},
            )
            if vid_resp.status_code != 200:
                raise HTTPException(500, f"Failed to upload driving video: {vid_resp.text[:200]}")
            vid_filename = vid_resp.json().get("name", f"drive_{job_id}.{vid_ext}")
            logger.info("Uploaded driving video: %s", vid_filename)

            workflow = _build_wan_animate_workflow(
                ref_image_filename=img_filename,
                driving_video_filename=vid_filename,
                prompt=prompt,
                negative_prompt=negative_prompt,
                width=width,
                height=height,
                num_frames=num_frames,
                fps=fps,
                seed=seed,
                steps=steps,
                cfg=cfg,
                bg_mode=bg_mode,
            )

            resp = await client.post(f"{base_url}/prompt", json={"prompt": workflow})
            if resp.status_code != 200:
                logger.error("ComfyUI /prompt rejected workflow: %s", resp.text[:2000])
            resp.raise_for_status()
            prompt_id = resp.json()["prompt_id"]

            _video_jobs[job_id] = {
                "prompt_id": prompt_id,
                "status": "running",
                "seed": seed,
                "started_at": time.time(),
                "num_frames": num_frames,
                "fps": fps,
                "mode": "animate",
                "message": "WAN 2.2 Animate submitted...",
            }

            logger.info("WAN Animate job started: %s -> %s", job_id, prompt_id)
            asyncio.create_task(_poll_video_job(job_id, prompt_id))

            return {
                "job_id": job_id,
                "status": "running",
                "seed": seed,
                "estimated_time": f"~{num_frames * 3} seconds",
            }

    except httpx.HTTPError as e:
        logger.error("WAN Animate generation failed: %s", e)
        raise HTTPException(500, f"Generation failed: {e}")


def _build_wan_animate_workflow(
    ref_image_filename: str,
    driving_video_filename: str,
    prompt: str = "a person dancing, smooth motion",
    negative_prompt: str = "",
    width: int = 832,
    height: int = 480,
    num_frames: int = 81,
    fps: int = 16,
    seed: int = 42,
    steps: int = 20,
    cfg: float = 6.0,
    bg_mode: str = "auto",
) -> dict:
    """Build ComfyUI API workflow for WAN 2.2 Animate (motion transfer from driving video).

    Pipeline:
      reference image -> CLIP encode + resize
      driving video   -> DWPreprocessor (pose skeleton)
      both            -> WanVideoAnimateEmbeds -> WanVideoSampler -> decode -> MP4

    bg_mode options:
      "keep"          - use reference image as background (character's original background)
      "driving_video" - use driving video frames as background
      "auto"          - no bg hint, model generates its own background
    """
    neg = negative_prompt or "blurry, static, low quality, watermark, text"

    workflow = {
        # VAE
        "1": {
            "class_type": "WanVideoVAELoader",
            "inputs": {
                "model_name": "wan_2.1_vae.safetensors",
                "precision": "bf16",
            },
        },
        # CLIP Vision
        "2": {
            "class_type": "CLIPVisionLoader",
            "inputs": {"clip_name": "clip_vision_h.safetensors"},
        },
        # Diffusion model
        "3": {
            "class_type": "WanVideoModelLoader",
            "inputs": {
                "model": "wan2.2_animate_14B_bf16.safetensors",
                "base_precision": "bf16",
                "quantization": "fp8_e4m3fn",
                "load_device": "offload_device",
                "attention_mode": "sdpa",
            },
        },
        # Load T5 text encoder
        "4": {
            "class_type": "LoadWanVideoT5TextEncoder",
            "inputs": {
                "model_name": "umt5-xxl-enc-fp8_e4m3fn.safetensors",
                "precision": "bf16",
            },
        },
        # Encode text prompts
        "16": {
            "class_type": "WanVideoTextEncode",
            "inputs": {
                "positive_prompt": prompt,
                "negative_prompt": neg,
                "t5": ["4", 0],
                "force_offload": True,
            },
        },
        # Load reference character image
        "5": {
            "class_type": "LoadImage",
            "inputs": {"image": ref_image_filename},
        },
        # Resize to target resolution
        "6": {
            "class_type": "ImageResizeKJv2",
            "inputs": {
                "image": ["5", 0],
                "width": width,
                "height": height,
                "upscale_method": "lanczos",
                "keep_proportion": "pad_edge_pixel",
                "pad_color": "0, 0, 0",
                "crop_position": "top",
                "divisible_by": 16,
            },
        },
        # CLIP Vision encode reference
        "7": {
            "class_type": "WanVideoClipVisionEncode",
            "inputs": {
                "clip_vision": ["2", 0],
                "image_1": ["6", 0],
                "strength_1": 1.0,
                "strength_2": 1.0,
                "crop": "center",
                "combine_embeds": "average",
                "force_offload": True,
            },
        },
        # Load driving video (dance moves)
        "8": {
            "class_type": "VHS_LoadVideo",
            "inputs": {
                "video": driving_video_filename,
                "force_rate": fps,
                "custom_width": 0,
                "custom_height": 0,
                "frame_load_cap": num_frames if num_frames > 0 else 0,
                "skip_first_frames": 0,
                "select_every_nth": 1,
            },
        },
        # Extract pose skeleton from driving video
        "9": {
            "class_type": "DWPreprocessor",
            "inputs": {
                "image": ["8", 0],
                "detect_hand": "disable",
                "detect_body": "enable",
                "detect_face": "disable",
                "resolution": max(width, height),
                "bbox_detector": "yolox_l.torchscript.pt",
                "pose_estimator": "dw-ll_ucoco_384_bs5.torchscript.pt",
                "scale_stick_for_xinsr_cn": "disable",
            },
        },
        # Animate embeddings: combine ref image + pose + optional background
        "10": {
            "class_type": "WanVideoAnimateEmbeds",
            "inputs": {
                "vae": ["1", 0],
                "clip_embeds": ["7", 0],
                "ref_images": ["6", 0],
                "pose_images": ["9", 0],
                # bg_mode: "keep" = ref image bg, "driving_video" = video frames bg, "auto" = model decides
                **({} if bg_mode == "auto" else {
                    "bg_images": ["6", 0] if bg_mode == "keep" else ["8", 0],
                }),
                "width": width,
                "height": height,
                # When num_frames==0 ("Match video"), link to GetImageSizeAndCount output slot 3
                "num_frames": ["15", 3] if num_frames == 0 else num_frames,
                "force_offload": True,
                "frame_window_size": 77,
                "colormatch": "disabled",
                "pose_strength": 1.0,
                "face_strength": 1.0,
            },
        },
        # Diffusion sampler (no context_options — WanAnim handles looping internally)
        "12": {
            "class_type": "WanVideoSampler",
            "inputs": {
                "model": ["3", 0],
                "image_embeds": ["10", 0],
                "text_embeds": ["16", 0],
                "steps": steps,
                "cfg": cfg,
                "shift": 5.0,
                "seed": seed,
                "force_offload": True,
                "scheduler": "dpm++_sde",
                "riflex_freq_index": 0,
                "denoise_strength": 1.0,
            },
        },
        # Decode latents to frames
        "13": {
            "class_type": "WanVideoDecode",
            "inputs": {
                "vae": ["1", 0],
                "samples": ["12", 0],
                "enable_vae_tiling": True,
                "tile_x": 272,
                "tile_y": 272,
                "tile_stride_x": 144,
                "tile_stride_y": 128,
            },
        },
        # Combine frames into MP4
        "14": {
            "class_type": "VHS_VideoCombine",
            "inputs": {
                "images": ["13", 0],
                "frame_rate": fps,
                "loop_count": 0,
                "filename_prefix": "WanAnimate",
                "format": "video/h264-mp4",
                "pix_fmt": "yuv420p",
                "crf": 19,
                "save_metadata": True,
                "trim_to_audio": False,
                "pingpong": False,
                "save_output": True,
            },
        },
    }

    # "Match video" mode (num_frames=0): detect actual frame count from posed video
    # GetImageSizeAndCount outputs: (IMAGE, width, height, count) — slot 3 = frame count
    if num_frames == 0:
        workflow["15"] = {
            "class_type": "GetImageSizeAndCount",
            "inputs": {"image": ["9", 0]},
        }

    return workflow


def _build_wan_i2v_workflow(
    uploaded_filename: str = None,
    image_b64: str = None,
    prompt: str = "",
    negative_prompt: str = "",
    num_frames: int = 81,
    fps: int = 24,
    seed: int = -1,
) -> dict:
    """Build ComfyUI workflow for WAN 2.2 Image-to-Video."""

    # WAN 2.2 I2V workflow
    # This assumes the WAN 2.2 nodes are installed on the pod
    workflow = {
        # Load the input image
        "1": {
            "class_type": "LoadImage",
            "inputs": {
                "image": uploaded_filename or "input.png",
            },
        },
        # WAN 2.2 model loader
        "2": {
            "class_type": "DownloadAndLoadWanModel",
            "inputs": {
                "model": "Wan2.2-I2V-14B-480P",
            },
        },
        # Text encoder
        "3": {
            "class_type": "WanTextEncode",
            "inputs": {
                "prompt": prompt,
                "negative_prompt": negative_prompt,
                "wan_model": ["2", 0],
            },
        },
        # Image-to-Video generation
        "4": {
            "class_type": "WanImageToVideo",
            "inputs": {
                "image": ["1", 0],
                "wan_model": ["2", 0],
                "conditioning": ["3", 0],
                "num_frames": num_frames,
                "seed": seed,
                "steps": 30,
                "cfg": 5.0,
            },
        },
        # Decode to frames
        "5": {
            "class_type": "WanDecode",
            "inputs": {
                "samples": ["4", 0],
                "wan_model": ["2", 0],
            },
        },
        # Save as animated WEBP
        "6": {
            "class_type": "SaveAnimatedWEBP",
            "inputs": {
                "images": ["5", 0],
                "filename_prefix": "wan_video",
                "fps": fps,
                "lossless": False,
                "quality": 85,
            },
        },
    }

    return workflow