# -*- coding: utf-8 -*-
"""两幅最贴合主题的水彩稿：线条图 + 配色图
作品一《书页上的长征》   —— 长征胜利90周年 + 阅读
作品二《一盏灯，一百零五年》—— 建党105周年 + 阅读
"""
import base64, glob, json, os, sys, 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']
LINE_DIR = '/data/www/files/pandaReadArt/best2/lineart'
CLR_DIR = '/data/www/files/pandaReadArt/best2/color'
os.makedirs(LINE_DIR, exist_ok=True)
os.makedirs(CLR_DIR, exist_ok=True)
SIZE = '2304x1728'          # 4:3 横版

NOTEXT = (" Absolutely NO TEXT anywhere in the image: no letters, no Chinese characters, no numbers, no "
          "calligraphy, no words, no captions, no titles, no labels, no writing on any book page, banner, sign, "
          "plaque or flag — all book pages must show only blank page lines or small pictorial pictures, never "
          "text; no logos, no watermarks, no signature, no seals, no stamps. ")

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 a 9-10 year old can draw, such as page lines, roof tile rows, window frames, wave "
        "ripples, floorboard lines, leaf clumps, star shapes. ABSOLUTELY NO shading, NO cross-hatching, NO "
        "stippling, NO grey tones, NO gradients, NO tonal patches, NO colour fill — outlines only, every area "
        "left pure white. Genuine scene with foreground, middle ground and background, clear overlapping layers "
        "and simple perspective with nearer objects bigger. Characters drawn with simple but expressive faces "
        "(dot eyes, small smile), clear limbs and readable poses. Closed clear shapes, readable silhouettes, "
        "well-balanced wide composition, white margins. ")

T1 = NOTEXT + (
 " A magical reading scene on a grassy meadow. Lower foreground: one enormous open book lying on the grass, "
 "spread wide so that its two open pages form the ground of the picture, with page lines radiating from the "
 "centre spine, grass tufts, small wildflowers and a few five-pointed-star-shaped flowers around its edges. On "
 "the LEFT open page, drawn as a miniature landscape painted on the page itself: two triangular snow-capped "
 "mountains, a small patch of marsh grass, a small three-arch stone bridge and a winding path drawn as a line. "
 "Walking out of that page toward the centre: four cute chibi children dressed as young Red Army soldiers in "
 "blue-grey uniforms, caps with a star and grey puttees, marching in a single line along the open page, the "
 "leading child holding a tall red flag on a pole planted at the page edge; small red triangular flags stuck "
 "along the page edge. On the RIGHT: a nine-year-old girl with a ponytail, round face, dot eyes and a small "
 "smile, wearing a white shirt and a neckerchief triangle on her chest, kneeling on the grass beside the book "
 "with a smaller open book in her hands, leaning forward with a wondering expression, one hand resting on the "
 "big page. Behind the book, the two halves of the big open book rise upward like two wide leaning pages, with "
 "a gap of sky between them. Background: a large round sun with short rays rising in that gap, a few stars, a "
 "distant hill with the silhouette of a nine-tier pagoda on top, two white doves flying, and one long red ribbon "
 "flowing across the whole sky."
) + LINE

T2 = NOTEXT + (
 " A wide landscape arranged as three connected stages along one continuous wavy band of light. LEFT third: a "
 "small traditional Chinese boat with a red hull, a curved wooden roof and a small lantern hanging at its bow, "
 "floating on a calm lake with wave lines, big lotus leaves, two lotus flowers and reeds. MIDDLE third: a green "
 "hill with a nine-tier pagoda on its top and two arched cave dwellings cut into the hillside, short rays of "
 "light drawn coming out of one cave window, three pine trees, terraced field lines. RIGHT third: a corner of a "
 "child's room with a simple wooden desk, a desk lamp with a round shade and a bent arm, a big open book lying "
 "flat on the desk with page lines, a small stack of two books beside it, a mug, and a ten-year-old child with "
 "a ponytail, round face, dot eyes and a smile wearing a neckerchief sitting at the desk reading, one hand on "
 "the page, the lamp shade bent above the book; a low stool, a rug with simple pattern lines on the floor, a "
 "window frame behind. CONNECTING all three stages: one wide wavy double-line band flowing from the boat lantern "
 "through the cave window to the desk lamp, with small radiating glow marks along it. Above: a large sky with a "
 "crescent moon, scattered stars, two small decorative clouds and one red ribbon. Below the band: water ripples "
 "on the left, hillside lines in the middle, floorboard lines on the right. Two white doves flying, a few small "
 "five-pointed-star-shaped flowers."
) + LINE

SCENES = {'1_书页上的长征': T1, '2_一盏灯一百零五年': T2}

