# -*- coding: utf-8 -*-
"""插画 v2：修 3 处遗留问题
A 主题指向弱 → 加同伴一起喝、墙上水龙头、桌上三只水杯、炉上水壶；主体更明确
B 星芒被判悬浮 → 删掉星芒，改为"墙上水龙头+木桶""炉上水壶冒汽"两个落地的水元素
C 右侧水龙头悬空 → 明确"三个龙头都装在同一块墙面横板上"，并把墙面画出来
"""
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'
os.makedirs(OUT, exist_ok=True)
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. 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. "
 "Foreground right: TWO children standing side by side and BOTH drinking 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 "
 "as they take a small sip; a thin wisp of steam rises from each glass; the girl's glass carries three plain short "
 "tick marks; they stand on a stone-paved plaza with grass tufts and two small flowers along the bottom edge. "
 "Middle ground: one long winding S-shaped ribbon of clear blue water flows down through the picture from the upper "
 "left to their glasses; along that ribbon, from far to near — a small mountain stream tumbling over three round "
 "stones, then a wide river with ripple lines carrying one small wooden boat with a boatman, reeds on the bank, and "
 "then the ribbon runs behind a low white house wall with one square window. THAT WALL CARRIES a small tap with a "
 "red handle, fixed on the wall, with a wooden bucket standing on the ground directly under it catching the drips; "
 "beside the bucket a watering can stands next to 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 on the right "
 "horizon, a long river-bank line, a big mountain with simple ridge lines and three pine shapes on the left, a round "
 "sun with short rays, two soft clouds and three small birds. "
 "Colour: clear cyan-blue water everywhere, 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 tall transparent bottle lying tipped over on its side with a straw in "
 "its neck, packed inside with stacked cube-shaped sugar lumps, and a big heap of about twenty cube-shaped sugar "
 "lumps spilling out of it into a small white hill on the table top; two loose 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, white sugar lumps, clear cyan-blue water, three red "
 "lanterns and two red neckerchiefs as the strong accents. "
) + SAFE

T['C_接一杯_喝一口_关紧它'] = NOTEXT + ART + (
 " A wide primary-school corridor scene about drinking water at school and not wasting it. "
 "Foreground: a LOW CONTINUOUS WALL PANEL runs along the corridor behind the children, and THREE separate taps are "
 "each mounted ON that wall panel at the same height, with a short bracket drawn joining every tap to the wall so "
 "that no tap floats; a slim drain channel is drawn on the corridor floor directly under the taps. Three children "
 "stand along it. From left to right — a girl with two braids in a sky blue shirt holds a blue water bottle with "
 "plain tick marks under the first tap and fills it, a clear stream of water falling into the bottle with small "
 "spray droplets at the bottle mouth; in the middle, drawn biggest and nearest, a boy with a short bowl haircut in a "
 "bright yellow shirt tips a small cup up to his mouth with BOTH hands and takes a small sip; on the right a boy "
 "with flat short hair in a white shirt reaches up with one hand and turns the third tap shut with no water running, "
 "while his other hand holds a green water bottle. All three have round faces, dot eyes, small smiles and red "
 "neckerchiefs; each water bottle has plain tick marks and its own stripe pattern. "
 "Middle ground: the corridor floor with long perspective lines and the wall panel continuing away to the left; a "
 "corridor railing with vertical bars; outside the corridor TWO two-storey school teaching buildings with rows of "
 "square windows; a big plastic bucket catching rain water under the eave; a flower bed with three flowers. "
 "Background: a red running-track arc with white lane lines, a basketball hoop with a backboard in the far left "
 "distance, two leafy trees and one bamboo clump, a long mountain ridge, a round sun with short rays, three soft "
 "clouds and four small birds. "
 "Colour: bright daylight, warm cream corridor, brick-red track, fresh green court, clear cyan-blue water, the three "
 "water bottles in bright red, blue and green as the 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=3) as ex:
        print(list(ex.map(lambda kv: gen(*kv), T.items())))
