#!/usr/bin/env python3
"""
重试第 13 页 - Well API
"""

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

WELL_API_KEY = os.environ.get('WELL_API_KEY')
API_URL = "https://wellapi.ai/v1/images/generations"
MODEL = "flux-pro"
IMAGE_SIZE = "512x512"
OUTPUT_DIR = Path("/root/.openclaw/workspace/trilingual-picturebook/output")

def generate_image(prompt: str, filename: str) -> dict:
    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}")
        response = requests.post(API_URL, headers=headers, json=payload, timeout=180)
        
        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=60)
                    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}
            return {"success": False, "error": "No image data"}
        else:
            print(f"   ❌ API 错误：{response.status_code}")
            return {"success": False, "error": f"API error {response.status_code}"}
    except Exception as e:
        print(f"   ❌ 错误：{e}")
        return {"success": False, "error": str(e)}

# 第 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
"""

result = generate_image(prompt_13, "well-page-13-v3")
print(f"\n结果：{result}")
