#!/usr/bin/env python3
"""
三语绘本图像生成脚本
使用 OpenRouter API 调用 nano banana 2 模型生成绘本插图
"""

import os
import requests
import json
from pathlib import Path

# API 配置
OPENROUTER_API_KEY = os.environ.get('OPENROUTER_API_KEY')
API_URL = "https://openrouter.ai/api/v1/images/generations"

# 模型名称 - 请根据实际情况调整
MODEL = "nano-banana-2"  # 或 "nanobanana2" 或其他正确格式

# 输出目录
OUTPUT_DIR = Path("/root/.openclaw/workspace/trilingual-picturebook/output")
OUTPUT_DIR.mkdir(exist_ok=True)

# 角色提示词 (用于生成角色设定图)
CHARACTER_PROMPTS = {
    "character-boy-front": """children's book illustration, watercolor style, 
2 year old Chinese boy, short black hair, round face, big bright eyes, 
wearing light blue t-shirt, cute smile, looking at viewer, 
soft pastel colors, warm lighting, simple white background, 
for toddlers picture book, square composition, 
no text, no watermark, high quality, detailed face""",

    "character-boy-side": """children's book illustration, watercolor style, 
2 year old Chinese boy, short black hair, side profile view, 
wearing light blue t-shirt, cute expression, 
soft pastel colors, warm lighting, simple white background, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "character-girl-front": """children's book illustration, watercolor style, 
2 year old Chinese girl, black hair with two small pigtails, bangs, 
round face, big bright eyes, wearing pink dress, cute smile, 
looking at viewer, soft pastel colors, warm lighting, 
simple white background, for toddlers picture book, square composition, 
no text, no watermark, high quality, detailed face""",

    "character-girl-side": """children's book illustration, watercolor style, 
2 year old Chinese girl, black hair with two small pigtails, side profile, 
wearing pink dress, cute expression, 
soft pastel colors, warm lighting, simple white background, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",
}

# 《哥哥妹妹早上好》16 页提示词
GOODMORNING_PROMPTS = {
    "goodmorning-page-01": """children's book illustration, watercolor style, 
bright yellow sun rising outside bedroom window, 
small blue birds flying in sky, fluffy white clouds, 
morning golden light streaming through window, 
seen from inside bedroom, window frame visible, 
soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-02": """children's book illustration, watercolor style, 
2 year old Chinese boy with short black hair, 
sitting up in bed, stretching arms, yawning, 
wearing blue pajamas, messy morning hair, 
soft morning sunlight from window, bedroom scene, 
soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-03": """children's book illustration, watercolor style, 
2 year old Chinese girl with black hair and two small pigtails, 
sitting up in bed, stretching arms, cute yawn, 
wearing pink pajamas, sleepy expression, 
soft morning sunlight from window, bedroom scene, 
soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-04": """children's book illustration, watercolor style, 
2 year old Chinese boy and girl holding hands, 
boy in blue pajamas, girl in pink pajamas, 
walking together down hallway, morning light, 
soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-05": """children's book illustration, watercolor style, 
2 year old Chinese boy standing at bathroom sink, 
brushing teeth, toothbrush in hand, toothpaste foam on mouth, 
looking in bathroom mirror, blue pajamas, 
bathroom scene, soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-06": """children's book illustration, watercolor style, 
2 year old Chinese girl with pigtails at bathroom sink, 
brushing teeth, toothbrush in hand, cute expression, 
looking at boy next to her, pink pajamas, 
bathroom scene, soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-07": """children's book illustration, watercolor style, 
2 year old Chinese boy washing face with both hands, 
water splashing, white towel hanging nearby, 
blue pajamas, bathroom scene, 
soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-08": """children's book illustration, watercolor style, 
2 year old Chinese girl with pigtails drying face, 
using soft white towel, clean fresh face, happy expression, 
pink pajamas, bathroom scene, 
soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-09": """children's book illustration, watercolor style, 
2 year old Chinese boy putting on light blue t-shirt, 
arms in sleeves, bedroom scene, 
morning light from window, 
soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-10": """children's book illustration, watercolor style, 
2 year old Chinese girl pointing at boy, 
excited expression, clapping hands, 
boy standing proudly in blue t-shirt, 
bedroom scene, morning light, 
soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-11": """children's book illustration, watercolor style, 
2 year old Chinese boy helping girl button her dress, 
careful expression, girl waiting patiently, 
boy in blue t-shirt, girl in pink dress, 
bedroom scene, soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-12": """children's book illustration, watercolor style, 
2 year old Chinese boy and girl standing in front of mirror, 
both dressed nicely, looking at themselves, smiling, 
boy in blue outfit, girl in pink dress, 
bedroom scene, soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-13": """children's book illustration, watercolor style, 
2 year old Chinese boy and girl holding hands, 
walking down wooden stairs, boy leading, girl following, 
boy in blue outfit, girl in pink dress, 
soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-14": """children's book illustration, watercolor style, 
cute golden retriever puppy at bottom of stairs, 
looking up, wagging tail, happy expression, 
boy and girl visible on stairs above, 
soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-15": """children's book illustration, watercolor style, 
2 year old Chinese boy and girl petting golden puppy, 
gentle touches, puppy enjoying with eyes closed happily, 
living room scene, morning light, 
soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",

    "goodmorning-page-16": """children's book illustration, watercolor style, 
2 year old Chinese boy and girl with golden puppy, 
sitting together by window, looking outside, 
bright sunshine streaming in, peaceful scene, 
soft pastel colors, warm lighting, 
for toddlers picture book, square composition, 
no text, no watermark, high quality""",
}


