# -*- coding: utf-8 -*-
"""横版 A4 · 第1步修订 v2：5 份全出
QA 结论（v1）：只有①被判定"一眼看懂科学饮水"，②③④⑤被读成"居家喝热饮/夏日消暑/浇花劳动/普通家庭场景"。
修法（三件必备要素，每份都要有）：
  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/horizontal/lineart'
os.makedirs(OUT, exist_ok=True)
SIZE = '2896x2048'

NOTEXT = ("Absolutely NO TEXT anywhere. No Chinese characters, no letters, no words, no numbers, no digits, "
          "no calligraphy, no captions, no titles, no logos, no watermarks, no signature, no seals or stamps. "
          "No numbers or digits on any cup, bottle, jug or measuring scale — the measuring marks must be plain "
          "short horizontal tick lines only. No writing on the shop signs, the labels, the cups, the blackboard "
          "or any banner — every signboard, screen and printed surface must be completely blank. ")

LIQUID = ("Any liquid inside a cup, glass, bottle, jar or pot must be shown with OUTLINES ONLY — a simple wavy "
          "surface line — with absolutely NO grey fill, NO shading and NO tonal patches inside the liquid. ")

LINE = (" Clean black-and-white line drawing for a children's colouring template and tracing outline. Uniform "
        "black outlines on pure white background. MODERATE level of detail: include interior detail lines a 9-10 "
        "year old can draw, such as roof tile rows, window frames, brick rows, water ripple lines, leaf clumps, "
        "stone paving lines, cloth folds, bottle ribbing. "
        "ABSOLUTELY NO shading, NO cross-hatching, NO stippling, NO grey tones, NO gradients, NO tonal patches, "
        "NO colour fill, NO texture rendering — outlines only, every area left pure white. "
        "Genuine wide scene composition with foreground, middle ground and background, simple one-point "
        "perspective with nearer objects bigger and further objects smaller, clear overlapping layers. "
        "Characters drawn with simple but expressive faces (dot eyes, small smile) and clear limbs and poses. "
        "Every object rests on or touches something solid — nothing floats in the air unsupported. Closed clear "
        "shapes, readable silhouette, well-balanced wide composition, white margins. ")

DRINK = ("is drinking: the cup is tipped up and its rim touches the mouth, the head is tilted slightly back, and "
         "a small wisp of steam and three small water droplets are drawn beside the cup; ")

T = {}

# ------------------------------------------------ 1 一起喝够八杯水（v2）
T['1_一起喝够八杯水'] = NOTEXT + LIQUID + (
 " A sunny riverside plaza in eastern Sichuan where several children drink water together. "
 "Foreground: THREE children in a row across the lower half, each with a round face, dot eyes and a small "
 "smile, wearing shirts and red neckerchiefs, and each one " + DRINK +
 "the child in the centre stands nearest and is drawn biggest, the two others stand a little further and are "
 "drawn a little smaller. "
 "Middle ground: a large glass tumbler standing ON a low stone bench beside the children, about as tall as a "
 "child, drawn with EIGHT plain short tick marks along its side and one wavy water line, its base clearly "
 "resting on the bench top; behind the children a low round fountain basin with a small water jet rising and "
 "splash droplets falling into it, drawn with ripple rings. "
 "Middle ground, far left: a low stone bench holding a row of FOUR small cups; far right: another low stone "
 "bench holding a row of FOUR small cups, so eight cups in total are clearly visible; a low stone railing runs "
 "behind the benches. "
 "Background: a tall plain stone monument standing on a wide stepped plaza base with a row of small lamp posts; "
 "a long wide river with long ripple lines and one small wooden boat with a boatman; a big mountain with simple "
 "ridge lines and a few pine tree shapes; the sun with short rays, three soft cloud shapes and four small birds."
) + LINE

# ------------------------------------------------ 2 院坝里的一杯温开水（v2）
T['2_院坝里的一杯温开水'] = NOTEXT + LIQUID + (
 " An open farmhouse courtyard in eastern Sichuan where two children drink warm boiled water. "
 "Centre, foreground: TWO children standing side by side, the nearer one drawn biggest; both have round faces, "
 "dot eyes and small smiles, wear shirts and red neckerchiefs, and each one " + DRINK +
 "the nearer child's glass carries plain short tick marks on its side. "
 "Middle ground, left: a plain wall tap above a stone basin, a clear straight stream of water pouring from the "
 "tap into a wooden bucket standing in the basin, with spray droplets at the point where the water hits, and a "
 "bar of soap on the basin edge. "
 "Middle ground, right: a low brick stove standing on the ground with a round metal kettle on top, a curly "
 "steam line rising from the spout, two firewood logs stacked on the floor beside it, and a long wooden bench "
 "beside the stove with a white porcelain cooling jar, which has a lid and a spout, standing on it. "
 "Background: a low courtyard wall with a wooden gate; a leafy pomelo tree with three round fruit; a big clay "
 "rain-water jar standing against the wall with a bamboo dipper hanging on its side; a distant hill ridge; the "
 "sun with short rays, two soft cloud shapes and three small birds."
) + LINE

# ------------------------------------------------ 3 白开水最好喝（v2）
T['3_白开水最好喝'] = NOTEXT + LIQUID + (
 " A wide old riverside street scene in eastern Sichuan that contrasts a bottled sweet drink with plain water. "
 "Foreground, centre: TWO children standing side by side, the nearer one drawn biggest; both have round faces, "
 "dot eyes and small smiles, wear shirts and red neckerchiefs, and each one " + DRINK +
 "three small four-point sparkle shapes are drawn around their glasses. "
 "Foreground, left: a wooden table carrying ONE tall transparent plastic bottle tipped over on its side with a "
 "straw in its neck, packed inside with stacked cube-shaped sugar lumps drawn with visible straight cube edges, "
 "and a BIG heap of about twenty cube-shaped sugar lumps that has spilled out and piled up into a small hill on "
 "the table top, covering nearly half of it, each lump drawn as a little block with visible edges; two short "
 "motion lines behind the bottle; two loose lumps lying on the ground below the table. "
 "Foreground, right: a small wooden table with a white porcelain cooling jar, which has a lid and a spout, and a "
 "round plate holding one whole fruit; a bamboo chair behind it. "
 "Middle ground: a stone-paved street with paving-joint lines; the tiled eaves and wooden wall of the old "
 "houses with rows of roof tiles; three round lanterns hanging in a row under the eave; a big clay rain-water "
 "jar with a wooden lid and a bamboo dipper standing against the wall; a cat sitting on a wooden bench. "
 "Background: the wide river surface with long ripple lines, two wooden boats with simple masts and hulls, two "
 "thin bands of morning mist, a distant hill outline, one leafy tree on the far bank, and three small birds."
) + LINE

# ------------------------------------------------ 4 接一杯 喝一口 关紧它（v2）
T['4_接一杯_喝一口_关紧它'] = NOTEXT + LIQUID + (
 " A wide school corridor scene about drinking water at school and not wasting it. "
 "Foreground, along a long straight drinking-water station fixed on the corridor wall, there are THREE separate "
 "taps in a row. From left to right: at the first tap a child holds a water bottle under the running water and "
 "fills it, with a clear stream of water entering the bottle, spray droplets and two ripple rings; at the MIDDLE "
 "tap, drawn biggest and nearest, a child tips a small cup up to the mouth with the head tilted back, taking a "
 "small sip, three water droplets drawn beside the cup; at the third tap a child reaches up and turns the tap "
 "shut, the tap drawn with NO water running, while the other hand holds a water bottle with plain short tick "
 "marks. All three children have round faces, dot eyes and small smiles, wear shirts and red neckerchiefs, and "
 "each also owns a water bottle drawn with plain short tick marks and a stripe pattern, standing on the floor or "
 "held in hand. "
 "Middle ground: the corridor floor with long perspective lines; a corridor railing with vertical bars; TWO "
 "separate two-storey school teaching buildings outside, drawn with rows of square windows and a rooftop "
 "parapet; a big plastic bucket catching rain water under the eave; a flower bed with three flowers in the far "
 "background. "
 "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 outline; the sun with short rays, three "
 "soft clouds and four small birds."
) + LINE

# ------------------------------------------------ 5 全家一起 喝够每一杯（v2）
T['5_全家一起_喝够每一杯'] = NOTEXT + LIQUID + (
 " A wide warm family dining scene at home in eastern Sichuan where the whole family drinks water together. "
 "Foreground: a long old wooden table stretching across the lower half of the picture, seen from a slightly "
 "high angle; along the table stand FIVE cups in a row, each filled to a DIFFERENT height shown with one wavy "
 "water-surface line and a plain short tick mark: a small bowl with a spoon resting in it, a tall bottle with "
 "plain tick marks, a plain glass, a mug with a handle, and an enamel mug with a rim stripe; each cup is drawn "
 "with its own rim, handle and base details. "
 "Middle ground: THREE family members sitting or standing around the table and ALL drinking at the same time — "
 "each one holds a cup tipped up to the mouth with the head tilted slightly back, taking a small slow sip, with "
 "three water droplets drawn beside the cup; on the left a child, in the middle an adult on a wooden chair, on "
 "the right an elderly grandparent on a wooden chair; all three have round friendly faces, dot eyes and small "
 "smiles. At the centre of the table stands a big white porcelain cooling jar with a lid and a spout, and a thin "
 "wisp of steam rises from two of the cups. "
 "Behind them: a brick stove with a metal kettle blowing out a curly steam line; a wooden wall shelf holding "
 "two bowls and three stacked dishes. "
 "Background, seen through a big kitchen window: a courtyard with a big clay rain-water jar standing under the "
 "eave, a clothesline with three hanging pieces of clothing, a leafy pomelo tree with three round fruit, a low "
 "wall and a distant hill outline; inside, on a side cabinet, a round basket with two fruit; one potted plant "
 "with three leaves on the window sill; two soft cloud shapes and two small birds in the sky."
) + LINE


def gen(name, prompt, retries=2):
    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=5) as ex:
        print(list(ex.map(lambda kv: gen(*kv), T.items())))
