#!/usr/bin/env python3
"""
重新生成第 13-14 页 - 使用优化后的角色一致性提示词
图片质量：1k (512x512)
"""

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"
MODEL = "google/gemini-3.1-flash-image-preview"

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

# 角色参考图路径
CHARACTER_SHEET_DIR = Path("/root/.openclaw/workspace/trilingual-picturebook")
YANGYANG_REF = CHARACTER_SHEET_DIR / "_charsheet_yangyang.png"
ZHUAZHUA_REF = CHARACTER_SHEET_DIR / "_charsheet_zhuazhua.png"

# 图像分辨率 - 1k 质量
IMAGE_SIZE = "512x512"


def load_image_as_base64(image_path: Path) -> str:
    """加载图片为 base64 data URL"""
    with open(image_path, "rb") as f:
        image_data = f.read()
    base64_data = base64.b64encode(image_data).decode('utf-8')
    return f"data:image/png;base64,{base64_data}"


def generate_image(prompt_text: str, filename: str, use_references: bool = True):
    """生成单张图片"""
    print(f"\n📸 生成：{filename}")
    
    headers = {
        "Authorization": f"Bearer {OPENROUTER_API_KEY}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://openclaw.ai",
        "X-Title": "Picturebook Regenerator"
    }
    
    # 构建消息内容
    content_parts = []
    
    # 添加参考图（如果使用）
    if use_references:
        if YANGYANG_REF.exists():
            print(f"   📎 参考图：yangyang")
            content_parts.append({
                "type": "image_url",
                "image_url": load_image_as_base64(YANGYANG_REF)
            })
        if ZHUAZHUA_REF.exists():
            print(f"   📎 参考图：zhuazhua")
            content_parts.append({
                "type": "image_url",
                "image_url": load_image_as_base64(ZHUAZHUA_REF)
            })
    
    # 添加文字提示词 - 强调角色一致性
    content_parts.append({
        "type": "text",
        "text": f"""IMPORTANT: Use the provided character reference images to maintain consistent character appearance.

{prompt_text}

Style: children's book illustration, watercolor style, soft pastel colors, warm lighting
Characters: Keep consistent with reference images (2 year old Chinese twins)
Composition: square, no text, no watermark, high quality
Resolution: {IMAGE_SIZE}"""
    })
    
    payload = {
        "model": MODEL,
        "messages": [
            {
                "role": "user",
                "content": content_parts
            }
        ],
        "max_tokens": 1000
    }
    
    # 发送请求（带重试）
    max_retries = 5
    base_delay = 10
    
    for attempt in range(max_retries):
        try:
            response = requests.post(API_URL, headers=headers, json=payload, timeout=120)
            
            if response.status_code == 429:
                wait_time = base_delay * (2 ** attempt)
                print(f"   ⏳ 限流，等待 {wait_time} 秒...")
                time.sleep(wait_time)
                continue
            
            response.raise_for_status()
            result = response.json()
            
            # 提取图片
            if "choices" in result and len(result["choices"]) > 0:
                message = result["choices"][0].get("message", {})
                if "images" in message and len(message["images"]) > 0:
                    image_url = message["images"][0].get("image_url", "")
                    if isinstance(image_url, dict):
                        image_url = image_url.get("url", "")
                    
                    if image_url.startswith("data:image"):
                        image_data = base64.b64decode(image_url.split(",")[1])
                    else:
                        image_resp = requests.get(image_url, timeout=30)
                        image_data = image_resp.content
                    
                    # 保存图片
                    output_path = OUTPUT_DIR / f"{filename}.png"
                    with open(output_path, "wb") as f:
                        f.write(image_data)
                    
                    file_size_kb = len(image_data) / 1024
                    print(f"   ✅ 已保存：{filename} ({file_size_kb:.1f} KB)")
                    return {"success": True, "path": str(output_path), "size_kb": file_size_kb}
            
            print(f"   ❌ 未返回图片数据")
            return {"success": False, "error": "No image data"}
            
        except Exception as e:
            print(f"   ❌ 错误：{e}")
            if attempt < max_retries - 1:
                wait_time = base_delay * (2 ** attempt)
                time.sleep(wait_time)
            else:
                return {"success": False, "error": str(e)}
    
    return {"success": False, "error": "Max retries exceeded"}


def main():
    print("=" * 60)
    print("📖 重新生成第 13-14 页（优化角色一致性）")
    print("=" * 60)
    print(f"📁 输出目录：{OUTPUT_DIR}")
    print(f"📐 图片尺寸：{IMAGE_SIZE}")
    print(f"📎 角色参考：yangyang + zhuazhua")
    
    # 第 13 页提示词 - 优化版
    prompt_13 = """
Scene: Twin toddlers holding hands, walking down wooden stairs together

Character details (MUST match reference images):
- Boy (yangyang): 2 year old Chinese boy, short black hair, round face, wearing light blue outfit, leading the way
- Girl (zhuazhua): 2 year old Chinese girl, black hair with two small pigtails, round face, wearing pink dress, following brother

Emotion: Warm sibling bond, brother protecting sister, gentle morning light

Action: Boy holds girl's hand, carefully guiding her down the stairs, both looking down at steps

Background: Wooden staircase in home, soft morning sunlight from window, warm cozy atmosphere

Style notes: Watercolor illustration for toddlers, soft edges, pastel colors, square composition
"""
    
    # 第 14 页提示词 - 优化版
    prompt_14 = """
Scene: Golden retriever puppy greeting the twins at bottom of stairs

Character details (MUST match reference images):
- Boy (yangyang): 2 year old Chinese boy, short black hair, blue outfit, visible on stairs above
- Girl (zhuazhua): 2 year old Chinese girl, black hair with pigtails, pink dress, visible on stairs above
- Puppy: Cute golden retriever puppy, sitting at bottom of stairs, looking up excitedly

Emotion: Joyful greeting, puppy happy to see the children, tail wagging

Action: Puppy looking up at the twins with happy expression, twins about to reach bottom of stairs

Background: Bottom of wooden staircase, home interior, warm morning light

Style notes: Watercolor illustration for toddlers, soft edges, pastel colors, square composition
"""
    
    results = []
    
    # 生成第 13 页
    result_13 = generate_image(prompt_13, "gemini-page-13-retry", use_references=True)
    results.append(("gemini-page-13-retry", result_13))
    
    # 等待一下
    time.sleep(3)
    
    # 生成第 14 页
    result_14 = generate_image(prompt_14, "gemini-page-14-retry", use_references=True)
    results.append(("gemini-page-14-retry", result_14))
    
    # 保存结果日志
    log_path = OUTPUT_DIR / f"regenerate-log-{datetime.now().strftime('%Y%m%d-%H%M%S')}.json"
    with open(log_path, "w", encoding="utf-8") as f:
        json.dump(results, f, ensure_ascii=False, indent=2)
    
    print(f"\n📋 结果日志：{log_path}")
    print("\n" + "=" * 60)
    print("✅ 生成完成！")
    print("=" * 60)


if __name__ == "__main__":
    main()
