# -*- coding: utf-8 -*-
"""第1步修订版：重出 2/3/5 三张线条图（修 QA 问题）
修点：
  2 竹节 —— 杯上出现数字 → 明令刻度只许短横线、无任何数字；杯子加竹枝支撑防悬浮
  3 嘉陵江 —— 主题辨识度低（方糖被看成冰块）→ 方糖画成棱角分明的立方并堆成小堆，孩子高举白开水+星芒水滴
  5 家庭 —— 液体出现灰阶填充 + 左下角孤立手臂 → 液体只留波浪轮廓线；删掉前景悬浮的手；补"喝水"动作
"""
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/lineart'
os.makedirs(OUT, exist_ok=True)

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 writing on the blackboard, on the banners, on the shop signs, on the labels or on any cup. "
          "No numbers or digits on any cup, bottle or measuring scale — the measuring marks must be plain short "
          "horizontal tick lines only. Every signboard, screen and printed surface must be completely blank. ")

NOFILL = ("Any liquid inside a cup, glass, 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 watercolour painting workbook — a tracing and "
        "colouring outline. Uniform black outlines on pure white background. MODERATE level of detail: include "
        "interior detail lines that a 9-10 year old can draw, such as roof tile rows, window frames, bamboo "
        "sections, water ripple lines, leaf clumps, stone paving lines, brick rows. "
        "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 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 = {}

# ---------------------------------------------------------------- 2 竹节（重出）
T['2_竹节里的八杯水'] = NOTEXT + NOFILL + (
 " A fresh green mountain-bamboo scene that turns a bamboo stalk into a drinking-water measuring scale. "
 "Foreground, lower left: a child with a round face, dot eyes and a small smile, hair tied up, wearing a shirt "
 "and a red neckerchief, standing on the ground and holding a small cup with plain tick marks, taking a small "
 "sip; the child's feet rest on two stepping stones; grass tufts and three small mushrooms at the bottom edge. "
 "Centre of the picture: one very thick bamboo stalk rises vertically from the bottom of the frame right up to "
 "the top, drawn with EIGHT clearly separated bamboo nodes as horizontal joint lines and long vertical fibre "
 "lines; at EACH of the eight nodes a short thick bamboo side-branch sticks out to the left or the right, and "
 "on each of those side-branches rests one small cup, clearly touching and supported by the branch, with no "
 "cup floating in the air; every cup is drawn with plain short horizontal tick marks and one wavy water-surface "
 "line, and the water level inside the cups gets a little higher for the cups that are higher up the stalk; one "
 "single big water drop rests on a bamboo leaf beside three of the cups. "
 "At the foot of the stalk: a rock face with a narrow crack from which a spring water line flows out and splashes "
 "into a small pool drawn with ripple rings; two stepping stones; three young bamboo shoots with pointed tips "
 "and wrapping sheaths. "
 "Middle ground left and right: several bamboo leaf clusters in overlapping groups, a small bamboo fence, a "
 "winding mountain footpath with a low step, a wooden water ladle with a long handle leaning against a stone, "
 "and a small wooden bucket standing on the ground. "
 "Background: a large mountain with simple ridge lines and pine shapes, a soft band of morning cloud sea across "
 "its middle, a big rising sun with short straight rays behind the ridge, two birds, two soft cloud shapes, and "
 "clumps of distant bamboo on the far slopes."
) + LINE

# ---------------------------------------------------------------- 3 嘉陵江（重出）
T['3_嘉陵江边的一壶白开水'] = NOTEXT + NOFILL + (
 " A warm old riverside town street scene about a child choosing plain boiled water instead of a sugary drink. "
 "Foreground, centre: a wooden square table with four straight legs. On the table, on the right side, one "
 "tipped-over bottle lies on its side with a drinking straw beside it; out of the bottle mouth a heap of about "
 "sixteen CLEARLY CUBE-SHAPED sugar lumps, each drawn with visible cube edges so it looks like a small block, "
 "has spilled out and piled up into a little hill on the table — this is a little pile of sugar blocks, not "
 "ice. On the left side of the table stands one tall plain glass of clear water. A child with a round face, dot "
 "eyes and a small smile, wearing a shirt and a red neckerchief, stands at the table and pushes that little "
 "hill of sugar cubes away to the right with one flat open palm, while the other hand lifts the tall plain "
 "glass of clear water up high; around the raised glass of water there are three small four-point sparkle "
 "shapes and two water-drop shapes with little highlights, and two tiny curved motion lines behind the pushing "
 "hand. Beside the table a long-spouted copper kettle is tipped forward pouring a thin stream of hot water into "
 "a white porcelain pot, with a curly steam line rising from both the kettle and the pot. "
 "Middle ground: a stone-paved street drawn in simple perspective with paving-joint lines; the tiled eaves and "
 "one wall of an old wooden house on the left, with rows of roof tiles and three hanging round lanterns under "
 "the eave; a bamboo chair and a long wooden bench standing on the pavement; a big clay rain-water jar with a "
 "wooden lid and a bamboo dipper standing against the wall; a bamboo-woven water bottle hanging from a wall peg; "
 "a cat sitting on the 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

# ---------------------------------------------------------------- 5 家庭（重出）
T['5_我家的水位线'] = NOTEXT + NOFILL + (
 " A warm and cosy home kitchen-and-dining scene about drinking water at home, using the water level in every "
 "cup as a family health scale. "
 "Foreground: an old wooden table seen from a slightly high angle; on the table stand THREE of the child's own "
 "cups in a row from left to right — a small bowl with a spoon resting in it, a small tumbler, and a taller "
 "bottle with plain short tick marks — each one drawn with one wavy water-surface line and the water level "
 "growing higher from left to right; a small round plate with a slice of fruit stands at the left end of the "
 "table. "
 "Middle ground: the same table holds the whole family's cups arranged in an open semicircle — a white enamel "
 "mug with a rim stripe, a plain glass, a tall vacuum thermos flask with a lid and a handle, and a mug with a "
 "handle — each cup filled to a DIFFERENT height with a clearly drawn wavy water-surface line, and each shown "
 "with its own rim, handle and base details. A child with a round face, dot eyes and a small smile, wearing a "
 "shirt, stands behind the table pouring water from a small pot into one of the mugs with both hands. On a "
 "wooden chair beside the table an elderly grandparent sits holding an enamel mug in both hands and takes a "
 "small slow sip with a gentle smile. Behind them a kitchen stove with a metal kettle blowing out a curly "
 "steam line, a wall shelf with two bowls and three stacked dishes. "
 "Background: a kitchen window with a cross frame and a short curtain; through the 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 round fruit, a low wall, a distant hill outline, two clouds and two birds; a round "
 "basket of fruit standing on a side cabinet; a cat curled up sleeping beside the clay 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": "2048x2048", "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())))
