#!/usr/bin/env python3
"""HunyuanVideo I2V - Proper workflow"""

import json
import urllib.request
import urllib.error
import uuid

COMFY_URL = "http://localhost:8188"
INPUT_IMAGE = "pool_party.png"

PROMPT = """Two men stand beside a swimming pool at sunset. The larger man on the left slowly turns to face the smaller man. The smaller man turns around to face him. They embrace in a warm hug and share a tender romantic kiss. All movements are smooth, slow, and natural. High quality detailed hands with proper anatomy. Photorealistic video quality."""

workflow = {
    "1": {"class_type": "LoadImage", "inputs": {"image": INPUT_IMAGE, "upload": "image"}},
    
    "2": {"class_type": "ImageResizeKJv2", "inputs": {
        "image": ["1", 0], "width": 848, "height": 480,
        "upscale_method": "lanczos", "keep_proportion": "crop",
        "pad_color": "0, 0, 0", "crop_position": "center", "divisible_by": 32
    }},
    
    "3": {"class_type": "HyVideoModelLoader", "inputs": {
        "model_name": "hunyuan/hunyuan_video_I2V_720_fixed_fp8_e4m3fn.safetensors",
        "precision": "bf16",
        "quantization": "fp8_e4m3fn"
    }},
    
    "4": {"class_type": "HyVideoVAELoader", "inputs": {
        "vae_name": "hunyuan_video_vae_bf16.safetensors",
        "precision": "bf16"
    }},
    
    "5": {"class_type": "DownloadAndLoadHyVideoTextEncoder", "inputs": {
        "model": "llava-llama-3-8b-v1_1-transformers",
        "precision": "bf16",
        "device": "offload_device"
    }},
    
    "6": {"class_type": "HyVideoI2VEncode", "inputs": {
        "text_encoders": ["5", 0],
        "prompt": PROMPT
    }},
    
    "7": {"class_type": "HyVideoBlockSwap", "inputs": {
        "blocks_to_swap": 20
    }},
    
    "8": {"class_type": "HyVideoSampler", "inputs": {
        "model": ["3", 0],
        "hyvid_embeds": ["6", 0],
        "width": 848,
        "height": 480,
        "num_frames": 61,
        "steps": 30,
        "embedded_guidance_scale": 1.0,
        "flow_shift": 7.0,
        "seed": 42,
        "force_offload": True,
        "scheduler": "euler",
        "block_swap_args": ["7", 0],
        "i2v_mode": True
    }},
    
    "9": {"class_type": "HyVideoDecode", "inputs": {
        "vae": ["4", 0],
        "samples": ["8", 0],
        "enable_tiling": True,
        "tile_size": 256
    }},
    
    "10": {"class_type": "VHS_VideoCombine", "inputs": {
        "images": ["9", 0],
        "frame_rate": 24,
        "loop_count": 0,
        "filename_prefix": "Hunyuan_I2V",
        "format": "video/h264-mp4",
        "pix_fmt": "yuv420p",
        "crf": 16,
        "save_metadata": True,
        "save_output": True
    }}
}

def submit():
    prompt_id = str(uuid.uuid4())
    data = {"prompt": workflow, "client_id": "selena"}
    req = urllib.request.Request(
        f"{COMFY_URL}/prompt",
        data=json.dumps(data).encode('utf-8'),
        headers={'Content-Type': 'application/json'}
    )
    try:
        with urllib.request.urlopen(req) as response:
            result = json.loads(response.read().decode('utf-8'))
            print(f"✅ Submitted! ID: {result.get('prompt_id', prompt_id)}")
            return result.get('prompt_id')
    except urllib.error.HTTPError as e:
        err = e.read().decode('utf-8')
        print(f"❌ Error: {err[:1000]}")
        return None

if __name__ == "__main__":
    print("🎬 HunyuanVideo I2V:")
    print("   - Better temporal coherence")
    print("   - 30 steps euler scheduler")
    print("   - 61 frames @ 24fps (~2.5 sec)")
    print()
    submit()
