#!/usr/bin/env python3
"""
短剧《总裁的替身前妻》第一集 - 关键场景图片生成
"""

import json
import urllib.request
import time
import os

COMFYUI_URL = "http://127.0.0.1:8188"

# 模型选择
BEST_MODEL = "SDXL 1.0\\9527DetailRealistic_v30.safetensors"

# 负面提示词
NEGATIVE_PROMPT = "(worst quality, low quality:1.4), deformed, distorted, disfigured, bad anatomy, bad proportions, ugly, noisy, blurry, low contrast, watermark, text, signature, cartoon, anime, 3d, painting, drawing, illustration, western features, blue eyes, blonde hair, extra fingers, malformed hands, missing limbs, floating limbs, disconnected limbs, nsfw, nude, naked"

# 第一集关键场景
SCENES = [
    {
        "id": "01",
        "name": "雨夜奔跑",
        "seed": 3001,
        "width": 832,
        "height": 1216,
        "prompt": "(masterpiece, best quality, ultra-detailed:1.3), beautiful young chinese woman running in heavy rain at night, city street with neon lights reflection on wet pavement, wearing white dress soaked in rain, holding portfolio case, high heels broken, desperate expression, tears mixing with raindrops, messy black hair, cinematic lighting, dramatic atmosphere, photorealistic, 8k, shot on ARRI Alexa, full body shot, low angle, raindrops visible",
        "output_prefix": "Drama_EP1_01_Rain_Run_"
    },
    {
        "id": "02",
        "name": "豪车相遇",
        "seed": 3002,
        "width": 1216,
        "height": 832,
        "prompt": "(masterpiece, best quality, ultra-detailed:1.3), black Maybach luxury car stopped at night intersection, rain pouring, headlights illuminating raindrops, a woman sitting on wet ground looking up, dramatic car scene, cinematic composition, neon city lights in background, wet asphalt reflection, moody atmosphere, photorealistic, 8k, wide shot, dramatic lighting",
        "output_prefix": "Drama_EP1_02_Car_Meeting_"
    },
    {
        "id": "03",
        "name": "四目相对",
        "seed": 3003,
        "width": 832,
        "height": 1216,
        "prompt": "(masterpiece, best quality, ultra-detailed:1.3), handsome chinese man in black suit holding black umbrella, looking down with shocked expression, raindrops on his face, sharp jawline, intense eyes, night city background with bokeh lights, umbrella shielding a woman below, dramatic romantic scene, cinematic lighting, photorealistic, 8k, medium shot, shallow depth of field, rain atmosphere",
        "output_prefix": "Drama_EP1_03_Eye_Contact_"
    },
    {
        "id": "04",
        "name": "百万支票",
        "seed": 3004,
        "width": 832,
        "height": 1216,
        "prompt": "(masterpiece, best quality, ultra-detailed:1.3), close-up of man's hand giving check to woman's hand, check showing 1000000 yuan amount, fingers touching, raindrops on hands, dramatic lighting, shallow depth of field, expensive watch on man's wrist, delicate woman's hand, emotional moment, photorealistic, 8k, extreme detail, macro shot",
        "output_prefix": "Drama_EP1_04_Check_Million_"
    },
    {
        "id": "05",
        "name": "对视特写",
        "seed": 3005,
        "width": 832,
        "height": 1216,
        "prompt": "(masterpiece, best quality, ultra-detailed:1.3), beautiful chinese woman and handsome chinese man facing each other in rain, intense eye contact, woman with wet messy hair and teary eyes, man with serious expression holding umbrella, romantic tension, night city lights bokeh background, raindrops visible, cinematic color grading, photorealistic, 8k, close-up portrait, dramatic atmosphere",
        "output_prefix": "Drama_EP1_05_Face_To_Face_"
    },
    {
        "id": "06",
        "name": "豪宅内景",
        "seed": 3006,
        "width": 1216,
        "height": 832,
        "prompt": "(masterpiece, best quality, ultra-detailed:1.3), luxurious modern penthouse interior at night, floor-to-ceiling windows with city skyline view, minimalist luxury design, warm ambient lighting, expensive furniture, marble floor, woman in towel standing in living room, man loosening tie in background, dramatic interior photography, photorealistic, 8k, wide angle shot",
        "output_prefix": "Drama_EP1_06_Luxury_Penthouse_"
    },
    {
        "id": "07",
        "name": "女主特写",
        "seed": 3007,
        "width": 832,
        "height": 1216,
        "prompt": "(masterpiece, best quality, ultra-detailed:1.3), portrait of beautiful young chinese woman, 24 years old, designer, wet black hair clinging to face, smudged makeup from rain, teary eyes with determination, wearing wet white dress, dramatic side lighting, raindrops on skin, emotional expression, cinematic portrait, photorealistic, 8k, close-up, shallow depth of field, ARRI Alexa",
        "output_prefix": "Drama_EP1_07_Heroine_Portrait_"
    },
    {
        "id": "08",
        "name": "男主特写",
        "seed": 3008,
        "width": 832,
        "height": 1216,
        "prompt": "(masterpiece, best quality, ultra-detailed:1.3), portrait of handsome chinese man, 28 years old, CEO, sharp facial features, cold expression, black suit with loosened tie, wet hair from rain, intense eyes, night city lights background, dramatic chiaroscuro lighting, business tycoon, cinematic portrait, photorealistic, 8k, close-up, shallow depth of field, Hasselblad",
        "output_prefix": "Drama_EP1_08_Hero_Portrait_"
    }
]

