# -*- coding: utf-8 -*-
"""横版 A4（1.4141:1）5 份新主题 —— 第1步：线条图
设计原则：主题"科学饮水共促健康"必须一眼看懂 —— 中心主体都是明确的喝水/白开水/水龙头动作，
         不再用"竹节刻度""水位线"这类需要解释的隐喻。
尺寸 2896x2048 = 5,931,008 px（Seedream 5.0 下限 3,686,400），横构图 A4 比例。
"""
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. ")

T = {}

# ------------------------------------------------ 1 一起喝够八杯水（足量规律）
T['1_一起喝够八杯水'] = NOTEXT + LIQUID + (
 " A sunny riverside plaza in eastern Sichuan where several children drink water together, making the idea of "
 "drinking ENOUGH water through the day obvious. "
 "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, each holding a cup up and taking a small sip; the child in the "
 "centre stands nearest and is drawn biggest, holding the largest tall glass tumbler; the two other children "
 "stand a little further and are drawn a little smaller; small water droplets are drawn beside each cup; a low "
 "wooden stool with a round plate of two fruit slices at the lower right; grass tufts along the bottom edge. "
 "Middle ground, centre: one very tall transparent glass tumbler stands as the biggest object in the picture, "
 "drawn with EIGHT plain short tick marks along its side and one wavy water line; behind the children a low "
 "round fountain basin with a small water jet and ripple rings. "
 "Middle ground, left: a low stone bench holding a row of FOUR small cups; middle ground, right: another low "
 "stone bench holding a row of FOUR small cups, so that eight cups in total are clearly visible in the picture; "
 "the low benches are plain slabs resting on two stone blocks each; a low stone railing runs behind them. "
 "Background: a tall plain stone monument standing on a wide stepped plaza base with a row of small lamp posts; "
 "a long wide river shown 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 in the sky."
) + LINE

# ------------------------------------------------ 2 烧开晾温 小口慢饮（正确方法）
T['2_烧开晾温_小口慢饮'] = NOTEXT + LIQUID + (
 " A warm country kitchen in an eastern Sichuan farmhouse, arranged as a clear left-to-right story of getting "
 "drinking water ready: tap water, boiling it, letting it cool, then sipping it slowly. "
 "Left side, middle ground: a plain wall tap above a stone sink, with a clear stream of water pouring into a "
 "small wooden bucket standing in the sink; a bar of soap and a folded cloth on the sink edge; a small hand "
 "towel hanging on a wall peg. "
 "Centre, middle ground: a brick stove with a round metal kettle on top; a curly steam line rises from the "
 "kettle spout; beside the stove a neat stack of two firewood logs on the floor; a kitchen window with a cross "
 "frame behind the stove. "
 "Right side, foreground: a child with a round face, dot eyes and a small smile, wearing a shirt and a red "
 "neckerchief, sitting on a low wooden stool at a small wooden table, both hands holding a glass cup close to "
 "the chin, taking a small slow sip; a thin wisp of steam rises from the glass; on the same table a white "
 "porcelain cooling jar with a lid and a spout, and a small round plate with two fruit slices; below the table "
 "a pair of slippers on the floor. "
 "Middle ground, right: a wooden wall shelf holding two bowls and three stacked cups; a bamboo screen panel "
 "leaning against the wall; a big clay water jar with a wooden lid standing in the corner with a bamboo dipper "
 "hung on its side. "
 "Background, seen through the window: tiled rooftops of a small riverside town drawn with rows of roof tiles, "
 "a wide river with long ripple lines and one small wooden boat, a mountain ridge outline, the sun with short "
 "rays, two cloud shapes and two small birds."
) + LINE

# ------------------------------------------------ 3 一瓶甜饮料 一堆方糖（减少含糖饮料）
T['3_一瓶甜饮料_一堆方糖'] = NOTEXT + LIQUID + (
 " A wide old riverside street scene that contrasts a bottled sweet drink with a plain glass of water, making "
 "the choice obvious. The picture is clearly divided into a LEFT half and a RIGHT half by an open doorway in "
 "the middle where a child stands. "
 "Left half: a small wooden shop counter holding THREE transparent bottles of sweet drink drawn with simple "
 "labels kept completely blank; beside the bottles a tall plastic bottle stands tipped a little, packed inside "
 "with stacked cube-shaped sugar lumps and a straw in its neck, and a heap of about sixteen clearly cube-shaped "
 "sugar lumps has spilled out and piled up into a small hill on the counter top, each lump drawn as a little "
 "block with visible straight cube edges; a couple of sugar lumps have rolled onto the ground below. "
 "Right half: a plain old wooden table holding ONE tall plain glass of clear water with three small four-point "
 "sparkle shapes around it and a small round plate with a whole fruit and two slices; a bamboo chair behind the "
 "table; a big clay rain-water jar with a wooden lid and a bamboo dipper standing beside the table. "
 "Centre: a child with a round face, dot eyes and a small happy smile, wearing a shirt and a red neckerchief, "
 "standing in the doorway and holding the tall plain glass of clear water with BOTH hands lifted to chest "
 "height, facing forward. "
 "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 cat sitting on a "
 "wooden bench; some grass tufts between the paving stones. "
 "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 接一杯 喝一口 关紧它（校园·节水）
T['4_接一杯_喝一口_关紧它'] = NOTEXT + LIQUID + (
 " A wide school corridor scene about drinking water at school and not wasting it, with three children doing "
 "three clear things in a row from left to right. "
 "Foreground, along a long straight drinking-water station fixed on the corridor wall, with THREE separate "
 "taps: on the left a child holds a water bottle with plain tick marks under the first tap and fills it, water "
 "running into the bottle; in the middle a child holds a small cup and takes a small sip with a happy face; on "
 "the right a child reaches up with one hand and turns the third tap shut, while the other hand holds a "
 "watering can; all three children have round faces, dot eyes and small smiles, wear shirts and red "
 "neckkerchiefs; each child also has their own water bottle with plain tick marks and a stripe pattern, "
 "standing on the floor or held in hand; a few water droplets and two ripple rings are drawn near the taps. "
 "Middle ground: the corridor floor with long perspective lines and a row of square window frames along the "
 "right side; a corridor railing with vertical bars; TWO separate two-storey school teaching buildings outside "
 "the corridor, drawn with rows of square windows and a rooftop parapet; a flower bed with three flowers "
 "beside the corridor, watered by the watering can; a big plastic bucket catching rain water under the eave; a "
 "broom leaning against the corridor wall. "
 "Background: a red running-track arc with white lane lines and 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 全家一起 喝够每一杯（家庭）
T['5_全家一起_喝够每一杯'] = NOTEXT + LIQUID + (
 " A wide warm family dining scene at home in eastern Sichuan about the whole family drinking enough 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 child's small bowl with a spoon resting in it, a child's "
 "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: at the centre of the table a big white porcelain cooling jar with a lid and a spout; three "
 "family members around the table, all with round friendly faces, dot eyes and small smiles — on the left a "
 "child standing and pouring water from a small pot into one of the cups with both hands; in the middle an "
 "adult sitting on a wooden chair taking a drink from a mug; on the right an elderly grandparent sitting on a "
 "wooden chair holding the enamel mug in both hands and taking a small slow sip; behind them a brick stove with "
 "a metal kettle blowing out a curly steam line, and 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, a distant hill outline, two cloud shapes and two birds; inside, on a side cabinet, a round basket with "
 "two fruit in it; a cat curled up sleeping on the floor beside the jar; one potted plant with three leaves on "
 "the window sill."
) + 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())))
