# -*- coding: utf-8 -*-
"""A4 白纸彩色板报版式（2896x2048）—— 每版同时容纳 安全/反诈/禁毒 三大板块"""
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/heibanbao3in1/rich'
os.makedirs(OUT, exist_ok=True)

STYLE = (
 "A hand-drawn COLOURFUL CLASSROOM POSTER LAYOUT (Chinese primary school 黑板报 版式设计稿) printed on a sheet "
 "of white A4 paper, seen perfectly straight-on and filling the whole frame. "
 "PAPER: clean BRIGHT WHITE paper background with a very faint warm off-white tint and subtle paper grain; a "
 "touch of empty white margin at the left, right and bottom edges. "
 "MEDIUM: a teacher's hand-painted layout template — BOLD hand-drawn outlines in dark brown-black ink, filled "
 "with FLAT BRIGHT MARKER COLOURS. Cheerful saturated school-poster palette: bright red, warm golden yellow, "
 "sky blue, grass green, orange, pink, purple, warm brown, cream. Colourful and lively, plenty of colour all "
 "over the page. "
 "BRIGHT FLAT LOOK: flat clean colour fills, NO gradients inside objects, NO shading, NO 3D, NO photorealism, "
 "NO muddy or dark colours. "
 "LINE RULE: every outline is ONE single colour — dark brown-black ink. Do NOT draw red-and-blue offset double "
 "lines, do NOT produce any misprint / colour-registration effect. "
 "COLOUR RICHNESS: use at least SIX different bright colours (red, yellow, sky blue, grass green, orange, "
 "pink) spread across the whole page so it looks rich, cheerful and full of colour. "
 "CRITICAL — this is NOT a chalkboard: absolutely NO dark green or black background, NO chalk texture, NO "
 "white-chalk-on-black writing, NO wooden frame, NO easel, NO classroom scene behind the page. The page is "
 "WHITE PAPER with colourful drawings on it. "
 "COMPOSITION: a well-balanced poster-like page of hand-drawn panel frames plus illustrations, like a printed "
 "worksheet that a child fills in. Every panel frame is drawn with a bold coloured outline and its INTERIOR IS "
 "COMPLETELY EMPTY WHITE paper, ready for a pupil to write into — never fill a panel interior with anything, "
 "no fill, no lines, no decoration inside any panel. "
 "TITLE BAND: the TOP 25 PERCENT of the page is left COMPLETELY EMPTY white paper — absolutely no frame line, "
 "no panel, no sun, no cloud, no fruit, no character, no decoration, no symbol inside that band, because a big "
 "hand-written title will be placed there. Every panel frame and every illustration must stay BELOW the 30 "
 "percent height line of the page and ABOVE the 96 percent height line. "
 "FIGURES: EVERY figure drawn in exactly the same flat style — bold outlines with simple flat colour fills, "
 "NO realistic skin tones, NO hair colour, round simple heads, dot eyes, small smile. "
 "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. Any signboard, sign face, "
 "screen, banner, poster or book in the scene must be completely BLANK."
)

