#!/usr/bin/env python3
"""
Generate anime opening key frames for Broken Spire - REVISED
Using detailed character descriptions from visual canon
"""

import requests
import time

COMFYUI_URL = "https://mu1aafo3zo4da1-8188.proxy.runpod.net"

# Detailed prompts based on visual canon - more specific to match reference images
FRAMES = [
    {
        "name": "01_void",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, dark void, fractured clock faces spinning backward, glitch effects, purple energy cracks, blue temporal distortion, cinematic lighting, dark atmosphere, epic, no humans"
    },
    {
        "name": "02_ash_birth",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1boy, solo, young adult, early twenties, blond hair, medium length, messy, falling across forehead, pale skin, slim athletic body, dancer build, defined muscles but not bulky, black tribal tattoos on arm and shoulder, sharp organic claw flame pattern tattoos, large expressive anime eyes, strong cheekbones but soft androgynous face, fragile beautiful look, dark cosmic background, temporal energy, dramatic backlighting, intense, masterpiece"
    },
    {
        "name": "03_far_future_ash_evil",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1man, solo, mature, late thirties, long white hair flowing, pale skin, glowing red eyes, terrifying expression, dark aura, menacing, multiple arms with weapons, dark armor, glowing red hexcore patterns on armor, floating, surrounded by dark energy, god of death, apocalyptic, destroyed city, red sky, horror, scary, evil, brutal, villain, menacing presence"
    },
    {
        "name": "04_post_apocalyptic_city",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, cityscape, post-apocalyptic, ruined buildings, crumbling towers, neon signs flickering, blue hexcore energy pillars, augmented soldiers patrolling, rain, ash covered streets, dark cyberpunk, dramatic lighting, cinematic, wide shot, atmospheric, dystopian"
    },
    {
        "name": "05_everly_soldier",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1woman, solo, mid thirties, short dark hair, intense eyes, military uniform, tactical gear, multiple weapons, dark expression, dark humor, confident pose, hand on weapon, scars, dramatic lighting, cinematic, from below, powerful, dangerous, cyberpunk, dark sci-fi, dominant energy"
    },
    {
        "name": "06_eva_doctor",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1woman, solo, french woman, shoulder length brown hair, professional, intense eyes, lab coat, medical clothing, surgical gloves, focused expression, intelligent, blunt, emotionally guarded, sterile medical environment, blue medical lights, cyberpunk clinic, detailed background, doctor"
    },
    {
        "name": "07_nova_warrior",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1woman, solo, late twenties, long flowing red hair, playful fierce expression, combat gear, multiple stylish weapons, dynamic action pose, battle stance, war artist energy, stylish lethal, ruins background, explosion, dramatic lighting, cinematic, anime action, intense, war scene, beautiful violence"
    },
    {
        "name": "08_violet_devil",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1woman, solo, long purple hair, red devil horns, glowing red eyes, devil form dark wings, elegant dangerous pose, claws, beautiful and terrifying, dark aura, crimson energy, night background, dramatic lighting, horror, duality, human and devil forms"
    },
    {
        "name": "08_violet_human",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1woman, solo, long purple hair, human form, gentle expression, soft features, elegant, beautiful, detailed face, dramatic lighting, cyberpunk, emotional"
    },
    {
        "name": "09_nova_human",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1woman, solo, long red hair, human form, soft expression, warm, beautiful, detailed face, detailed eyes, dramatic lighting, romantic, emotional"
    },
    {
        "name": "10_lin_weishan",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1woman, solo, asian woman, long black hair, determined expression, combat clothing, martial arts, detailed face, dramatic lighting, cyberpunk, action, intense, fighter"
    },
    {
        "name": "11_tc23_esper",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1woman, solo, mechanical body parts, cybernetic augments, glowing cybernetic eyes, esper powers, glowing energy, futuristic outfit, robot parts, detailed machinery, sci-fi, cyberpunk, esper, mechanical"
    },
    {
        "name": "12_tk_character",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1man, solo, young adult, detailed face, cyberpunk, futuristic, combat ready, dramatic lighting, sci-fi"
    },
    {
        "name": "13_seraphine_vale",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1woman, solo, elegant, detailed face, long hair, royal appearance, powerful, detailed, dramatic lighting, fantasy, cyberpunk"
    },
    {
        "name": "14_jonas_ghost",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1man, solo, large muscular build, scarred face, short brown hair, warm smile, ghost effect, ethereal, fading, memories, nostalgic, emotional, memorial, husband"
    },
    {
        "name": "15_berserk_battle",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, action scene, intense battle, blood splatter, gore, brutal combat, multiple characters, weapons, explosions, dynamic, fast action, dark sci-fi, anime, cinematic, violent, intense, berserk style, dark fantasy, horror, 18+"
    },
    {
        "name": "16_ash_everly_tension",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1man and 1woman, couple, blond man and dark haired woman, close together, intense eye contact, emotional tension, sexual tension, dark romance, 18+, mature, dramatic lighting, cinematic, close-up, cyberpunk, beautiful"
    },
    {
        "name": "17_ash_eva_medical",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1man and 1woman, couple, blond man and brown haired french woman, medical setting, gentle touch, her hand on his cheek, tender, emotional, warm lighting, intimate, 18+, mature, romantic, cyberpunk, beautiful"
    },
    {
        "name": "18_ash_nova_war",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1man and 1woman, couple, blond man and red haired woman, together, exhausted, rare smile, battle aftermath, holding hands, warm moment, intimate, dramatic lighting, cinematic, 18+, mature, romantic, war romance"
    },
    {
        "name": "19_far_future_ash_watching",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1man, solo, far future, long white hair flowing, glowing red eyes, dark silhouette, watching from shadows, menacing, terrifying, horror, suspense, building tension, dramatic lighting, threatening, villain"
    },
    {
        "name": "20_all_characters",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, multiple characters, group shot, blond man and multiple women, triangular composition, dramatic, emotional, intense, hexcore energy, different timelines, cosmic background, 18+, mature, dark romance, cyberpunk, cinematic, beautiful composition"
    },
    {
        "name": "21_title_card",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, title card, BROKEN SPIRE text, glitch effects, broken sun, ruined city, characters as shadows, cinematic, dramatic, epic, dark sci-fi, poster style"
    },
    {
        "name": "22_ash_walking_hope",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, 1man, solo, young adult, blond hair, walking away, back view, broken sun horizon half black hole half burning, shattered city, rain, atmospheric, cinematic, dramatic, hopeful, beautiful, melancholic, epic"
    },
    {
        "name": "23_final_text",
        "prompt": "masterpiece, best quality, very aesthetic, absurdres, text EVERY CYCLE BEGINS WITH AN END, dark background, cinematic, dramatic, epic, minimal"
    }
]