def submit_prompt(scene):
    """提交单个场景到 ComfyUI"""
    prompt_data = {
        "prompt": {
            "3": {
                "class_type": "KSampler",
                "inputs": {
                    "cfg": 7.0,
                    "denoise": 1,
                    "latent_image": ["5", 0],
                    "model": ["4", 0],
                    "negative": ["7", 0],
                    "positive": ["6", 0],
                    "sampler_name": "dpmpp_2m",
                    "scheduler": "karras",
                    "seed": scene["seed"],
                    "steps": 30
                }
            },
            "4": {
                "class_type": "CheckpointLoaderSimple",
                "inputs": {
                    "ckpt_name": BEST_MODEL
                }
            },
            "5": {
                "class_type": "EmptyLatentImage",
                "inputs": {
                    "batch_size": 1,
                    "height": scene["height"],
                    "width": scene["width"]
                }
            },
            "6": {
                "class_type": "CLIPTextEncode",
                "inputs": {
                    "clip": ["4", 1],
                    "text": scene["prompt"]
                }
            },
            "7": {
                "class_type": "CLIPTextEncode",
                "inputs": {
                    "clip": ["4", 1],
                    "text": NEGATIVE_PROMPT
                }
            },
            "8": {
                "class_type": "VAEDecode",
                "inputs": {
                    "samples": ["3", 0],
                    "vae": ["4", 2]
                }
            },
            "9": {
                "class_type": "SaveImage",
                "inputs": {
                    "filename_prefix": scene["output_prefix"],
                    "images": ["8", 0]
                }
            }
        }
    }
    
    try:
        req = urllib.request.Request(
            f'{COMFYUI_URL}/prompt',
            data=json.dumps(prompt_data).encode('utf-8'),
            headers={'Content-Type': 'application/json'},
            method='POST'
        )
        
        with urllib.request.urlopen(req, timeout=10) as response:
            result = json.loads(response.read().decode('utf-8'))
            return True, result.get('prompt_id', 'unknown')
    except Exception as e:
        return False, str(e)

def main():
    print("=" * 70)
    print("🎬 短剧《总裁的替身前妻》第一集 - 场景图生成")
    print("=" * 70)
    print(f"\n📦 使用模型:{BEST_MODEL}")
    print(f"📊 场景数量:{len(SCENES)} 个")
    print("=" * 70)
    
    # 检查 ComfyUI 连接
    print("\n📡 检查 ComfyUI 连接...")
    try:
        req = urllib.request.Request(f'{COMFYUI_URL}/queue', method='GET')
        with urllib.request.urlopen(req, timeout=5) as response:
            queue = json.loads(response.read().decode('utf-8'))
            print(f"✅ ComfyUI 连接成功")
            print(f"   当前队列:{len(queue.get('queue_running', []))} 运行中,{len(queue.get('queue_pending', []))} 等待中")
    except Exception as e:
        print(f"❌ 无法连接 ComfyUI: {e}")
        return
    
    # 提交所有场景
    print("\n" + "=" * 70)
    print("🚀 开始提交生成任务...")
    print("=" * 70)
    
    success_count = 0
    for i, scene in enumerate(SCENES, 1):
        print(f"\n[{i}/{len(SCENES)}] {scene['name']}")
        
        success, result = submit_prompt(scene)
        
        if success:
            print(f"   ✅ 提交成功 (Prompt ID: {result})")
            success_count += 1
        else:
            print(f"   ❌ 提交失败:{result}")
        
        time.sleep(0.5)
    
    print("\n" + "=" * 70)
    print("📊 生成结果")
    print("=" * 70)
    print(f"✅ 成功:{success_count}/{len(SCENES)}")
    
    if success_count > 0:
        print(f"\n💾 图片将保存到:ComfyUI/output/")
        print(f"   文件名前缀:Drama_EP1_XX_场景名_")
        print(f"\n🌐 查看进度:http://127.0.0.1:8188")
    
    print("\n" + "=" * 70)
    
    # 显示场景列表
    print("\n📋 场景清单:")
    print("-" * 70)
    for scene in SCENES:
        print(f"  {scene['id']}. {scene['name']} - {scene['output_prefix']}")
    print("-" * 70)

if __name__ == "__main__":
    main()