# -*- coding: utf-8 -*-
"""深色黑板 + 彩色粉笔手绘风格（参考用户附件）—— 每版含 安全/反诈/禁毒 三区"""
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/heibanbaoChalk/raw'
os.makedirs(OUT, exist_ok=True)

STYLE = (
 "A hand-drawn CHALK POSTER painted directly on a real classroom BLACKBOARD — the whole picture IS the dark board, "
 "filling the frame edge to edge, seen perfectly straight-on and flat, no wooden frame, no easel, no room, no wall, "
 "no perspective tilt, no photograph of a classroom. "
 "BACKGROUND: deep charcoal-black chalkboard, almost black (about #141410 and #1E1E16), with soft uneven chalk-dust "
 "haze, faint grey eraser smudges and a very slight warm-green cast in places; fine dry chalk grain visible all over. "
 "MEDIUM: everything is drawn with CHALK and coloured chalk. Every single shape is outlined with a BOLD, slightly "
 "wobbly WHITE CHALK line that is dry and grainy with tiny gaps and a faint dust halo, and then filled with flat "
 "bright coloured chalk: crimson red, orange, golden yellow, grass green, sky blue, lavender purple, pink. The colours "
 "are cheerful, saturated, matte and powdery — like a teacher drawing with a box of coloured chalk. White chalk is "
 "used for all outlines, for the stars, the clouds and for simple hatching highlights. "
 "CHALK TEXTURE RULE: rough grainy edges on every line and every colour patch, faint chalk dust around them, "
 "NO clean vector edges, NO glossy or plastic look, NO gradients inside shapes, NO photorealistic shading, NO 3D "
 "rendering, NO digital airbrush, NO drop shadows. "
 "CARTOON STYLE: cute Chinese primary-school chalk cartoons — round heads, big simple eyes, small smiles, "
 "short rounded limbs, thick white chalk outlines, flat chalk colour fills, NO realistic skin tones, NO realistic "
 "hair shading; every child has a different shirt colour. "
 "DECORATION VOCABULARY (use a few, scattered in empty corners only): small white chalk four-pointed stars, fluffy "
 "white chalk clouds, one pastel rainbow arch, green grass tufts along the bottom edge, small pink and yellow "
 "flowers, red-and-white spotted mushrooms, big yellow sunflowers with brown centres, a blue-and-white striped paper "
 "airplane, a yellow pencil, a small chalk butterfly. "
 "TITLE AREA: the TOP 18 PERCENT of the board is left almost EMPTY — only a few tiny white chalk stars near the very "
 "top corners; absolutely no character, no icon, no panel, no banner, no cloud, no rainbow, no decoration inside that "
 "band, because a large hand-written title will be added there afterwards. Every drawing stays below the 20 percent "
 "height line. "
 "ABSOLUTELY NO TEXT ANYWHERE: no Chinese characters, no letters, no words, no numbers, no digits, no calligraphy, "
 "no captions, no title, no logo, no watermark, no signature, no seal, no grid paper. Every board, sign, screen, "
 "banner, book and flag must be completely BLANK and free of marks. "
 "Wide horizontal A4 composition, flat frontal view, generous dark empty board space in each zone so short section "
 "titles can be written in later."
)

