#!/usr/bin/env python3
"""
三语绘本图像生成脚本 - Nano Banana 2 正式版
使用 OpenRouter API 调用 Google Gemini 3.1 Flash Image Preview (Nano Banana 2)
"""

import os
import requests
import json
import base64
import time
from pathlib import Path
from datetime import datetime

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

# 模型：Nano Banana 2
MODEL = "google/gemini-3.1-flash-image-preview"

# 输出目录
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 extract_image_data(result: dict) -> bytes | None:
    """
    从 API 响应中提取图片数据
    """
    try:
        # Nano Banana 2 的响应格式：choices[0].message.images[0].image_url.url
        if "choices" in result and len(result["choices"]) > 0:
            message = result["choices"][0].get("message", {})
            
            if "images" in message:
                images = message["images"]
                if images and len(images) > 0:
                    image_obj = images[0]
                    
                    # 获取 image_url
                    if "image_url" in image_obj:
                        image_url_obj = image_obj["image_url"]
                        url = image_url_obj if isinstance(image_url_obj, str) else image_url_obj.get("url", "")
                        
                        # 解析 data URL
                        if url.startswith("data:image"):
                            # data:image/png;base64,xxxxx
                            base64_data = url.split(",")[1]
                            return base64.b64decode(base64_data)
                        elif url.startswith("http"):
                            # 直接下载
                            resp = requests.get(url, timeout=30)
                            if resp.status_code == 200:
                                return resp.content
    except Exception as e:
        print(f"   提取图片失败：{e}")
    
    return None


def generate_image(prompt: str, filename: str) -> dict:
    """
    调用 OpenRouter API (Nano Banana 2) 生成图片
    """
    headers = {
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://openclaw.ai",
        "X-Title": "Trilingual Picturebook Generator"
    }
    
    payload = {
        "model": MODEL,
        "messages": [
            {"role": "user", "content": f"Generate an image: {prompt}"}
        ],
        "response_format": {"type": "image"}
    }
    
    output_path = OUTPUT_DIR / f"{filename}.png"
    
    try:
        print(f"📸 正在生成：{filename}...")
        response = requests.post(API_URL, headers=headers, json=payload, timeout=120)
        
        if response.status_code == 200:
            result = response.json()
            image_data = extract_image_data(result)
            
            if image_data:
                with open(output_path, "wb") as f:
                    f.write(image_data)
                
                # 获取图片大小
                file_size = len(image_data) / 1024  # KB
                
                print(f"✅ 已保存：{output_path} ({file_size:.1f} KB)")
                return {"success": True, "path": str(output_path), "size_kb": file_size}
            else:
                print(f"⚠️  未找到图片数据")
                return {"success": False, "path": None, "error": "No image data"}
        else:
            error_msg = f"API error {response.status_code}: {response.text[:200]}"
            print(f"❌ {error_msg}")
            return {"success": False, "path": None, "error": error_msg}
            
    except requests.exceptions.Timeout:
        return {"success": False, "path": None, "error": "Timeout"}
    except Exception as e:
        return {"success": False, "path": None, "error": str(e)}


def test_model():
    """测试模型连接"""
    print("🔍 测试 Nano Banana 2 模型...")
    
    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:
            models = response.json().get("data", [])
            nano_banana = [m for m in models if "gemini-3.1-flash-image" in m.get("id", "")]
            
            if nano_banana:
                model = nano_banana[0]
                print(f"✅ 模型：{model.get('id')}")
                print(f"   名称：{model.get('name', 'N/A')}")
                return True
        print("❌ 未找到模型")
        return False
    except Exception as e:
        print(f"❌ 测试失败：{e}")
        return False


def main():
    """主函数"""
    print("=" * 60)
    print("📚 三语绘本图像生成器")
    print("🍌 Google Nano Banana 2 (Gemini 3.1 Flash Image)")
    print("=" * 60)
    
    if not OPENROUTER_API_KEY:
        print("❌ 错误：未设置 OPENROUTER_API_KEY")
        return
    
    if not test_model():
        print("\n⚠️  模型测试失败，但仍尝试生成...")
    
    # 选择生成模式
    print("\n请选择生成模式:")
    print("1. 仅生成角色设定图 (4 张)")
    print("2. 生成《哥哥妹妹早上好》全书 (16 张)")
    print("3. 生成全部 (20 张)")
    print("4. 自定义页码")
    print("5. 测试生成 (1 张)")
    
    choice = input("\n请输入选项 (1-5): ").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}")
    elif choice == "5":
        prompts_to_use = {"test-001": CHARACTER_PROMPTS["character-boy-front"]}
    else:
        print("❌ 无效选项")
        return
    
    if not prompts_to_use:
        print("❌ 没有要生成的内容")
        return
    
    print(f"\n📝 将生成 {len(prompts_to_use)} 张图片")
    print(f"📁 输出目录：{OUTPUT_DIR}")
    print(f"🍌 模型：{MODEL}")
    print("\n" + "=" * 60)
    
    # 生成图片
    results = []
    total_size = 0
    
    for filename, prompt in prompts_to_use.items():
        result = generate_image(prompt, filename)
        results.append((filename, result))
        
        if result["success"]:
            total_size += result.get("size_kb", 0)
        
        # API 限流控制
        if len(prompts_to_use) > 1:
            time.sleep(5)
    
    # 总结
    print("\n" + "=" * 60)
    print("📊 生成完成!")
    
    success_count = sum(1 for _, r in results if r["success"])
    fail_count = len(results) - success_count
    
    print(f"✅ 成功：{success_count} 张")
    print(f"❌ 失败：{fail_count} 张")
    print(f"💾 总大小：{total_size:.1f} KB")
    
    if fail_count > 0:
        print("\n失败的项:")
        for filename, result in results:
            if not result["success"]:
                print(f"  - {filename}: {result['error']}")
    
    print(f"\n📁 输出目录：{OUTPUT_DIR}")
    print("=" * 60)
    
    # 生成记录
    record_path = OUTPUT_DIR / f"generation-log-{datetime.now().strftime('%Y%m%d-%H%M%S')}.json"
    with open(record_path, "w", encoding="utf-8") as f:
        json.dump({
            "model": MODEL,
            "timestamp": datetime.now().isoformat(),
            "total": len(prompts_to_use),
            "success": success_count,
            "failed": fail_count,
            "total_size_kb": total_size,
            "results": [(fn, r) for fn, r in results]
        }, f, indent=2, ensure_ascii=False)
    
    print(f"📄 生成记录：{record_path}")


if __name__ == "__main__":
    main()