def generate_image(prompt: str, filename: str, size: str = "1024x1024") -> bool:
    """
    调用 OpenRouter API 生成单张图片
    """
    headers = {
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://openclaw.ai",
        "X-Title": "Trilingual Picturebook Generator"
    }
    
    payload = {
        "model": MODEL,
        "prompt": prompt,
        "size": size,
        "n": 1,
        "response_format": "url"
    }
    
    try:
        print(f"📸 正在生成：{filename}...")
        response = requests.post(API_URL, headers=headers, json=payload, timeout=60)
        response.raise_for_status()
        
        result = response.json()
        
        # 解析响应
        if "data" in result and len(result["data"]) > 0:
            image_url = result["data"][0].get("url")
            
            if image_url:
                # 下载图片
                img_response = requests.get(image_url, timeout=30)
                img_response.raise_for_status()
                
                # 保存图片
                output_path = OUTPUT_DIR / f"{filename}.png"
                with open(output_path, "wb") as f:
                    f.write(img_response.content)
                
                print(f"✅ 已保存：{output_path}")
                return True
            else:
                print(f"❌ 未返回图片 URL: {result}")
                return False
        else:
            print(f"❌ 响应格式异常：{result}")
            return False
            
    except requests.exceptions.RequestException as e:
        print(f"❌ API 请求失败：{e}")
        if hasattr(e, 'response') and e.response is not None:
            print(f"   响应内容：{e.response.text[:500]}")
        return False
    except Exception as e:
        print(f"❌ 生成失败：{e}")
        return False


def test_connection():
    """
    测试 API 连接
    """
    print("🔍 测试 OpenRouter API 连接...")
    
    headers = {
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
    }
    
    try:
        # 尝试获取模型列表
        response = requests.get("https://openrouter.ai/api/v1/models", headers=headers, timeout=10)
        if response.status_code == 200:
            print("✅ API 连接成功")
            models = response.json().get("data", [])
            print(f"📦 可用模型数量：{len(models)}")
            
            # 查找 nano banana 相关模型
            nano_models = [m for m in models if "nano" in m.get("id", "").lower() or "banana" in m.get("id", "").lower()]
            if nano_models:
                print("🍌 找到 nano/banana 相关模型:")
                for m in nano_models:
                    print(f"   - {m.get('id')}")
            return True
        else:
            print(f"❌ API 连接失败：{response.status_code}")
            print(f"   响应：{response.text[:200]}")
            return False
    except Exception as e:
        print(f"❌ 测试失败：{e}")
        return False


def main():
    """
    主函数
    """
    print("=" * 60)
    print("📚 三语绘本图像生成器")
    print("=" * 60)
    
    if not OPENROUTER_API_KEY:
        print("❌ 错误：未设置 OPENROUTER_API_KEY 环境变量")
        return
    
    # 测试连接
    if not test_connection():
        print("\n⚠️  API 连接测试失败，但仍尝试生成...")
    
    # 选择生成模式
    print("\n请选择生成模式:")
    print("1. 仅生成角色设定图 (4 张)")
    print("2. 生成《哥哥妹妹早上好》全书 (16 张)")
    print("3. 生成全部 (20 张)")
    print("4. 自定义页码")
    
    choice = input("\n请输入选项 (1-4): ").strip()
    
    prompts_to_use = {}
    
    if choice == "1":
        prompts_to_use = CHARACTER_PROMPTS
    elif choice == "2":
        prompts_to_use = GOODMORNING_PROMPTS
    elif choice == "3":
        prompts_to_use = {**CHARACTER_PROMPTS, **GOODMORNING_PROMPTS}
    elif choice == "4":
        print("\n可用页码:")
        print("角色图：character-boy-front, character-boy-side, character-girl-front, character-girl-side")
        print("绘本页：goodmorning-page-01 到 goodmorning-page-16")
        pages = input("请输入页码 (逗号分隔): ").strip()
        for page in pages.split(","):
            page = page.strip()
            if page in CHARACTER_PROMPTS:
                prompts_to_use[page] = CHARACTER_PROMPTS[page]
            elif page in GOODMORNING_PROMPTS:
                prompts_to_use[page] = GOODMORNING_PROMPTS[page]
            else:
                print(f"⚠️  未找到页码：{page}")
    else:
        print("❌ 无效选项")
        return
    
    if not prompts_to_use:
        print("❌ 没有要生成的内容")
        return
    
    print(f"\n📝 将生成 {len(prompts_to_use)} 张图片")
    print(f"📁 输出目录：{OUTPUT_DIR}")
    print("\n" + "=" * 60)
    
    # 生成图片
    success_count = 0
    fail_count = 0
    
    for filename, prompt in prompts_to_use.items():
        if generate_image(prompt, filename):
            success_count += 1
        else:
            fail_count += 1
        
        # 避免请求过快
        import time
        time.sleep(2)
    
    # 总结
    print("\n" + "=" * 60)
    print("📊 生成完成!")
    print(f"✅ 成功：{success_count} 张")
    print(f"❌ 失败：{fail_count} 张")
    print(f"📁 输出目录：{OUTPUT_DIR}")
    print("=" * 60)


if __name__ == "__main__":
    main()