LAYOUTS = {
 'A_综合版_安全反诈禁毒': (
   "LAYOUT: THREE ZONES across the board. "
   "LEFT THIRD — a smiling boy standing on green chalk grass: short brown hair, white short-sleeved shirt, blue "
   "shorts, red neckerchief, both hands holding up one BIG SKY-BLUE SHIELD with a big white tick on it; behind and "
   "above him a pastel rainbow arching between two fluffy white chalk clouds, a small chalk butterfly; beside him a "
   "sky-blue laptop and an upright smartphone with a large orange warning triangle with an exclamation mark floating "
   "just above its screen; at his feet two small pink flowers and one red-and-white spotted mushroom. Keep the upper "
   "third of this zone clear of drawings. "
   "CENTRE — a wide winding pale-yellow chalk PATH flowing from the middle of the board down to the bottom edge, drawn "
   "with a dashed brown centre line, bordered by grass tufts and small flowers; beside the path a friendly cartoon "
   "POLICE OFFICER in a dark navy-blue peaked cap, light blue uniform shirt and black tie, one arm raised pointing "
   "forward, mouth open as if calling out. Keep the upper part of this centre zone clear. "
   "RIGHT THIRD — one BIG RED PROHIBITION CIRCLE (thick red ring with ONE clean diagonal bar) containing simple white "
   "chalk drawings of a syringe, three scattered pills and two small bottles; below it three big yellow sunflowers "
   "with brown centres growing on grass and a group of THREE happy children in blue, green and orange shirts cheering "
   "with both arms raised. Keep the upper third of this zone clear of drawings."
 ),
 'B_校园场景版_安全反诈禁毒': (
   "LAYOUT: one wide SCHOOL-YARD scene drawn in chalk on the black board with a single continuous chalk ground line. "
   "LEFT THIRD — a school gate with a guard in a dark navy-blue uniform and cap standing beside it, a zebra crossing "
   "in front of the gate, a tall traffic light post with red, yellow and green lamps standing on the ground, and a boy "
   "wearing a red safety helmet waiting at the kerb. Keep the sky area of this zone clear of drawings. "
   "CENTRE — a short flight of stairs with a red fire extinguisher standing on the ground beside them, a girl walking "
   "up the right-hand side of the stairs, and above them an upright smartphone with a big orange warning triangle and "
   "a small padlock chalk icon; a narrow winding pale-yellow chalk path runs from the centre down to the bottom edge. "
   "Keep the sky area of this zone clear. "
   "RIGHT THIRD — a round RED PROHIBITION SIGN on a short post planted on the grass, the ring containing a simple "
   "white chalk poppy seed pod with a serrated crown and two small leaves; beside it two big yellow sunflowers and "
   "three children in purple, pink and green shirts standing together waving. Keep the sky area of this zone clear."
 ),
 'C_三分区留白版_安全反诈禁毒': (
   "LAYOUT: THREE BIG EMPTY CHALK PANELS standing side by side across the board, each drawn as a thick wobbly "
   "hand-drawn chalk rectangle with rounded corners — the LEFT frame in WHITE chalk, the MIDDLE frame in GOLDEN "
   "YELLOW chalk, the RIGHT frame in RED chalk. The panels occupy the area from 27 percent down to 78 percent height, "
   "separated by narrow dark gaps. The whole interior of every panel is COMPLETELY EMPTY DARK BOARD, untouched and "
   "free of drawings, ready for a pupil to write into — no lines, no grid, no decoration, no fill inside. "
   "Above the LEFT panel: one big SKY-BLUE SHIELD with a white tick and a sky-blue laptop beside it. Above the MIDDLE "
   "panel: one upright smartphone with a large orange warning triangle and a small white padlock. Above the RIGHT "
   "panel: one big RED PROHIBITION CIRCLE with a syringe and two pills inside it. These three icons sit on the panel "
   "top edges and stay below the 26 percent height line. "
   "Along the bottom edge, on one continuous chalk grass line: green grass tufts, small pink and yellow flowers, two "
   "red-and-white spotted mushrooms, three big yellow sunflowers, and three cheering children in blue, red and green "
   "shirts. A pastel rainbow arcs low in the left bottom corner and a few white chalk stars sit in the top corners."
 ),
}


def gen(key, layout):
    name = key + '.jpg'
    prompt = STYLE + layout
    for a in range(4):
        try:
            r = requests.post(f"{BASE}/images/generations",
                headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
                json={"model": MODEL, "prompt": prompt, "size": "2896x2048", "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, name)
                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)[:300]}", flush=True)
        except Exception as e:
            print(f"EXC {name} #{a}: {e}", flush=True)
        time.sleep(8)
    return None


if __name__ == '__main__':
    import sys
    items = LAYOUTS.items()
    if len(sys.argv) > 1:
        items = [(k, v) for k, v in items if any(n in k for n in sys.argv[1:])]
    with ThreadPoolExecutor(max_workers=3) as ex:
        list(ex.map(lambda kv: gen(*kv), items))
