#!/usr/bin/env python3
"""
用 Well API 重新生成第 13-14 页
模型：Flux Pro - 角色一致性更好
质量：1k (512x512)
"""

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

# API 配置 - WellAPI
WELL_API_KEY = os.environ.get('WELL_API_KEY')
API_URL = "https://wellapi.ai/v1/images/generations"

# 模型：Flux Pro（角色一致性更好）
MODEL = "flux-pro"
IMAGE_SIZE = "512x512"  # 1k 质量

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


def generate_image(prompt: str, filename: str) -> dict:
    """调用 WellAPI 生成图片"""
    headers = {
        "Authorization": f"Bearer {WELL_API_KEY}",
        "Content-Type": "application/json"
    }
    
    payload = {
        "model": MODEL,
        "prompt": prompt,
        "size": IMAGE_SIZE,
        "n": 1
    }
    
    output_path = OUTPUT_DIR / f"{filename}.png"
    
    try:
        print(f"📸 生成：{filename}")
        print(f"   模型：{MODEL} | 尺寸：{IMAGE_SIZE}")
        
        response = requests.post(API_URL, headers=headers, json=payload, timeout=120)
        
        if response.status_code == 200:
            result = response.json()
            
            if "data" in result and len(result["data"]) > 0:
                image_url = result["data"][0].get("url")
                
                if image_url:
                    print(f"   📥 下载图片...")
                    img_response = requests.get(image_url, timeout=30)
                    if img_response.status_code == 200:
                        with open(output_path, "wb") as f:
                            f.write(img_response.content)
                        
                        file_size_kb = len(img_response.content) / 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"}
        else:
            print(f"   ❌ API 错误：{response.status_code}")
            print(f"   响应：{response.text[:200]}")
            return {"success": False, "error": f"API error {response.status_code}"}
            
    except Exception as e:
        print(f"   ❌ 错误：{e}")
        return {"success": False, "error": str(e)}


def main():
    print("=" * 60)
    print("📖 Well API 重新生成第 13-14 页")
    print("=" * 60)
    print(f"📁 输出目录：{OUTPUT_DIR}")
    print(f"📐 图片尺寸：{IMAGE_SIZE}")
    print(f"🎨 模型：{MODEL}")
    
    # 第 13 页 - 强化角色描述
    prompt_13 = """
children's book illustration, watercolor style, 2 year old Chinese twin boy and girl holding hands walking down wooden stairs together

Boy: short black hair, round chubby face, big bright eyes, wearing light blue t-shirt and shorts, leading the way, caring big brother expression

Girl: black hair with two small pigtails on top of head, round chubby face, pink dress, following brother, trusting expression

Warm morning sunlight streaming through window, cozy home interior, soft pastel colors, gentle watercolor brush strokes

Square composition, no text, no watermark, high quality, for toddlers picture book

IMPORTANT: Keep characters consistent - cute 2 year old Chinese twins, boy in blue, girl in pink with pigtails
"""
    
    # 第 14 页
    prompt_14 = """
children's book illustration, watercolor style, cute golden retriever puppy sitting at bottom of wooden stairs looking up happily

Puppy: fluffy golden fur, wagging tail, excited expression, tongue out slightly

In background: 2 year old Chinese twin boy and girl on stairs above (boy in blue outfit, girl in pink dress with pigtails), coming down to greet puppy

Warm morning light, cozy home interior, soft pastel colors, gentle watercolor style

Square composition, no text, no watermark, high quality, for toddlers picture book
"""
    
    results = []
    
    # 生成第 13 页
    print("\n--- 第 13 页 ---")
    result_13 = generate_image(prompt_13, "well-page-13-v2")
    results.append(("well-page-13-v2", result_13))
    
    # 等待 3 秒
    time.sleep(3)
    
    # 生成第 14 页
    print("\n--- 第 14 页 ---")
    result_14 = generate_image(prompt_14, "well-page-14-v2")
    results.append(("well-page-14-v2", result_14))
    
    # 保存结果日志
    log_path = OUTPUT_DIR / f"well-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)
    
    success_count = sum(1 for _, r in results if r.get("success"))
    print(f"✅ 成功：{success_count}/{len(results)}")
    print("=" * 60)


if __name__ == "__main__":
    main()