# 各作品配色方案
COLORS = {
 '1_书页上的长征': " Colour scheme: fresh grass green meadow with warm yellow-green highlights; the big open book "
                   "with pale cream pages and a warm brown cover edge; the miniature landscape on the left page "
                   "drawn in cool white-and-pale-blue snow mountains, muted green marsh grass and pale grey "
                   "stone; the marching children in faded blue-grey uniforms with red stars on their caps and a "
                   "pure bright red leading flag; the girl's shirt white, her neckerchief and hair ribbon pure "
                   "bright red, hair dark brown, skin warm light; the sky behind the rising pages a soft blue "
                   "fading to warm golden sunrise near the sun; the sun pale yellow with soft golden rays; the "
                   "distant pagoda in muted grey-violet silhouette; small red triangular flags and the long "
                   "flowing ribbon pure bright red; doves white.",
 '2_一盏灯一百零五年': " Colour scheme: a deep blue-violet night sky at the top with a pale cream crescent moon and "
                       "pale yellow stars, and a warm glow low on the horizon; the connecting band of light a "
                       "luminous warm golden yellow with soft halo; LEFT: the lake in soft blue-green, lotus "
                       "leaves in deep green with two pink flowers, the boat hull pure bright red with a warm "
                       "brown curved roof, its small lantern glowing warm yellow; MIDDLE: the hill in warm "
                       "yellow-green with a golden-ochre nine-tier pagoda and dark brown eaves, the cave "
                       "dwellings warm ochre with deep brown doorways and one window glowing warm yellow; RIGHT: "
                       "the room interior in warm cream and pale wood tones, the desk warm brown, the desk lamp "
                       "shade pale cream glowing warm yellow with a soft pool of light falling on the open book's "
                       "pale cream pages, the child's shirt white with a pure bright red neckerchief and dark "
                       "brown hair, the rug deep red with pale pattern, the window showing the dark night sky; "
                       "one red ribbon scrolling through the whole composition; doves white."
}

BASE_INSTR = ("Create the watercolour COLOURED version of this exact line drawing, painted in the style of a "
              "schoolchild's watercolour painting. Keep EXACTLY the same shapes, positions, proportions and "
              "composition — do not add, remove, move or redraw any element. Simply fill the outlined areas with "
              "clean transparent flat watercolour washes that stay neatly inside the black outlines, with the "
              "black outlines still clearly visible on top. Gentle layered washes, soft transparent pooling, "
              "visible watercolour paper grain, warm and luminous. NO text of any kind anywhere — no letters, no "
              "characters, no numbers, no writing on the book pages, no signature, no watermark, no stamp. Keep it "
              "simple and neatly painted: no heavy dark shading, no gradients into black. ")


def gen_line(name, prompt, retries=3):
    for a in range(retries):
        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=200).content
                p = os.path.join(LINE_DIR, f"{name}.jpg")
                open(p, 'wb').write(img)
                print(f"OK line  {name}  {len(img)//1024}KB", flush=True)
                return p
            print(f"ERR {name} #{a}: {json.dumps(d, ensure_ascii=False)[:200]}", flush=True)
        except Exception as e:
            print(f"EXC {name} #{a}: {e}", flush=True)
        time.sleep(6)
    return None


def gen_color(name, strength=0.6, retries=3):
    src = os.path.join(LINE_DIR, f"{name}.jpg")
    b64 = base64.b64encode(open(src, 'rb').read()).decode()
    prompt = BASE_INSTR + COLORS.get(name, '')
    for a in range(retries):
        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,
                      "image": f"data:image/jpeg;base64,{b64}", "strength": strength}, timeout=300)
            d = r.json()
            if d.get('data'):
                img = requests.get(d['data'][0]['url'], timeout=200).content
                p = os.path.join(CLR_DIR, f"{name}.jpg")
                open(p, 'wb').write(img)
                print(f"OK color {name}  s={strength}  {len(img)//1024}KB", flush=True)
                return p
            print(f"ERR {name} #{a}: {json.dumps(d, ensure_ascii=False)[:200]}", flush=True)
        except Exception as e:
            print(f"EXC {name} #{a}: {e}", flush=True)
        time.sleep(6)
    return None


if __name__ == '__main__':
    cmd, names = sys.argv[1], sys.argv[2:]
    names = [n for n in names if n in SCENES] or list(SCENES)
    if cmd == 'line':
        with ThreadPoolExecutor(max_workers=2) as ex:
            print(list(ex.map(lambda n: gen_line(n, SCENES[n]), names)))
    elif cmd == 'color':
        with ThreadPoolExecutor(max_workers=2) as ex:
            print(list(ex.map(gen_color, names)))