NEGATIVE_PROMPT = "lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry, artist name"

def queue_prompt(positive_prompt, filename_prefix):
    payload = {
        "prompt": {
            "1": {"class_type": "CheckpointLoaderSimple", "inputs": {"ckpt_name": "animagine-xl-3.1.safetensors"}},
            "2": {"class_type": "CLIPTextEncode", "inputs": {"text": positive_prompt, "clip": ["1", 1]}},
            "3": {"class_type": "CLIPTextEncode", "inputs": {"text": NEGATIVE_PROMPT, "clip": ["1", 1]}},
            "4": {"class_type": "EmptyLatentImage", "inputs": {"width": 832, "height": 1216, "batch_size": 1}},
            "5": {"class_type": "KSampler", "inputs": {"seed": 42, "steps": 28, "cfg": 7, "sampler_name": "euler_ancestral", "scheduler": "normal", "denoise": 1.0, "model": ["1", 0], "positive": ["2", 0], "negative": ["3", 0], "latent_image": ["4", 0]}},
            "6": {"class_type": "VAEDecode", "inputs": {"samples": ["5", 0], "vae": ["1", 2]}},
            "7": {"class_type": "SaveImage", "inputs": {"filename_prefix": filename_prefix, "images": ["6", 0]}}
        }
    }
    
    response = requests.post(f"{COMFYUI_URL}/api/prompt", json=payload)
    return response.json()

def check_queue():
    response = requests.get(f"{COMFYUI_URL}/api/queue")
    return response.json()

def main():
    print("Starting REVISED Broken Spire frame generation...")
    print(f"Total frames: {len(FRAMES)}")
    
    for i, frame in enumerate(FRAMES):
        print(f"\nGenerating frame {i+1}/{len(FRAMES)}: {frame['name']}")
        
        result = queue_prompt(frame['prompt'], frame['name'])
        print(f"  Result: {result.get('prompt_id', 'error')}")
        
        # Wait for completion
        while True:
            queue_status = check_queue()
            if not queue_status.get('queue_running') and not queue_status.get('queue_pending'):
                break
            time.sleep(2)
        
        time.sleep(1)
    
    print("\nAll frames generated!")

if __name__ == "__main__":
    main()