"""
一键生成朋友圈配图 → 保存到 moments_img/ 目录
运行方式: cd C:\trae_project\scan\parent_companion && python generate_moments_images.py
前提: tts_server.py 已启动（localhost:8000）
"""

import requests, base64, os, sys

BACKEND = "http://localhost:8000"
OUT_DIR = "moments_img"
os.makedirs(OUT_DIR, exist_ok=True)

IMAGES = {
    "hongshaorou": (
        "Overhead view of a Chinese family dinner table with multiple home-cooked dishes, "
        "the main dish is a white plate of red braised pork (红烧肉) in the center foreground, "
        "around it there is a plate of stir-fried green vegetables (炒青菜), "
        "a bowl of soup with meat, a small dish of cold tofu appetizer, "
        "a bowl of white rice with chopsticks resting on top of the bowl, "
        "the table surface is plain light colored, "
        "overhead fluorescent kitchen light giving a slightly cool white illumination, "
        "phone photo taken from above looking straight down at the table, "
        "multiple dishes partially overlapping the frame edges, "
        "authentic messy Chinese family dinner for 2-3 people, not styled, "
        "no chopsticks lying on the table surface, "
        "no text no watermark, realistic casual phone photo"
    ),
    "sunset": (
        "Golden hour sunset seen from a typical Chinese apartment balcony, "
        "warm orange sky with clouds, residential tower blocks in the background, "
        "on the balcony there are messy potted flowers, a drying rack with some clothes, "
        "old slippers on the floor, concrete balcony railing, "
        "taken casually leaning on the railing with a phone, "
        "not a perfect composition, feels like a real middle-aged woman took this, "
        "warm nostalgic golden light, everyday Chinese urban balcony scene, "
        "no text no watermark, realistic casual phone photo"
    ),
    "knitting": (
        "A half-finished hand-knitted scarf in cream white and soft pink yarn, "
        "laid out on a grey fabric sofa, a knitting pattern magazine or book propped up "
        "behind it showing a scarf design, two balls of yarn in cream and pink colors "
        "sitting next to the knitting, bamboo or wooden knitting needles still attached, "
        "a fluffy white cushion or pillow in the background, "
        "wooden furniture like a chair or railing partially visible, "
        "warm natural afternoon daylight from a window with curtains, "
        "cozy lived-in Chinese living room atmosphere, "
        "phone photo taken at a slight angle looking down at the sofa, "
        "no text no watermark, realistic casual domestic photo"
    ),
    "morning_market": (
        "Handheld phone photo at a busy Chinese wet morning market (菜市场), "
        "a vendor stall with piles of red tomatoes and green leafy vegetables, "
        "a small plastic basket with bright red strawberries, "
        "price tags written by hand on cardboard, plastic bags everywhere, "
        "other shoppers partially visible, fluorescent or natural morning light, "
        "slightly crowded and messy authentic Chinese market atmosphere, "
        "taken quickly while shopping not carefully composed, "
        "some motion blur is okay, vibrant everyday colors, "
        "no text no watermark, realistic casual phone photo"
    ),

    # ── 温柔爸爸 ──
    "dad_ocean": (
        "Ocean waves crashing on a rocky beach shore, "
        "blue sky with some white clouds, clear daylight, "
        "shot from standing on the beach looking out at the sea, "
        "some wet rocks and sand in the foreground, "
        "casual phone photo taken by a middle-aged man on vacation, "
        "slightly tilted angle not perfectly composed, "
        "natural bright daylight, peaceful seaside atmosphere, "
        "no people in the frame, no text no watermark, realistic phone photo"
    ),
    "dad_meal": (
        "Overhead view of a simple Chinese home dinner for one or two people, "
        "a whole steamed or pan-fried fish on a white plate as the main dish, "
        "a small plate of stir-fried green vegetables, a bowl of rice, "
        "a glass of beer or tea, a small dish of dipping sauce, "
        "plain dining table surface slightly cluttered, "
        "warm overhead kitchen light, chopsticks resting on the bowl, "
        "casual phone photo taken from above, "
        "simple bachelor-style or middle-aged man cooking for himself, "
        "not fancy not styled, authentic everyday meal, "
        "no text no watermark, realistic casual phone photo"
    ),
    "dad_ancient_town": (
        "A street view of an ancient Chinese town (古镇/古城), "
        "traditional architecture with grey brick walls and curved tile roofs, "
        "old stone-paved street, a few tourists walking in the distance, "
        "red lanterns hanging from the eaves, old wooden shop fronts, "
        "overcast or soft daylight, autumn atmosphere, "
        "taken while walking down the street with a phone, "
        "slightly off-center composition like a tourist snapped it casually, "
        "authentic Chinese historic town atmosphere, "
        "no text no watermark, realistic casual travel photo"
    ),
    "dad_fishing": (
        "A small caught fish on a newspaper or plastic sheet next to a river bank, "
        "a simple fishing rod lying beside it, a plastic bucket or tackle box nearby, "
        "grass and dirt ground, river water visible in the background, "
        "afternoon natural daylight, relaxed outdoor fishing scene, "
        "taken with phone looking down at the catch, "
        "casual angle like a dad proudly showing his small catch, "
        "not professional photography, everyday leisure moment, "
        "no text no watermark, realistic casual phone photo"
    ),
}

def generate_and_save(name, prompt):
    path = os.path.join(OUT_DIR, f"{name}.jpg")
    if os.path.exists(path):
        print(f"  ⏭ {name}.jpg 已存在，跳过（删除后重新运行可重新生成）")
        return True

    print(f"  ⏳ 正在生成 {name}...")
    try:
        resp = requests.post(
            f"{BACKEND}/v1/images/generate",
            json={"prompt": prompt, "size": "1024x1024", "quality": "medium"},
            timeout=120,
        )
        resp.raise_for_status()
        data = resp.json()

        url = data.get("url") or (data.get("data", [{}])[0].get("url"))
        b64_data = data.get("b64_json") or (data.get("data", [{}])[0].get("b64_json"))

        if b64_data:
            img_bytes = base64.b64decode(b64_data)
        elif url:
            img_resp = requests.get(url, timeout=60)
            img_resp.raise_for_status()
            img_bytes = img_resp.content
        else:
            print(f"  ✗ {name} 返回数据无 url 也无 b64_json")
            return False

        with open(path, "wb") as f:
            f.write(img_bytes)
        size_kb = len(img_bytes) / 1024
        print(f"  ✓ {name}.jpg 已保存 ({size_kb:.0f} KB)")
        return True

    except Exception as e:
        print(f"  ✗ {name} 生成失败: {e}")
        return False

if __name__ == "__main__":
    print("=" * 50)
    print("朋友圈配图生成器")
    print(f"后端: {BACKEND}")
    print(f"输出: {OUT_DIR}/")
    print("=" * 50)

    # 检查后端是否在线
    try:
        requests.get(f"{BACKEND}/docs", timeout=5)
    except Exception:
        print("\n❌ 后端未启动！请先运行: python server\\tts_server.py")
        sys.exit(1)

    print(f"\n共 {len(IMAGES)} 张图片待生成:\n")
    success = 0
    for name, prompt in IMAGES.items():
        if generate_and_save(name, prompt):
            success += 1

    print(f"\n{'=' * 50}")
    print(f"完成: {success}/{len(IMAGES)} 张")
    if success == len(IMAGES):
        print("✅ 全部生成成功！朋友圈配图已就绪。")
    else:
        print("⚠️ 部分失败，可重新运行此脚本补生成。")