LAYOUTS = {
 '1_三联幅_安全反诈禁毒': (
   "LAYOUT: THREE BIG TALL ROUNDED-RECTANGLE PANELS standing side by side across the page like three newspaper "
   "columns, with a narrow empty white gap between them. They occupy the area from 33 percent down to 84 "
   "percent height. The LEFT panel has a thick SKY-BLUE frame, the MIDDLE panel a thick ORANGE frame, the "
   "RIGHT panel a thick RED frame. The whole interior of each of the three panels is COMPLETELY EMPTY WHITE "
   "paper ready for a pupil to write into — no fill, no lines, no decoration, no illustration inside. "
   "BELOW each panel, sitting on the same visible ground line, one single big flat icon centred under its "
   "panel: under the LEFT panel a plain shield with a big tick inside it that is NOT crossed out; under the "
   "MIDDLE panel an upright smartphone with a small warning triangle beside it; under the RIGHT panel a round "
   "prohibition sign with ONE diagonal bar over a small poppy seed pod — the pod is NOT crossed out by "
   "scribbles, only the single clean bar. These three icons are large, simple and clearly separated. "
   "In the bottom left corner, standing on the same ground line beside the shield, one small girl and one "
   "small boy holding hands."
 ),
 '2_三色竖栏_安全反诈禁毒': (
   "LAYOUT: THREE TALL VERTICAL BANDS filling the page from left to right, from 32 percent down to 80 percent "
   "height, separated by narrow empty white gaps. The LEFT band is outlined thick SKY BLUE, the MIDDLE band "
   "thick GOLDEN YELLOW, the RIGHT band thick GRASS GREEN. Every band is drawn as an OUTLINE only — the "
   "interior of each band is COMPLETELY EMPTY WHITE paper ready for a pupil to write into, no fill, no lines, "
   "no decoration, no illustration inside. "
   "At the TOP of each band, just INSIDE the band under its top frame line, one small round white badge "
   "outlined in the same band colour with one simple flat icon inside it: left band a plain shield with a big "
   "tick that is NOT crossed out, middle band an upright smartphone with a small warning triangle, right band "
   "a round prohibition sign with one diagonal bar over a small poppy seed pod. "
   "Across the BOTTOM of the page, below the three bands and standing on one clearly drawn ground line, a row "
   "of small flat icons — a red traffic light, a fire extinguisher, a lifebuoy ring, a red apple and a "
   "first-aid cross — and on the same ground line at the right end one small boy and one small girl walking "
   "hand in hand."
 ),
 '3_校园长卷_安全反诈禁毒': (
   "LAYOUT: a wide SCHOOL-YARD scene with one clearly drawn continuous ground line: on the LEFT a school gate "
   "with a guard in a dark navy-blue uniform standing beside it, in the MIDDLE a short stairway and a small "
   "running track, on the RIGHT a flowering tree growing on grass. "
   "THREE BIG BLANK NOTICE BOARDS are planted in this scene, each on TWO posts planted on the drawn ground — "
   "never floating, never resting on scribbles, doodles or random pencil lines: a SKY-BLUE framed board in "
   "front of the gate on the left, an ORANGE framed board in the middle above the track, a RED framed board on "
   "the right under the tree. The whole face of each board is COMPLETELY EMPTY WHITE paper ready for a pupil "
   "to write into. The three boards are large and evenly spaced. "
   "Small scene details on the ground line: a red traffic light beside the gate, a fire extinguisher next to "
   "the stairway, one pupil sitting on a bench in the middle holding a smartphone, and on the grass on the "
   "right a round prohibition sign on a short post with one diagonal bar over a small poppy seed pod."
 ),
 '4_中心徽章_安全反诈禁毒': (
   "LAYOUT: in the CENTRE of the page a BIG ROUND EMBLEM — a thick RED ring with a thin sky-blue inner ring, "
   "and a COMPLETELY EMPTY WHITE interior ready for a pupil to write a short slogan into. The emblem is centred "
   "at about 55 percent height and is clearly the largest single shape. "
   "Around the emblem THREE BIG ROUNDED PANEL FRAMES arranged like three petals, all at the same distance: one "
   "at the UPPER LEFT with a thick SKY-BLUE frame, one at the UPPER RIGHT with a thick ORANGE frame, one across "
   "the BOTTOM with a thick GRASS-GREEN frame. The whole interior of all three panels is COMPLETELY EMPTY "
   "WHITE paper, no fill, no lines, no decoration, no illustration inside. "
   "Three small flat icons sit touching the frames, none floating: a plain shield with a big tick that is NOT "
   "crossed out resting on the top edge of the upper-left panel, an upright smartphone with a small warning "
   "triangle resting on the top edge of the upper-right panel, a round prohibition sign with one diagonal bar "
   "over a small poppy seed pod standing on the top edge of the bottom panel. "
   "In the bottom left corner and the bottom right corner, one small pupil each, standing on a short visible "
   "ground line, drawn in the same flat style."
 ),
 '5_蜂巢六格_安全反诈禁毒': (
   "LAYOUT: SIX BIG HEXAGON PANEL FRAMES arranged in a honeycomb across the page — two hexagons in a LEFT "
   "column, two in a MIDDLE column set slightly lower, two in a RIGHT column, all of them large with narrow "
   "white gaps between them. Each hexagon has a thick bright frame in a different colour: sky blue, grass "
   "green, orange, golden yellow, red and pink. The whole interior of every hexagon is COMPLETELY EMPTY WHITE "
   "paper ready for a pupil to write into — no fill, no lines, no decoration, no illustration inside. "
   "Along the BOTTOM margin, standing on one clearly drawn ground line, a row of three flat icons, each "
   "touching the ground: a plain shield with a big tick that is NOT crossed out, an upright smartphone with a "
   "small warning triangle, and a round prohibition sign with one diagonal bar over a small poppy seed pod. "
   "In the bottom left corner two small pupils stand on the same ground line, side by side."
 ),
}


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)[:260]}", 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=5) as ex:
        list(ex.map(lambda kv: gen(*kv), items))
