# -*- coding: utf-8 -*-
"""插画 v3：只修 A、B
A 河流穿透房屋 → 水系改为纯自然路径（云雨→山涧→渠江，江自右侧出画），房屋/水龙头/桌子单独立在河岸广场上，互不穿越
B 方糖比瓶口大、可能被读成"鼓励甜饮料" → 糖块缩到指尖大小、明确"能从瓶口倒出"，只洒出一小把（约十块）
"""
import json, os, time, requests
from concurrent.futures import ThreadPoolExecutor

CFG = json.load(open('/data/www/files/LhyjdesignPro/config.json'))
API_KEY, BASE, MODEL = CFG['api_key'], CFG['base_url'], CFG['models']['image_gen']
OUT = '/data/www/files/waterHealthArt/final/illustration'
SIZE = '2896x2048'

NOTEXT = ("No text anywhere: no Chinese characters, no letters, no numbers, no calligraphy, no labels, no captions, "
          "no logos, no watermark, no signature. Every screen, signboard, label and printed surface is completely "
          "blank. No numbers on any cup or bottle — measuring marks are plain short tick lines only. ")

ART = (" Hand-painted children's picture-book illustration in watercolour with coloured-pencil accents, drawn in the "
        "warm sincere style of a gifted ten-year-old's award-winning painting: confident varied brush lines with "
        "thicker and thinner strokes, layered transparent watercolour washes, soft blooms and dry-brush edges, a "
        "little visible paper grain, a warm lively harmonious palette with a few strong accent colours, clear "
        "readable silhouettes, soft natural daylight. NOT flat vector art, NOT computer flat colouring, NOT a "
        "colouring-book fill, NOT 3D render, NOT a photograph. ")

SAFE = (" Rounded simple mitten-shaped hands with no separated fingers; every glass, cup or bottle is firmly held and "
        "supported by a clearly drawn hand — no missing hands, no extra limbs, no deformed fingers. Nothing floats "
        "in the air: no decorative sparkles or stars, every water drop falls or splashes from a clearly drawn source, "
        "every object rests on a surface or is fixed to a wall. Physically plausible: no object passes through "
        "another. Warm, healthy, wholesome and suitable for primary-school children. ")

T = {}

T['A_饮水思源_一滴水的旅行'] = NOTEXT + ART + (
 " A drinking-water education painting set in a riverside town in eastern Sichuan that clearly shows children "
 "drinking clean water and where that water comes from. The landscape water path and the buildings never overlap "
 "or pass through each other. "
 "Left and centre of the picture, a pure natural water path: a fat cloud with straight rain lines at the upper "
 "left, below it a small mountain stream tumbling over three round stones on a green mountain slope, and then a "
 "wide river with long ripple lines running across the middle of the picture and leaving the frame at the right "
 "edge; one small wooden boat with a boatman floats on the river, reeds grow on the near bank, and three pine trees "
 "stand on the mountain. "
 "Right foreground, standing on the stone-paved riverbank plaza and separate from the water path: TWO children "
 "drinking side by side at the same time — a girl with a ponytail in a light blue shirt, and beside her a boy with a "
 "short bowl haircut in a warm yellow shirt; both have round faces, dot eyes and small smiles, wear red neckerchiefs, "
 "and each holds a glass up to the mouth with BOTH hands taking a small sip; a thin wisp of steam rises from each "
 "glass and the girl's glass carries three plain short tick marks. "
 "Right middle ground, on the plaza: a low white house wall with one square window and a wooden door; a small tap "
 "with a red handle is FIXED ON that wall with a wooden bucket standing on the ground directly under it catching the "
 "drips, and a watering can stands beside a flower bed with three flowers. In front of the wall a low table holds a "
 "white porcelain cooling jar with a lid and a spout, and a row of THREE small cups filled with clear water; next to "
 "the table a small stove carries a kettle that sends up a curly steam line. "
 "Background: a tall plain stone monument standing on a wide stepped plaza with three small lamp posts, a big "
 "mountain with simple ridge lines behind the stream, a round sun with short rays, two soft clouds and three small "
 "birds. Grass tufts and two small flowers along the bottom edge. "
 "Colour: clear cyan-blue water, fresh green mountain, warm sandstone plaza, white walls, cream steam, the two red "
 "neckerchiefs and the red tap handle as the strong accents. "
) + SAFE

T['B_白开水最好喝'] = NOTEXT + ART + (
 " An old riverside trading-street scene in eastern Sichuan about choosing plain water instead of a sweet bottled "
 "drink. "
 "Foreground centre: TWO children drinking side by side — the nearer a boy with a short bowl haircut, the further a "
 "girl with two braids — both with round faces, dot eyes and small smiles, in shirts and red neckerchiefs; each "
 "holds a tall plain glass of clear water up to the mouth with BOTH hands and takes a small sip. "
 "Foreground left: a wooden table carrying ONE transparent bottle lying tipped over on its side with a straw in its "
 "neck; the bottle is clearly see-through and packed inside with many SMALL cube-shaped sugar lumps, each lump only "
 "about the size of a fingertip and clearly smaller than the bottle mouth so they could really slide out; a short "
 "trail of about ten such small sugar lumps has slid out of the bottle mouth and lies scattered in a modest row on "
 "the table top beside the bottle, NOT a big pile, and two single lumps lie on the ground below. "
 "Foreground right: a small wooden table holding a white porcelain cooling jar, which has a lid and a spout, and a "
 "round plate with one whole fruit; a bamboo chair stands behind it. "
 "Middle ground: a stone-paved street with joint lines; on the left the tiled eaves and wooden wall of an old house "
 "with rows of roof tiles and three round red lanterns hanging under the eave; a small tap with a red handle is "
 "FIXED ON that wall with a wooden bucket standing on the ground under it; a big clay rain-water jar with a wooden "
 "lid and a bamboo dipper stands against the wall; a low stove beside it carries a kettle that sends up a curly "
 "steam line; a wooden bench stands nearby. "
 "Background: a wide river with ripple lines and two wooden boats with masts, two thin bands of morning mist, a "
 "distant hill outline, one leafy tree on the far bank and three small birds. "
 "Colour: warm morning light, honey-brown wood, warm grey stone, small white sugar lumps, clear cyan-blue water, "
 "three red lanterns and two red neckerchiefs as the strong accents. "
) + SAFE


def gen(name, prompt, retries=3):
    for a in range(retries + 1):
        try:
            r = requests.post(f"{BASE}/images/generations",
                headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
                json={"model": MODEL, "prompt": prompt, "size": SIZE, "n": 1, "watermark": False},
                timeout=300)
            d = r.json()
            if d.get('data'):
                img = requests.get(d['data'][0]['url'], timeout=180).content
                p = os.path.join(OUT, f"{name}.jpg")
                open(p, 'wb').write(img)
                print(f"OK  {name}  {len(img)//1024}KB", flush=True)
                return p
            print(f"ERR {name} #{a}: {json.dumps(d, ensure_ascii=False)[:220]}", flush=True)
        except Exception as e:
            print(f"EXC {name} #{a}: {e}", flush=True)
        time.sleep(6)
    return None


if __name__ == '__main__':
    with ThreadPoolExecutor(max_workers=2) as ex:
        print(list(ex.map(lambda kv: gen(*kv), T.items())))
