#!/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 generate_image(prompt: str, filename: str) -> dict:
    """
    调用 OpenRouter API (Nano Banana 2) 生成图片
    返回：{"success": bool, "path": str|None, "error": str|None}
    """
    headers = {
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://openclaw.ai",
        "X-Title": "Trilingual Picturebook Generator"
    }
    
    # Nano Banana 2 / Gemini Image 的 API 格式
    payload = {
        "model": MODEL,
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "text",
                        "text": f"Generate an image. {prompt}"
                    }
                ]
            }
        ],
        "max_tokens": 1
    }
    
    try:
        print(f"📸 正在生成：{filename}...")
        response = requests.post(API_URL, headers=headers, json=payload, timeout=120)
        
        output_path = OUTPUT_DIR / f"{filename}.png"
        
        if response.status_code == 200:
            result = response.json()
            
            # 检查响应结构
            if "choices" in result and len(result["choices"]) > 0:
                message = result["choices"][0].get("message", {})
                content = message.get("content", "")
                
                # 尝试多种格式解析
                image_data = None
                
                # 格式 1: 直接 base64
                if isinstance(content, str):
                    if content.startswith("data:image"):
                        # data:image/png;base64,...
                        image_data = base64.b64decode(content.split(",")[1])
                    elif "base64" in content.lower():
                        import re
                        match = re.search(r'base64,([A-Za-z0-9+/=]+)', content)
                        if match:
                            image_data = base64.b64decode(match.group(1))
                
                # 格式 2: 结构化响应 (可能有 image_url 或类似字段)
                if isinstance(content, list):
                    for item in content:
                        if isinstance(item, dict):
                            if "image_url" in item:
                                url = item["image_url"]
                                if isinstance(url, dict):
                                    url = url.get("url", "")
                                # 下载图片
                                img_resp = requests.get(url, timeout=30)
                                if img_resp.status_code == 200:
                                    image_data = img_resp.content
                            elif "image" in item:
                                img_data = item["image"]
                                if img_data.startswith("http"):
                                    img_resp = requests.get(img_data, timeout=30)
                                    if img_resp.status_code == 200:
                                        image_data = img_resp.content
                                else:
                                    image_data = base64.b64decode(img_data)
                
                # 格式 3: 检查 response 中是否有直接的图片数据
                if not image_data and "images" in result:
                    images = result["images"]
                    if images and len(images) > 0:
                        img_data = images[0]
                        if isinstance(img_data, dict) and "image" in img_data:
                            img_data = img_data["image"]
                        if img_data.startswith("http"):
                            img_resp = requests.get(img_data, timeout=30)
                            if img_resp.status_code == 200:
                                image_data = img_resp.content
                        else:
                            image_data = base64.b64decode(img_data)
                
                # 格式 4: 检查 message 中的其他字段
                if not image_data:
                    for key in ["image", "image_url", "images", "data"]:
                        if key in message:
                            img_data = message[key]
                            if isinstance(img_data, str):
                                if img_data.startswith("http"):
                                    img_resp = requests.get(img_data, timeout=30)
                                    if img_resp.status_code == 200:
                                        image_data = img_resp.content
                                elif img_data.startswith("data:"):
                                    image_data = base64.b64decode(img_data.split(",")[1])
                                else:
                                    try:
                                        image_data = base64.b64decode(img_data)
                                    except:
                                        pass
                            break
                
                # 保存找到的图片
                if image_data:
                    with open(output_path, "wb") as f:
                        f.write(image_data)
                    print(f"✅ 已保存：{output_path}")
                    return {"success": True, "path": str(output_path), "error": None}
                else:
                    # 保存原始响应以便调试
                    debug_path = OUTPUT_DIR / f"{filename}.response.json"
                    with open(debug_path, "w") as f:
                        json.dump(result, f, indent=2, ensure_ascii=False)
                    print(f"⚠️  未找到图片数据，响应已保存到：{debug_path}")
                    return {"success": False, "path": None, "error": "No image data in response"}
            else:
                return {"success": False, "path": None, "error": f"No choices in response: {result}"}
        else:
            error_msg = f"API error {response.status_code}: {response.text[:300]}"
            print(f"❌ {error_msg}")
            return {"success": False, "path": None, "error": error_msg}
            
    except requests.exceptions.Timeout:
        return {"success": False, "path": None, "error": "Request 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
            else:
                print("❌ 未找到 Nano Banana 2 模型")
                return False
        else:
            print(f"❌ API 错误：{response.status_code}")
            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 = []
    
    for filename, prompt in prompts_to_use.items():
        result = generate_image(prompt, filename)
        results.append((filename, result))
        
        # 避免请求过快 (API 限流)
        if len(prompts_to_use) > 1:
            time.sleep(3)
    
    # 总结
    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} 张")
    
    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,
            "results": [(fn, r) for fn, r in results]
        }, f, indent=2, ensure_ascii=False)
    
    print(f"📄 生成记录：{record_path}")


if __name__ == "__main__":
    main()
